-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSumOf2DArray
108 lines (93 loc) · 2.48 KB
/
SumOf2DArray
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//You are given two matrices (2D array). The first array A (n rows and m columns) and second array B (i rows and j columns).
//Output sum of the matrix which is greater than the sum of other matrix.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
// first matrix
int sumOfA=0;
int n=sc.nextInt();
int m=sc.nextInt();
sc.nextLine();
int[][] A=new int[n][m];
for(int a=0; a<n;a++){
for(int b=0; b<m; b++){
A[a][b]=sc.nextInt(); //i can also add the element here and comapre later rather using two more loop
}
}
sc.nextLine();
// second matrix
int sumOfB=0;
int i=sc.nextInt();
int j=sc.nextInt();
sc.nextLine();
int[] [] B=new int[i][j];
for(int k=0; k<i; k++){
for(int l=0; l<j; l++){
B[k][l]=sc.nextInt();
}
}
// first matrix sum
int sumOfA=0;
for(int a=0; a<n; a++){
for(int b=0; b<m; b++){
sumOfA=sumOfA+A[a][b];
}
}
//second matrix sum
int sumOfB=0;
for(int k=0; k<i; k++){
for(int l=0; l<j; l++){
sumOfB=sumOfB+B[k][l];
}
}
if(sumOfA>sumOfB){
System.out.println(sumOfA);
}
else{
System.out.println(sumOfB);
}
}
}
/*
Other Solution
//You are given two matrices (2D array). The first array A (n rows and m columns) and second array B (i rows and j columns).
//Output sum of the matrix which is greater than the sum of other matrix.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
// first matrix
int sumOfA=0;
int n=sc.nextInt();
int m=sc.nextInt();
sc.nextLine();
int[][] A=new int[n][m];
for(int a=0; a<n;a++){
for(int b=0; b<m; b++){
A[a][b]=sc.nextInt(); //i can also add the element here and comapre later rather using two more loop
sumOfA=sumOfA+A[a][b];
}
}
sc.nextLine();
// second matrix
int sumOfB=0;
int i=sc.nextInt();
int j=sc.nextInt();
sc.nextLine();
int[] [] B=new int[i][j];
for(int k=0; k<i; k++){
for(int l=0; l<j; l++){
B[k][l]=sc.nextInt();
sumOfB=sumOfB+B[k][l]; // calculating sum here only
}
}
if(sumOfA>sumOfB){
System.out.println(sumOfA);
}
else{
System.out.println(sumOfB);
}
}
}
*/