I had to make an array that counted the seating in a movie theater, the second class m2 represents another showtime. I do not know how to add both arrays together and print the result of the sum of these two arrays.
This the MovieSeats tester file:
public class MovieSeatsTester
{
public static void main(String[] args)
{
MovieSeats m = new MovieSeats(3,3);
MovieSeats m2 = new MovieSeats(3,3);
m.seating(0,0);
m.seating(0,1);
m.seating(1,0);
m.seating(2,2);
m.seating(2,2);
m2.seating(0,0);
m2.seating(0,0);
m.print();
m.reset();
m2.print();
m2.reset();
}
}
This is the MovieSeats file:
public class MovieSeats
{
private int attendance[][];
public MovieSeats()
{
}
public MovieSeats(int rows, int columns)
{
attendance = new int[rows][columns];
}
public void seating(int r, int c)
{
attendance[r][c] += 1;
}
public void print()
{
for (int r = 0; r < attendance.length; r++)
{
for (int c = 0; c < attendance.length; c++)
{
System.out.println("At row " + r + " col " + c + ", There are " + attendance[r][c] + " Sitting here.");
}
}
System.out.println();
}
public void reset()
{
for (int r = 0; r < attendance.length; r++)
{
for (int c = 0; c < attendance.length; c++)
{
attendance[r][c] = 0;
}
}
System.out.println();
}
}
I assume that by "add two different arrays" you mean "create a third array where each element in the third array is the sum of the corresponding element of each of the first two arrays."
1. Access Each Array
In order to add the two arrays together, you would first need access to each array somehow. Since the attendance field is private, you should add a getter method for it to the MovieSeats class.
Get attendance without encapsulation:
public int[][] getAttendance() {
return attendance;
}
Get attendance with encapsulation:
public int[][] getAttendance() {
int rows = attendance.length();
int cols = attendance[0].length();
int[][] copy = new int[rows][cols];
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
copy[i][j]=current[i][j];
return copy;
}
2. Add Two Arrays Element-Wise
Next, once you have access to both arrays in the same place (probably inside your main), you would then have to add them together. I would recommend putting the result in a third array. The most rudimentary way of adding these two arrays is the following:
int[][] attendance1 = m.getAttendance();
int[][] attendance2 = m2.getAttendance();
int[][] sum = new int[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
sum[i][j] = attendance1[i][j] + attendance2[i][j];
Then, you could print the total attendance by seat with the following:
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
System.out.printf("Total Attendance for seat (%d,%d): %d\n",
i, j, sum[i][j]);
Now, if instead what you want to do is to sum all of the elements of both arrays into a single value, then you would do the following.
Sum An Array
int sum = 0;
int[][] attendance1 = m.getAttendance();
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
sum += attendance1[i][j];
int[][] attendance2 = m2.getAttendance();
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
sum += attendance2[i][j];
You can add the following method to the MovieSeat class:
public int sum() {
int result = 0;
for (int r = 0; r < attendance.length; r++) {
for (int c = 0; c < attendance.length; c++) {
result += attendance[r][c];
}
}
return result;
}
And the call the sum method and find the total sum in the main method:
MovieSeats m = new MovieSeats(3, 3);
MovieSeats m2 = new MovieSeats(3, 3);
m.seating(0, 0);
m.seating(0, 1);
m.seating(1, 0);
m.seating(2, 2);
m.seating(2, 2);
m2.seating(0, 0);
m2.seating(0, 0);
m.print();
System.out.println("sum: " + m.sum());
System.out.println("---");
m2.print();
System.out.println("sum: " + m2.sum());
System.out.println("total sum: " + (m.sum() + m2.sum()));
m.reset();
m2.reset();
Note to reset after you call the sum method.
Related
Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!
My problem is in my basicsMatrixMain.java code, that I do not know how can I print out thre results I get from difference or transpone. Can anybody help me to solve it ?
public class basicsMatrix {
private final int N;
private final int M;
private final double[][] matrix;
public basicsMatrix(int M, int N) {
this.N = N;
this.M = M;
matrix = new double[M][N];
}
public basicsMatrix(double[][] matrix) {
M = matrix.length;
N = matrix[0].length;
this.matrix = new double[N][M];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.matrix[i][j] = matrix[i][j];
}
public void transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
}
public void add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
}
public void difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
public String matrixtostring(double[][] matrix1){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
sb.append(matrix1);
}
}
return sb.toString();
}
}
public class basicsMatrixMain {
public static void main(String[] args) {
int N = 2;
int M = 3;
double[][] matrix1 = { {2, 3, 4}, {5, 2, 3} };
double[][] matrix2 = { {-4, 5, 3}, {5, 6, 3} };
System.out.println("\n");
System.out.print("Difference:");
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
System.out.println();
}
}
}
}
You have defined a lot of functions in basicsMatrix that you can use here.
However there are some changes that you need to make. In your add, difference and transpose methods, you define something but you never save the result. I would recommend something like this:
public double[][] transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
return transpose;
}
public double[][] add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
return osszeadas;
}
public double[][] difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return kivonas;
}
All these functions now return a matrix that you can print out.
Now you just print you matrices. Something like this should work.
System.out.println(matrixtostring(transzponalas(matrix1)));
System.out.println(matrixtostring(add(matrix1,matrix2)));
System.out.println(matrixtostring(difference(matrix1,matrix2)));
Looking at the question description.
"Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!"
I suspect that you are supposed to create a class that calls functions on itself. In other words the basicsMatrix will become your matrix.
For example, the transzponalas method would become
public void transzponalas(){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = this.matrix[i][j];
}
}
int tmp = this.M
this.M = this.N
this.N = tmp
this.matrix = transpose;
}
This way, you change the matrix that is inside your basicsMatrix. You should make sure that you understand the assignment correctly.
I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);
I have a question. Can anyone help me with finding duplicates in submatrices?
I have a code which finds submatrices in 2d matrix, but I can't find duplicates. I thought to push the values onto the Stack (because in assignment I should use Stack), find all duplicates in each submatrix, and then compare them, but I don't really know how to do it. I'll be very gratefull, if anyone help me to finish this program.
My code:
public static void main(String[] args) throws Exception {
int[][] data = new int[3][3];
Random random = new Random();
for(int i=0; i<data.length;i++)
{
for(int j=0; j<data.length; j++)
{
data[i][j] = random.nextInt(10);
}
}
printSubMatrix(data);
}
private static void printSubMatrix(int[][] mat) {
int rows=mat.length;
int cols=mat[0].length;
Stack _stack = new Stack();
//prints all submatrix greater than or equal to 2x2
for (int subRow = rows; subRow >= 2; subRow--) {
int rowLimit = rows - subRow + 1;
for (int subCol = cols; subCol >= 2; subCol--) {
int colLimit = cols - subCol + 1;
for (int startRow = 0; startRow < rowLimit; startRow++) {
for (int startCol = 0; startCol < colLimit; startCol++) {
for (int i = 0; i < subRow; i++) {
for (int j = 0; j < subCol; j++) {
System.out.print(mat[i + startRow][j + startCol] + " ");
_stack.push(mat[i+startRow][j+startCol]);
}
System.out.print("\n");
}
System.out.print("\n");
}
}
}
}
System.out.printf(_stack.toString().replaceAll("\\[", "").replaceAll("]", ""));
}
I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
for(j=0;j
{
if(j>i)
d1+=a[i][j];. // Above the diagon
else
if(i>j)
d2+=a[i][j];. // Below the diagonal
}
I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}