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

Given a number N, place numbers from the range [1, N2] in an NxN matrix such that sum in every row is equal.

Examples:

Input: N = 3
Output: 1 5 9    
        2 6 7    
        3 4 8    
Sum in 1st row: 15
Sum in 2nd row: 15 
Sum in 2nd row: 15 

Input: N = 5
Output: 1 7 13 19 25    
        2 8 14 20 21    
        3 9 15 16 22    
        4 10 11 17 23    
        5 6 12 18 24    

A Greedy Approach has been used to fill the matrix, where the insertion of elements in the matrix is done row-wise. The required matrix can be obtained using below steps:

  • Fill the matrix initially with numbers in the range [1, N2] using matrix traversal.
  • Traverse the matrix and change every position in a new matrix considering it as answer matrix by answer[i][j] = mat[j][(i+j)%n].

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to distribute n^2 numbers to n people
public class Numbers {
    public static int[][] solve(int[][] arr, int n)
    {
        // 2D array for storing the final result
        int[][] ans = new int[n][n];
  
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // using modulo to go to the firs
                // column after the last column
                ans[i][j] = arr[j][(i + j) % n];
            }
        }
        return ans;
    }
    public static void show(int[][] arr, int n)
    {
        int[][] res = solve(arr, n);
        for (int i = 0; i < n; i++) {
  
            for (int j = 0; j < n; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }
    // making a 2D array containing numbers
    public static int[][] makeArray(int n)
    {
        int[][] arr = new int[n][n];
        int c = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                arr[i][j] = c++;
        }
        return arr;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int n = 5;
        int[][] arr = makeArray(n);
        show(arr, n);
    }
}

chevron_right


Output:

1 7 13 19 25 
2 8 14 20 21 
3 9 15 16 22 
4 10 11 17 23 
5 6 12 18 24


My Personal Notes arrow_drop_up

IT undergrad

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.