Write the method:
public int sumRow(int[][] matrix, int row)
that sums row row in the 2D array called matrix.
Given:
public void run()
{
System.out.println(sumRow(new int[][]{{70,93,68,78,83},{68,89,91,93,72},{98,68,69,79,88}}, 2));
System.out.println(sumRow(new int[][]{{1,1,1}, {2,2,2}, {3,3,3}}, 0));
System.out.println(sumRow(new int[][]{{2,4,6,8,10}, {1,2,3,4,5}, {10,20,30,40,50}}, 2));
}
So far I have:
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix.length; j++)
{
sum = sum + matrix[j][i];
}
}
return sum;
}
The outputs I get are 714, 18, and 78 when they should be 402, 3, and 150. What am I doing wrong?
You're currently trying to sum all of the elements in the 2D array when you were asked to sum a specific row within the 2D array. In this case, you only need one for loop to traverse a single row like you would traverse a single array. The loop would start at the first element, matrix[row][0] and run until the last element, matrix[row][matrix[row].length - 1] since matrix[row].length is the number of columns/elements in that specific row of the matrix. Therefore, matrix[row].length - 1 would be the index of the last element in matrix[row]. Here's what it should look like,
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
for(int i = 0; i < matrix[row].length; i++)
{
sum += matrix[row][i];
}
return sum;
}
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
int colSize = matrix[row].length;
for(int j = 0; j < colSize; j++){
sum += matrix[row][j];
}
return sum;
}
HINT
Length of row:
int row = matrix.length;
Length of column :
int col = matrix[0].length;
With Java Streams can be done very elegantly:
public static int sumRow2(int[][] matrix, int row) {
return Arrays.stream(matrix[row]).sum();
}
In the internal loop, modify the condition to:
for(int j = 0; j < matrix[i].length; j++)
and then switch i and j in the sum
there is a problem with your second for loop's condition , matrix.length is the length of first dimension , for the second dimension it looks like matrix[i].length
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
sum = sum + matrix[i][j];
}
}
i prefer to use sum+=matrix[i][j] instead of sum = sum + matrix[i][j]
calculating for one row :
for(int j = 0; j < matrix[row].length; j++){
sum = sum + matrix[row][j];
}
just note that row's range is from 0 to matrix.length-1
You need to reference the second dimension of the array for j.
//ex: first dimension is matrix.length
//second dimension is matrix[any index in the first dimension].length
//and this cycle would continue with more and more [num] on the end
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix**[0]**.length; j++)
{
sum = sum + matrix[j][i];
}
}
return sum;
}
Related
Code:
static void exchangeColumns(int matrix[][])
{
int i;
int n = matrix[0].length;
for (i=0;i<n;i++){
int temp = matrix[i][0];
matrix[i][0] = matrix[i][n-1];
matrix[i][n-1] = temp;
}
}
You are using a wrong way to iterate the multi-dimensional array. Please use the following way to iterate through your array.
for (int i = 0; i < matrix.length; ++i) {
for(int j = 0; j < matrix[i].length; ++j) {
System.out.println(matrix[i][j]); // Here you can place your logic by accessing the array elements
}
}
Given a binary matrix of 0 and 1. Find the longest sequence of 1's either row wise or column wise.
0 0 0 1 0 0
0 0 1 1 0 0
0 0 0 1 0 0
It should return highest count – 3. Help please write this program on Java. I wrote a simple algorithm, but it does not take into account the sequence.
public int columnMaxSequence(int[][] matrix) {
int maxSequence = 0;
int max = 0;
for (int i = 0; i < matrix[0].length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[j][i] == 1) {
max++;
}
}
if (max > maxSequence) {
maxSequence = max;
}
max = 0;
}
return maxSequence;
}
public int rowMaxSequence(int[][] matrix) {
int maxSequence = 0;
int max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 1) {
max++;
}
}
if (max > maxSequence) {
maxSequence = max;
}
max = 0;
}
return maxSequence;
}
/*
Returns the maximum sequence of 1s in a matrix.
*/
public int maxSequence(int[][] matrix) {
int rowMaxSequence = rowMaxSequence(matrix);
int columnMaxSequence = columnMaxSequence(matrix);
if (rowMaxSequence >= columnMaxSequence) {
return rowMaxSequence;
} else {
return columnMaxSequence;
}
}
You should try this out:
void main(int[][] matrix)
{
System.out.println(Math.max(columnMaxSequence(matrix), rowMaxSequence(matrix)));
}
public int columnMaxSequence(int[][] matrix)
{
int max = 0;
for(int i = 0; i < matrix[0].length; i++) // Column Index
{
int tempMax = 0;
for(int j = 0; j < matrix.length; j++) // Row Index
{
if(matrix[j][i] == 1)
{
tempMax = 1;
for(int k = j+1; k < matrix.length; k++)
{
if(matrix[k][i] == 1)
tempMax++;
else break;
}
if(max < tempMax)
max = tempMax;
}
}
}
return max;
}
public int rowMaxSequence(int[][] matrix)
{
int max = 0;
for(int i = 0; i < matrix.length; i++)
{
int tempMax = 0;
for(int j = 0; j < matrix[0].length; j++)
{
if(matrix[i][j] == 1)
{
tempMax = 1;
for(int k = j+1; k < matrix[0].length; k++)
{
if(matrix[i][k] == 1)
tempMax++;
else break;
}
if(max < tempMax)
max = tempMax;
}
}
}
return max;
}
Explanation -
For rowMaxSequence():
The loop goes down the matrix, and i stores the value of each row's index. j stores the index of each element in row i. At (i, j) if the matrix finds a 1, then it counts the number of 1's in that row until it finds a 0 - then it breaks. It keeps checking that row in the same manner, and when the orw is complete, it goes down to the next row.
For columnMaxSequence():
The loop goes across the matrix to the right, and i is the current column's index. j is the element in that column. If (j, i) is a 1, then it counts the 1's below it, until a 0 is found. Then it breaks. It keeps checking the column in this manner, and moves on to the right column.
I'm trying to find the sum of every subarray in a 2D array in Java and store them in a new array. This includes the sums of columns and rows. So far, all I can get down is code that can print out the sum of columns and rows.
I don't care about the complexity. In fact, I want to know the most brute force, obvious answer even if it is O(n^4). I am going to be comparing the subarray sums to a given value to see if that sum exists in the rectangular 2D array.
What I have:
public static void outputArray(int[][] array) {
for (int i = 0; i < array.length; i++){
int sum=0;
for (int j = 0; j < array[0].length; j++){
sum += array[i][j];
}
System.out.println("Print the sum of rows =" + sum);
}
int colSum=0;
for(int col=0;col<array[0].length;col++){
for(int row=0;row<array.length;row++){
colSum+=array[row][col];
}
System.out.println("Sum is "+colSum);
colSum = 0;
}
}
If u don't care about complexity && don't want to store the value then u can do it 0(n^6).
public static void outputArray(int[][] array) {
for(int i = 0; i < array.length; i++){
for(int j = 0; j< array[i].length; j++){
for(int k = i; k < array.length; k++){
for(int l = j; l < array[i].length; l++){
System.out.print("["+i+","+j+"]--->"+"["+k+","+l+"]");
int sum = 0;
for(int x = i; x <= k; x++){
for(int y = j; y<= l; y++){
sum+=array[x][y];
}
}
System.out.println("--->"+sum);
}
}
}
}
}
If u do some optimize like store prefix some then u can do it 0(n^4). With more optimization its possible to solve O(n^3).
Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.
static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};
public double[] columnSum(double [][] array){
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[i].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: "+sum);
index++;
}
return temp;
}
public static void main(String[] args) {
arrayq test = new arrayq();
test.columnSum(initialArray);
}
I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:
Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)
Your outer for loop condition is giving you problems. Here's your loop: -
for (int i = 0; i < array[i].length; i++)
Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.
Since the size of every internal arrays are same, you can change your loop to: -
for (int i = 0; i < array[0].length; i++)
Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.
I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -
public double[] columnSum(double [][] array){
int size = array[0].length; // Replace it with the size of maximum length inner array
double temp[] = new double[size];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`.
}
}
System.out.println(Arrays.toString(temp));
return temp; // Note you are not using this return value in the calling method
}
So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.
This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.
Also note that, I have used Arrays.toString(temp) method to print the array.
Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.
int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum = sum + input[i][j];
}
}
for (int i = 0; i < array[i].length; i++)
for(int i=0;i<size;i++)
i & size must never be change in the loop
So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.
You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.
for (int i = 0, j = 0; i < initialArray[j].length; i++) {
for (; j < initialArray.length; j++) {
System.out.println(i + " " + j);
}
j = 0;
}
And here is your modified program.
public class Main {
static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
public double[] columnSum(double[][] array) {
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[0].length; i++) {
double sum = 0;
for (int j = 0; j < array.length; j++) {
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: " + sum);
index++;
}
return temp;
}
public static void main(String[] args) {
new Main().columnSum(initialArray);
}
}
for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression
try it
public double[] columnSum(double [][] array){
double temp[] = new double[array[0].length];
for (int i = 0; i < array[0].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}