d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Horizontal Sum In 2d Array
Add Reply New Topic New Poll
Member
Posts: 1,307
Joined: Apr 9 2007
Gold: 1,676.45
Dec 7 2014 11:36am
Here is what the instructions tell me to do:

public static int[][] horizontalSums(int[][] a, int sumToFind)
This method will create a new output array called b that has the same dimensions as a. For
each a[i][j], where i and j are valid indices in a, if a[i][j] is part of a horizontal sum in a that
equals sumToFind, then b[i][j] = a[i][j]; otherwise, b[i][j] = 0. The method should return b.

I'm a little confused on how I should approach this problem. Any suggestions on how to approach this would be appreciated. I'm guessing I'll need three loops (two to run through the array, then one to switch everything) but not sure how I should structure them.

This post was edited by ice060788 on Dec 7 2014 11:38am
Member
Posts: 1,307
Joined: Apr 9 2007
Gold: 1,676.45
Dec 7 2014 04:16pm
Here is the code I have now

Code
public static int[][] horizontalSums(int[][] a, int sumToFind)
{
int columnStart = 0;
int[][] b = new int[a.length][a[0].length];
while (columnStart < a[0].length)
{
for (int row = 0; row < a.length; row++)
{
int sum = 0;
for (int column = columnStart; column < a[row].length; column++)
{
sum += a[row][column];
if (sum == sumToFind)
{
for(int i=0; i <= row; i++)
{
b[row][column] = a[row][column];
}
}
}
}
columnStart++;
}
return b;
}


This post was edited by ice060788 on Dec 7 2014 04:21pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll