Given two matrix A[][] and B[][] of same order m*n. The task is to find the intersection of both matrix as C, where:
Examples:
Input : A[N][N] = {{2, 4, 6, 8}, {1, 3, 5, 7}, {8, 6, 4, 2}, {7, 5, 3, 1}}; B[N][N] = {{0, 4, 3, 8}, {1, 3, 5, 7}, {8, 3, 6, 2}, {4, 5, 3, 4}}; Output : * 4 * 8 1 3 5 7 8 * * 2 * 5 3 *
As intersection of two set is a set which includes common elements to both set, similarly intersection of two matrix will include only corresponding common element and place “*” at the position of rest unmatching elements.
For finding the intersection of both matrix simply iterate over their size and print * if element at particular position in both matrix are not equal else print the element.
Below is the implementation of the above approach:
# Python 3 program to find intersection # of two matrices N, M = 4, 4 # Function to print the resultant matrix def printIntersection(A, B) : for i in range(M) : for j in range(N) : # print element value for equal # elements else * if (A[i][j] == B[i][j]) : print(A[i][j], end = " ") else : print("* ", end = " ") print() # Driver Code if __name__ == "__main__" : A = [ [2, 4, 6, 8 ], [ 1, 3, 5, 7 ], [ 8, 6, 4, 2 ], [ 7, 5, 3, 1 ] ] B = [ [ 2, 3, 6, 8 ], [ 1, 3, 5, 2 ], [ 8, 1, 4, 2 ], [ 3, 5, 4, 1 ] ] printIntersection(A, B) # This code is contributed by Ryuga
Output:
2 * 6 8 1 3 5 * 8 * 4 2 * 5 * 1
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.