How to make a N×N matrix each of i-th row and i-th column having all the elements 1 to 2N-1?

Ravinder Dudeja

This question was asked as a puzzle in one Book of Puzzles by RS AGGARWAL, which stated the problem as to build an order N matrix where each i'th row and i'th column combined have all the elements from 1 to 2N-1.

For instance, for N=2

[3,2]
[1,3]

I want to know when is an answer possible for it for which values of N it is possible to make a matrix and how to make it? and write code for it

Spektre

this has simple solution for square matrices where n is power of 2 so n=1,2,4,8,16,... do not ask me why there surely is some math proof for it ...

The algorithm to create such matrix is easy:

  1. clear matrix (with 0)

  2. loop i through all values i=1,2,3...2n-1

  3. for each i find all locations where i matrix is not yet filled (0) and there is not i present in row and column

    fill the position with i and repeat until no such location found.

In C++ something like this:

//---------------------------------------------------------------------------
const int n=8;
int m[n][n];
//---------------------------------------------------------------------------
// compute histogram u[n+n] of values per ith row,col of m[n][n]
void hist_rst(int *u                  ) { for (int j=0;j<n+n;j++) u[j]=0; }
void hist_row(int *u,int m[n][n],int i) { for (int j=0;j<n;j++) u[m[j][i]]=1; }
void hist_col(int *u,int m[n][n],int i) { for (int j=0;j<n;j++) u[m[i][j]]=1; }
//---------------------------------------------------------------------------
void matrix_init(int m[n][n])
    {
    int i,x,y,h[n][n+n];
    // clear matrix (unused cells)
    for (x=0;x<n;x++)
     for (y=0;y<n;y++)
      m[x][y]=0;
    // clear histograms
    for (i=0;i<n;i++) hist_rst(h[i]);
    // try to fill values 1..2n-1
    for (i=1;i<n+n;i++)
        {
        // find free position
        for (x=0;x<n;x++) if (!h[x][i])
         for (y=0;y<n;y++) if (!h[y][i])
          if (!m[x][y])
            {
            // set cell
            m[x][y]=i;
            h[x][i]=1;
            h[y][i]=1;
            break;
            }
        }
    }
//---------------------------------------------------------------------------

here few outputs:

  1

  1  3
  2  1

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

for non power of 2 matrices you could use backtracking but take in mind even 4x4 matrix will have many iterations to check ... so some heuristics would need to be in place to make it possible in finite time... as brute force is (n+n)^(n*n) so for n=4 there are 281474976710656 combinations to check ...

[edit1] genere&test solution for even n

//---------------------------------------------------------------------------
const int n=6;
int m[n][n];
//---------------------------------------------------------------------------
// compute histogram u[n+n] of values per ith row,col of m[n][n]
void hist_rst(int *u                  ) { for (int j=0;j<n+n;j++) u[j]=0; }
void hist_row(int *u,int m[n][n],int i) { for (int j=0;j<n;j++) u[m[j][i]]=1; }
void hist_col(int *u,int m[n][n],int i) { for (int j=0;j<n;j++) u[m[i][j]]=1; }
//---------------------------------------------------------------------------
void matrix_init2(int m[n][n])  // brute force
    {
    int x,y,a,ax[(n*n)>>1],ay[(n*n)>>1],an,u[n+n];
    // clear matrix (unused cells)
    for (x=0;x<n;x++)
     for (y=0;y<n;y++)
      m[x][y]=0;
    // main diagonal 1,1,1,1...
    for (x=0;x<n;x++) m[x][x]=1;
    // 1st row 1,2,3...n
    for (x=1;x<n;x++) m[x][0]=x+1;
    // cells for brute force
    for (an=0,x=0;x<n;x++)
     for (y=0;y<x;y++)
      if (!m[x][y])
        {
        ax[an]=x;
        ay[an]=y;
        an++;
        m[x][y]=2;
        }
    // brute force attack values 2,3,4,5,...,n-1
    for (;;)
        {
        // increment solution
        for (a=0;a<an;a++)
            {
            x=ax[a];
            y=ay[a];
            m[x][y]++;
            if (m[x][y]<=n) break;
            m[x][y]=2;
            }
        if (a>=an) break;   // no solution
        // test
        for (x=0;x<n;x++)
            {
            hist_rst(u);
            hist_col(u,m,x);
            hist_row(u,m,x);
            for (y=1;y<=n;y++) if (!u[y]) { y=0; x=n; break; }
            }
        if (y) break;       // solution found
        }

    // mirror other triangle
    for (x=0;x<n;x++)
     for (y=0;y<x;y++)
      m[y][x]=m[x][y]+n-1;
    }
//---------------------------------------------------------------------------

however its slow so do not try to go with n>6 without more optimizations/better heuristics... for now it is using triangle+mirror and diagonal + first row hard-coded heuristics.

maybe somehow exploit the fact that each iterated value will be placed n/2 times could speed this up more but too lazy to implement it ...

Here output for n=6:

[  52.609 ms]
  1  2  3  4  5  6
  7  1  6  5  3  4
  8 11  1  2  4  5
  9 10  7  1  6  3
 10  8  9 11  1  2
 11  9 10  8  7  1

iterating through 5^10 cases ...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I make cron run something every "N"th minute, where n % 5 == 1?

in R: how to take value from i+1th row of 1 dataframe and subtract from every row in i+1th column of 2nd dataframe

N-1th Loop Elements are missing

Adding "i"th elements of each of the inner arrays of an array (2 dimensional) in Python and to make a new array with the addition as the "i"th element

How do I get the nth minus the (n-1)th term from a dataframe in R?

how add the entry ij-th of a matrix to a data Fram who has column i and row j

If I am adding n data in recyclerview it is displaying n-1 data only.it is showing n th data when I add the n+1 th data

Prolog - Return the n-th row of a matrix

How can I move a matrix down by 1 row and 1 column?

Replacing i th column name with the i-1 th column name for a whole data set in R

Compare nth row with n+1 th row and if it lies in range of n th row print n+1th row USNG ORACLE QUERY only

How to make every n'th elements in a list in a list of their own?

How could I increment by 1 every 5th row whenever another row is the same?

Repeat each row n times in a matrix and add a column of 1*n next to each part

How do I average every n columns of each row in a matrix?

How can I add 1s in a python pandas column like row(n)=row(n-1)+1?

Select matrix first row based on 1st, 8th and 9th column value with awk or sed

Create a function that generates a matrix of (n,n) in which the sum of the elements of each column is equal to 1

how I can make column of a matrix equal 1?

matrix: move n-th row by n position efficiently

Counting the numbers between 1 and N (inclusive) where the i-th bit is set

Multiply Matrix element in i-th row by the i-th element in the first row

Pass (i+1) th data in (i)th anchor click in angular2

How can I make 5 column in 1 row with jumbotron bootstrap?

How do I prevent a jQuery function (that reads title attributes on 1st row th's of thead's) to apply retrieved titles to all tables in a document?

How can I get the n-th double precision number

How do I do something every n-th attempt?

How can I acces the N'th object property name?

How can i access N th level of Sub Document in MongoDB

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive