In: Computer Science
Implement a method/function in java that produces running sum
runningSum2DArray(int[][] array, int dir) across rows (left to right or right to left) or columns (top to bottom or bottom to top)
Input to the method: A 4x4 two dimensional int array and an integer (1, 2, 3 or 4 for left, right, up,down respectively).
Output: The modified array after producing the running sums according to the direction.
For example: If the input to the method is the same as the earlier array, and if the direction is 2 (right), the output array would be printed as:
10 25 55 95
15 20 28 30
20 22 26 28
1 5 10 10
Now, implement another function runningSum2DArrayList(ArrayList< ArrayList< Integer > > list, int dir) that performs the same functionality.
For the above things, we need to have the following things into consideration.
Following is the code for the same.
import java.util.ArrayList;
public class FindingTheSums {
public static void Sum2DArray(int arr[][], int dir)
{
if(dir == 1)
{
// Left
for(int
i=0;i<arr.length;i++) {
for(int j = arr[0].length-2;j>=0;j--) {
arr[i][j] = arr[i][j+1] +
arr[i][j];
}
}
}
else if(dir == 2)
{
// right
for(int i =
0;i<arr.length;i++) {
for(int j = 1;j<arr[0].length;j++) {
arr[i][j] = arr[i][j-1] +
arr[i][j];
}
}
}
else if(dir == 3)
{
// top
for(int j =
0;j<arr[0].length;j++) {
for(int i = arr.length-2;i>=0;i--) {
arr[i][j] = arr[i][j] +
arr[i+1][j];
}
}
}
else
{
// down
for(int j =
0;j<arr[0].length;j++) {
for(int i = 1;i<arr.length;i++) {
arr[i][j] = arr[i][j] +
arr[i-1][j];
}
}
}
}
public static void print(int arr[][]) {
for(int i = 0 ;i<arr.length;i++)
{
for(int j =
0;j<arr[0].length;j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public static void main(String args[]) {
int arr[][] = {{10, 15, 30,
40},{15, 5, 8, 2},{20, 2, 4, 2},{1, 4, 5, 0}};
Sum2DArray(arr, 2);
print(arr);
}
}
Following is the output snippet of the above program.
That was a nice
question to answer
Friend, If you have any doubts in understanding do let me know in
the comment section. I will be happy to help you further.
Please like if you think effort deserves like.
Thanks