Count pairs Sum in matrices Java
- Get link
- X
- Other Apps
PROGRAM TO COUNT PAIRS FROM TWO SORTED MATRICES WITH GIVEN SUM
import
java.io.*;
class
MAIN
{
int
SIZE =
10
;
// function to count pairs from
// two sorted matrices whose sum
// is equal to a given value x
static
int
countPairs(
int
mat1[][],
int
mat2[][],
int
n,
int
x)
{
// 'r1' and 'c1' for pointing current
// element of mat1[][]
// 'r2' and 'c2' for pointing current
// element of mat2[][]
int
r1 =
0
, c1 =
0
;
int
r2 = n -
1
, c2 = n -
1
;
// while there are more elements
// in both the matrices
int
count =
0
;
while
((r1 < n) && (r2 >= -
1
))
{
int
val = mat1[r1][c1] + mat2[r2][c2];
// if true
if
(val == x) {
// increment 'count'
count++;
// move mat1[][] column 'c1' to right
// move mat2[][] column 'c2' to left
c1++;
c2--;
}
// if true, move mat1[][]
// column 'c1' to right
else
if
(val < x)
c1++;
// else move mat2[][] column
// 'c2' to left
else
c2--;
// if 'c1' crosses right boundary
if
(c1 == n) {
// reset 'c1'
c1 =
0
;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if
(c2 == -
1
) {
// reset 'c2'
c2 = n -
1
;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return
count;
}
// Driver code
public
static
void
main (String[] args)
{
int
mat1[][] = { {
1
,
5
,
6
},
{
8
,
10
,
11
},
{
15
,
16
,
18
} };
int
mat2[][] = { {
2
,
4
,
7
},
{
9
,
10
,
12
},
{
13
,
16
,
20
} };
int
n =
3
;
int
x =
21
;
System.out.println (
"Count = "
+
countPairs(mat1, mat2, n, x));
}
}
OUTPUT
Count = 4
- Get link
- X
- Other Apps
Comments
Post a Comment