Place N^2 numbers in matrix such that every row has an equal sum in C++


In this problem, we are given an integer value N. our task is to print numbers within the range (1, N2) in a 2D matrix of size NxN in such a way that the sum elements of each row are equal.

Let’s take an example to understand the problem,

Input − N = 4

Output

1 6 11 16
2 7 12 13
3 8  9 14
4 5 10 15

Sum of elements in each row is 34

To solve this method, we need to place each element in the matrix in such a way that the total in each row is equal. For this, we will use the greedy approach and row by row to place the correct elements in place making the sum equal.

For this, we will initially feed all elements in the matrix and then create a new matrix that has elements of the previous matrix using this formula,

resultMat[i][j] = prevMat[j][(i+j)%n]

Example

The below code shows the implementation of our solution,

 Live Demo

#include<iostream>
using namespace std;
   int main(){
   int n = 4,i,j;
   cout<<"Matrix of size : "<<n<<" in which sum of elements of all rows is equal is :\n";
   int prevMat[n][n], resultMat[n][n] ;
   int c = 1;
   for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++)
      prevMat[i][j] = c++;
   }
   for (i = 0; i < n; i++) {
      for (<) {
         resultMat[i][j] = prevMat[j][((i+j)%n)];
      }
   }
   for (i = 0;i<n;i++) {
      for (j=0; j<n; j++) {
         cout<<resultMat[i][j]<<"\t";
      }
      cout<<endl;
   }
}

Output

Matrix of size : 4 in which sum of elements of all rows is equal is :
1 6 11 16
2 7 12 13
3 8  9 14
4 5 10 15

Updated on: 17-Apr-2020

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements