Shuffle a matrix elements in C++

In this tutorial, we will learn how to shuffle matrix elements in C++.

To do this we should know how to do randomization in C++.

Generating a random number in C++

We will use the rand() function in C++ to generate random numbers.

It generates random numbers in between 0 and RAND_MAX(It is a constant which is the maximum value returned by the rand function).

Let’s see an example to see the working of the rand function.

//this generates a random number in the range 0 to 9
r1 = rand() % 10;

//this generates a random number in the range 1 to 9 
r2 = 1+rand() % 10;

 

Now using this we will solve our main problem.

In the given code we are taking the input from the user i.e. dimensions of the matrix and the elements of the matrix.

To shuffle the matrix we are going to initialize two variables: row index and col index.

These are going to get a random value that lies between 0 and  (number of rows, number of columns).

Now we are going to swap/shuffle the matrix using a flag variable.

C++ Code to shuffle matrix elements:

#include<iostream>
#include<time.h>
using namespace std;
 
 
 
int main ()
{
  int n_rows,n_columns;
  cout<<"Enter the dimensions of the matrix: ";
  cin>>n_rows>>n_columns;

  int mat[n_rows][n_columns], flag,i,j;
  cout<<"Enter the elements of the matrix: "<<endl;
  for ( i=0;i<n_rows;i++) 
   for ( j=0;j<n_columns;j++) 
      { 
      cout<<"mat["<<i<<","<<j<<"]=";cin>>mat[i][j]; 
      } 

  cout<<"The given matrix is: "<<endl;
  for(i=0;i<n_rows;i++){
   for(j=0;j<n_columns;j++){
     cout<<mat[i][j]<<" ";
   }
   cout<<endl;
   }

int rowindex=rand()%n_rows;
int colindex=rand()%n_columns;

for(i=0;i<n_rows;i++)
   for(j=0;j<n_columns;j++)
      {
      flag=mat[i][j];
      mat[i][j]=mat[rowindex][colindex];
      mat[rowindex][colindex]=flag;
      }

cout<<"The matrix after shuffling is: "<< endl;
for(i=0;i<n_rows;i++){
    for(j=0;j<n_columns;j++)
      cout<<mat[i][j]<<" ";
    cout<<endl; 
}
      

return 0;
}

 

Input:

Enter the dimensions of the matrix: 3 3
Enter the elements of the matrix:
mat[0,0]=1
mat[0,1]=2
mat[0,2]=3
mat[1,0]=4
mat[1,1]=5
mat[1,2]=6
mat[2,0]=7
mat[2,1]=8
mat[2,2]=9
The given matrix is:
1 2 3
4 5 6
7 8 9

Output:

The matrix after shuffling is:
8 1 2
3 4 5
6 9 7

In this way, we can shuffle matrix elements in C++.

Leave a Reply

Your email address will not be published.