Print unique rows in a given Boolean matrix in C++

In this tutorial, we are going to learn about Print unique rows in a given Boolean matrix in C++. In this tutorial, we have to print the unique rows of the binary matrix. Firstly introduction to the matrix is given. Secondly, code in c++ to solve the problem.

Introduction

Matrix or 2-D array is a data structure in which we can store the data in rows and columns. For the iteration of the matrix, we need two loops which make the insertion in the matrix a bit expensive. The matrix we are going to use today will be of boolean type i.e, it contains only 1’s and 0’s.

In this tutorial, we have to find unique rows in the matrix. There are many ways to solve this problem.

The methods to solve this problem are:




  1. Simple Method: First method is to print to the first row and check every other row by comparing. And printing only unique rows.
  2. Binary Search Tree: Convert the binary values of the matrix into decimals and save the values in nodes with row number. don not insert the duplicate row and keep on inserting. After that traverse the tree and print all the rows.
  3. HashSet data structure: Convert the whole row into a string and insert in the hash table and do not insert duplicate values.

We are going to use the HashSet method here.

C++ program to print unique rows in a given Boolean matrix

#include<bits/stdc++.h>  
using namespace std;  
  
void arrayop(int arr[4][5], int row,  
                              int col)  
{  
    unordered_set<string> uset;  
      
    for(int i = 0; i < row; i++)  
    {  
        string s = "";  
          
        for(int j = 0; j < col; j++)  
            s += to_string(arr[i][j]);  
          
        if(uset.count(s) == 0)  
        {  
            uset.insert(s);  
            cout << s << endl;  
              
        }  
    }  
}  

int main() 
{
    int arr[4][5];
  cout<<"Enter the elements of matrix : ";
  for(int i=0;i<4;i++){
    for(int j=0;j<5;j++){
      cin>>arr[i][j];
    }
  }
      
    arrayop(arr, 4, 5);  
}  

Input and Output:

Enter the elements of the matrix : 0 1 0 1 1
0 0 0 0 0
0 1 0 1 1
1 1 1 0 0
0 0 1 1 1
01011
00000
01011
11100
00111

Also Checkout:

Merge Sort in C++
Find median in row wise sorted matrix in C++


Leave a Reply

Your email address will not be published. Required fields are marked *