0

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");
    }
rgolden
  • 149
  • 1
  • 6
  • Be wary of the call to `srand()` in the code. You should normally only call it once in a program. There is a good SO Q&A on the topic, but I don't have it bookmarked in the SO app. – Jonathan Leffler Jul 10 '16 at 22:05

2 Answers2

1

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");
}
Lorenzo Addazi
  • 325
  • 3
  • 12
0

rand()%8 will always return values from 0-7 in both of your lines for a and bas you may be knowing. So it may happen that it returns like (6,6) twice. The number of repetitions scaling upto five is a bit weird really when you are iterating over only 20 times. But only twice shows you are doing good too.

You can try this

a=rand()%8; b=(a+(i%8))%8;

Or if you want to be pitch-perfect, make a list of pairs of (a,b) and every time your original code generates a pair, you match it with the list to see if it is unique and then only you add it to the list and increment your loop counter.

Aakash Verma
  • 3,705
  • 5
  • 29
  • 66