Sunday, September 29, 2019

C++: Find all the unique elements in a matrix

We are given a matrix of any dimension and wee need to print all the elements that are unique i.e appearing only once. So here is the c++ code for the algorithm.

Output:
The unique elements in the matrix are 4 6 9

Explanation:

First, in the 'main' function, we create the matrix 'mat' of size 4 with 16 elements. Then we call the function 'uniqueElement' with the matrix 'mat' as the parameter. Note, at the top of the program, we have defined R(row) as 4 and C(col) as 4.

In the function 'uniqueElement', we first declare a map 'cnt' of integer type. Then we loop through all the elements of the matrix and increment the frequency of all the elements using 'cnt[mat[i][j]++'. After the loop, all the elements in the matrix will be mapped to its corresponding frequency.

After this, we loop through the map 'cnt' and print the elements with frequency 1.

No comments:

Post a Comment