arraysmatrixrandomtype-2-dimensionnon-repetitive

Selecting Non-Repeating Random Elements of 2 Dimensional Array in C


I'm pretty new to programming, so the solution needs to be simple. What I need to do is generate an 8x8 matrix, and, because of what I'll be doing with it later, I need to set all the elements equal to 0. Then, I need to select 20 of the elements randomly (without picking the same one twice) and change those elements to 1. With what I have now, I usually print 15 to 18 "1's" every time. Meaning 2 to 5 repeats. That in itself seems weirdly consistent to me, so I suspect there must be something bigger that I'm missing. I've seen other posts similar talking about randomizing possible elements and then selecting from that list, but the code needed to do that is a little over my head at this point.

Is there something flawed with my approach here?

int Board[8][8];
    int x, y, i, a, b;
    for (x = 0; x < 8; x++)
    {
        for (y = 0; y < 8; y++)
            Board[x][y] = 0;     //配列の定義
    }
        srand(time(NULL));     //任意なマスを1に設定
        for (i = 0; i < 20; i++)
        { 
                a = rand() % 8;
                b = rand() % 8;

                Board[a][b] = 1;
        }
    //盤面の出力
    for (x = 0; x < 8; x++)
    {
        for (y = 0; y < 8; y++)
            printf("  %d ", Board[x][y]);
        printf("\n");
    }

Solution

  • You could insert a do-while loop repeating the random number generation in case an existing pair is generated. Such as:

    int Board[8][8];
    int x, y, i, a = 0, b = 0;
    for (x = 0; x < 8; x++)
    {
        for (y = 0; y < 8; y++)
            Board[x][y] = 0;     //配列の定義
    }
        srand(time(NULL));     //任意なマスを1に設定
        for (i = 0; i < 20; i++)
        { 
                /* Repeat until found a '0'-valued cell*/
                do {
                    a = rand() % 8;
                    b = rand() % 8;
                } while(Board[a][b] == 1);
    
                Board[a][b] = 1;
        }
    //盤面の出力
    for (x = 0; x < 8; x++)
    {
        for (y = 0; y < 8; y++)
            printf("  %d ", Board[x][y]);
        printf("\n");
    }