0

Heres a part of my code, I am trying to generate a 2D matrix with random integers between 1-40 that are unique for each row meaning that two rows can have same integer but one row can not have two of the same integers.

i.e. row 1: 1,2,3,4,5,6,7 row 2: 1,2,3,4,5,6,7 this is ok

but this isnt: row1: 1,1,2,3,4,5,6

The user gives count in main which decides how many rows he will fill by himself and the rest of the rows are generated by random.

(no need to check if the user inputted rows are unique or not that is assumed)

In the most inner loop I am trying to check if any of the matrix[i][j] are same as the random number if so the number should be generated again, however right now it doesn't find the duplicates :/ how should I tweak the code to replace duplicates with unique random numbers?


#define MAX_ROWS 5
#define NUM_PER_ROW 7

int doStuff(int count) 
{
    int matrix[MAX_ROWS][NUM_PER_ROW];
    int num=0, cnt=0;

    // fill
    for(int i=0; i < count; i++)
    {
        for(int j=0; j < NUM_PER_ROW; j++) 
        {
            printf(" > ");
            scanf("%d", &num);
            matrix[i][j] = num;
        }
    }

    // fill the rest of the rows with random numbers
    
    for(int i = count; i < MAX_ROWS; i++) 
    {
        for(int j = 0; j < NUM_PER_ROW; j++) 
        {  
            num = rand() % 40 +1;
            int flag = 0;
            for(int k=0; k < NUM_PER_ROW; k++) 
            {
                if(matrix[i][j] == num) 
                {
                    flag = 1;
                    break;
                }
            }
            if(flag != 1) 
            {
                printf("%5d ", num);
                matrix[i][j] = num;
            }
        }
    printf("%d. \n", i);
    }
    return 0;
}

  • Did you read the documentation of [GCC](https://www.gnu.org/software/gcc/) and of [GDB](https://www.gnu.org/software/gdb) ? – Basile Starynkevitch Nov 03 '21 at 12:12
  • 1
    a) Make an array with the possible values 1-40. b) Swap them at random. c) Populate the row with the first `NUM_PER_ROW` elements. Repeat for next row from (b). – Weather Vane Nov 03 '21 at 12:46

0 Answers0