vendredi 15 septembre 2017

generate a 2d array of integers from given sums of its rows and columns

I want to generate an array of integers where the total sum of each row and column in the array is known , for example if I create a 4 by 4 array in c++ and then populate it pseudo randomly with numbers between 1 and 100:

int array[4][4] = {} ;
for(int x = 0 ; x<4 ; x++){
   for(int y = 0 ; y<4 ; y++){
      array[x][y] = rand() % 100 + 1 ;
   }
}

the array would be :

 8, 50, 74, 59
31, 73, 45, 79
24, 10, 41, 66
93, 43, 88,  4

then if I sum each row and each column by :

int rowSum[4] = {} ; 
int columnSum[4] = {} ; 
for(int x = 0 ; x < 4; x++){
    for(int y = 0 ; y < 4; y++){
        rowSum[x] += array[x][y] ;
        columnSum[y] += array[x][y] ;
    }
}

the rowSum would be {191,228,141,228} and the columnSum = {156,176,248,208}

what I'm trying to do at this point is to generate any random 4x4 1~100 array that will satisfy rowSum and columnSum I understand there is thousands of different arrays that will sum up to the same row and column sum ,and I've been trying to write the part of the code that will generate it , I would really appreciate it if anyone can give me a clue .




Aucun commentaire:

Enregistrer un commentaire