Skip to content

Commit a918951

Browse files
committed
Solution to calculate the sum of rows and columns in an ArrayList
1 parent 60f04c9 commit a918951

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package Scaler.Assignments;
2+
3+
import java.util.ArrayList;
4+
5+
public class RowAndColumnSums {
6+
public static void main(String[] args) {
7+
8+
ArrayList <Integer> l1 = new ArrayList<Integer>();
9+
l1.add(1);
10+
l1.add(2);
11+
12+
/*
13+
[[1,2],
14+
[3,4],
15+
[5,6]
16+
]
17+
* */
18+
19+
ArrayList <Integer> l2 = new ArrayList<Integer>();
20+
l2.add(4);
21+
l2.add(5);
22+
23+
ArrayList <Integer> l3 = new ArrayList<Integer>();
24+
l3.add(8);
25+
l3.add(9);
26+
27+
ArrayList<ArrayList<Integer>> x = new ArrayList<ArrayList<Integer>>();
28+
x.add(l1);
29+
x.add(l2);
30+
x.add(l3);
31+
32+
ArrayList<Integer> z = calculateRowAndColumnSum(x);
33+
System.out.println("Arraylist with Row and Column Sum is " + z);
34+
35+
}
36+
37+
static ArrayList<Integer> calculateRowAndColumnSum(ArrayList<ArrayList<Integer>> A) {
38+
39+
ArrayList <Integer> finalArrayList = new ArrayList<Integer>();
40+
41+
int sizeOfArrayList = A.size();
42+
43+
int columnSize = A.get(0).size();
44+
45+
46+
for (int i = 0; i < sizeOfArrayList; i++) {
47+
int rowSum = 0;
48+
49+
ArrayList<Integer> rowList = A.get(i);
50+
51+
for (int j = 0; j < rowList.size(); j++) {
52+
rowSum = rowSum + rowList.get(j);
53+
}
54+
finalArrayList.add(rowSum);
55+
}
56+
57+
/*
58+
[[1,2],
59+
[4,5],
60+
[8,9]
61+
]
62+
* */
63+
64+
for (int k = 0; k < columnSize; k++) {
65+
int columnSum = 0;
66+
67+
for (int l = 0; l < sizeOfArrayList; l++) {
68+
columnSum = columnSum + A.get(l).get(k);
69+
}
70+
System.out.println("columnSum is " + columnSum);
71+
finalArrayList.add(columnSum);
72+
}
73+
74+
return finalArrayList;
75+
}
76+
}

0 commit comments

Comments
 (0)