Count pairs Sum in matrices Python
- Get link
- X
- Other Apps
PROGRAM TO COUNT PAIRS FROM TWO SORTED MATRICES WITH GIVEN SUM
SIZE
=
10
# function to count pairs from two sorted matrices
# whose sum is equal to a given value x
def
countPairs(mat1, mat2, n, x):
# 'r1' and 'c1' for pointing current element
# of mat1[][]
# 'r2' and 'c2' for pointing current element
# of mat2[][]
r1
=
0
c1
=
0
r2
=
n
-
1
c2
=
n
-
1
# while there are more elements
# in both the matrices
count
=
0
while
((r1 < n)
and
(r2 >
=
-
1
)):
val
=
mat1[r1][c1]
+
mat2[r2][c2]
# if true
if
(val
=
=
x):
# increment 'count'
count
+
=
1
# move mat1[][] column 'c1' to right
# move mat2[][] column 'c2' to left
c1
+
=
1
c2
-
=
1
# if true, move mat1[][] column 'c1' to right
elif
(val < x):
c1
+
=
1
# else move mat2[][] column 'c2' to left
else
:
c2
-
=
1
# if 'c1' crosses right boundary
if
(c1
=
=
n):
# reset 'c1'
c1
=
0
# increment row 'r1'
r1
+
=
1
# if 'c2' crosses left boundary
if
(c2
=
=
-
1
):
# reset 'c2'
c2
=
n
-
1
# decrement row 'r2'
r2
-
=
1
# required count of pairs
return
count
# Driver program to test above
mat1
=
[ [
1
,
5
,
6
] ,[
8
,
10
,
11
],[
15
,
16
,
18
]]
mat2
=
[[
2
,
4
,
7
],[
9
,
10
,
12
],[
13
,
16
,
20
]]
n
=
3
x
=
21
print
(
"Count ="
,countPairs(mat1, mat2, n, x))
OUTPUT
Count = 4
- Get link
- X
- Other Apps
Comments
Post a Comment