c++ - 选择一个随机方 block 并生成一个随机数

标签 c++ c random

我有一 block 4 x 4 的棋盘(16 个方 block 的值为 0)。我必须在这个棋盘上随机选择一个方 block ,并为这个方 block 生成一个随机值。

这是我的代码

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sys/time.h>

using namespace std;

void pickSquare(int [][4]);
void printSquare(int [][4]);

int main() {
    int a[4][4];
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            a[i][j] = 0;

    for (int i = 0; i < 10; i++)
    {
        cout << endl << i << endl;
        pickSquare(a);
        printSquare(a);
    }
}

void pickSquare(int a[][4]) {
    struct timeval t1;
    gettimeofday(&t1, NULL);
    srand(t1.tv_usec * t1.tv_sec);

    int randValue = rand() % 10;
    if (randValue == 0 || randValue == 1) randValue = 4;
    else randValue = 2;

    int count = 0;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            if (a[i][j] == 0) ++count;
    int random = rand() % count;

    cout << endl << "count = " << count;
    cout << endl << "random = " << random;


    count = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++)
            if (a[i][j] == 0) {
                if (count == random) {
                    a[i][j] = randValue;
                    cout << endl << "  " << i << "  " << j << endl;
                    break;
                }
                ++count;
            }       
        if (count == random) break;
    }
}

void printSquare(int a[][4]) {
    cout << endl;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++)
            cout << a[i][j] << "  ";
        cout << endl;
    }
}

函数 pickSquare(int [][4]) 用于选择一个随机方 block 并生成一个随机值。 函数 printSquare(int [][4]) 用于打印 4 x 4 的棋盘。

我认为一切都很好,但是当我运行我的程序时,有时程序不会选择任何正方形。因此完成功能后,板子还是老样子。

谁能解释一下为什么?

最佳答案

我觉得问题是

if (count == random) break;

在这里,您可以在内部循环完成时跳出一个未经测试的计数。

关于c++ - 选择一个随机方 block 并生成一个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978710/

相关文章:

c - c语言中枚举字段有默认值吗

python - 为什么在使用集合创建随机字符串时会出现该模式?

C++模拟按下等号(=)和问号(?)

c++ - 想要在 istream C++ 的行尾读取重要的 double 值

c - C 编程中的段错误(核心转储)

c - c中输入数字的总和

c - 为什么当我在两台机器上同时用 C 语言运行 rand() 时,我得到了相同的结果?

python |避免从列表中随机选择先前的值

c++ - 延迟函数调用,如何传递参数?

c++ - 在 C++11 中访问 move 对象时发出警告