Count rows in a matrix that consist of same element in C++

C++Server Side ProgrammingProgramming

We are given a matrix consisting of integers. The goal is to find the number of rows in the matrix that have all identical elements in it.

If there is 5X4 matrix as shown −

15131
11111
53235
77777

The answer would be 2, row 1 (having all 1’s) and row 3 (having all 7’s) contain the same element.

Let us understand with examples.

Input 

matrix =
   [ 1 1 1 1 ]
   [ 2 3 2 7 ]
   [ 3 3 3 3 ]

Output − Count of rows in a matrix that consist of same element are − 2

Explanation − Row 0 contains all 1’s and row 2 contains all 3s.

Input

matrix =
   [ 1 2 3 4 ]
   [ 1 2 3 4 ]
   [ 1 2 3 4 ]

 Output − Count of rows in a matrix that consist of same element are − 0

Explanation − All rows have different elements.

Approach used in the below program is as follows

We are taking the matrix in the form of a vector of vectors<int>. We will traverse each vector and create a set<int> for each row. Keep on inserting row elements to this set. In the end if this set has only 1 element (take set size). Then the current row has all the same elements.

  • Take the matrix as a vector < vector <int> > matrix and initialize it

  • Calculate size using matrix.size().

  • Function same_rows(vector<vector<int>> matrix, int size) takes the matrix and it’s size and returns the count of rows that have the same elements.

  • Take the initial count as 0.

  • Traverse the matrix using for loop. i=0 to i=size.

  • For each row traverse from j=0 to j<matrix[i].size().

  • Take a set<int> set_row for storing elements of current row.

  • Add elements to this set for current row using set_row.insert(matrix[i][j]).

  • At the end check the size of set_row. If it is 1 then this row has all the same elements. Increment count.

  • At the end of all iterations for all rows, return count as the final result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int same_rows(vector> matrix, int size){
   int count = 0;
   for (int i = 0; i < size; i++){
      set set_row;
      for (int j = 0; j < matrix[i].size(); j++){
         set_row.insert(matrix[i][j]);
      }
      int set_size = set_row.size();
      if (set_size == 1){
         count++;
      }
   }
   return count;
}
int main(){
   vector<vector<int>> matrix = {
      { 2, 2, 2, 2},
      { 5, 5, 5, 5 },
      { 2, 2, 2, 2 },
      {5, 5, 5, 5}
   };
   int size = matrix.size();
   cout<<"Count of rows in a matrix that consist of same element are: "<<same_rows(matrix, size);
   return 0;
}

Output

If we run the above code it will generate the following output − 

Count of rows in a matrix that consist of same element are: 4

 

raja
Published on 01-Dec-2020 12:47:54
Advertisements