Saturday, March 17, 2012

Unique Rows in a Matrix.


Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrays
eg:
0 1 0 0 1
1 0 1 1 0
0 1 0 0 1
1 1 1 0 0
ans:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0


Approach:
1. Build a String from each row of the matrix, where each element is separated from another by a space.
2. store the string in a hashset.
3. in the end read the hashset and construct the matrix, the rows would be the unique ones.


Code input/output:
Input matrix is: 
0 1 0 0 1 
1 0 1 1 0 
0 1 0 0 1 
1 1 1 0 0 
Unique Rows are: 
0 1 0 0 1 
1 1 1 0 0 
1 0 1 1 0 

No comments:

Post a Comment