我希望在列和行中具有不同的值.值可以重复,但不能重复三次

  • 本文关键字:但不能 三次 我希望 arrays
  • 更新时间 :
  • 英文 :


我希望9x9的GRID具有1-5范围内的不同值它正在生成值,但我三次都得到了相同的值

例如
3 3 5 3 4 5 3 2
5 1 1 1 1 5 3 5 5 5 5
1 3 1 4 3 1 2 2 2
5 2 1 5 2 1 4 5 4 2
2 5 5 3 1 3 5 4 4 2
1 5 5 4 3 2 2 2 2 1 3 3 1 1 1 2 1 1 1

值一起重复三次

我的代码:

int GridArr[9][9]={0};

srand(time(0));
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
GridArr[i][j] = 1 + rand() % ((5 + 1) - 1);
if (GridArr[i][j] == GridArr[i+2][j] || GridArr[i][j] == GridArr[i][j+2])
{
srand(time(0));
GridArr[i][j] = 1 + rand() % ((5 + 1) - 1);
}
cout << GridArr[i][j] << " ";
}
cout << endl;
}

首先,重复值在随机采样中是完全正常的。关于随机性的真实本质,有很多学术研究,而人类认为的随机性并不是很随机。如果你感兴趣的话,读一下随机性。

无论如何,对于您的特殊情况,我理解您不希望>垂直或水平重复2次,对吗?

首先,您需要在水平方向和垂直方向上检查前面的两个值。在您的代码中,您似乎在向前看(i+2和j+2(,而不是向后看,换句话说,您正在与尚未设置的值进行比较。此外,您只检查前面两个正方形的值,而不是前面两个方块的值。

看起来你是用c++编码的,对吧?我已经很长时间没有用c++进行编码了,所以这可能不是最有效的方法,但我在您的代码中添加了一个";禁止数字";(之前水平或垂直为2(,并将这些值添加到地图中。然后,我将该映射传递给数字生成器,该生成器从一组值中选择,这些值包括除映射中的数字之外的所有数字。希望这是有道理的!

#include <iostream>
#include <map>
using namespace std;
int getRandomNumber(map<int, bool> forbiddenNumbers);
int main()
{
int GridArr[9][9] = { 0 };

srand(time(0));

for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
// this map will keep track of which numbers we don't want for this grid position
map<int, bool> forbiddenNumbers;

// check horizontal
if (i > 1 && GridArr[i-2][j] == GridArr[i-1][j]) {
forbiddenNumbers[GridArr[i-2][j]] = true;
}
// check vertical
if (j > 1 && GridArr[i][j-2] == GridArr[i][j-1])
{
forbiddenNumbers[GridArr[i][j-2]] = true;
}

// pass map of forbidden numbers to number generator
GridArr[i][j] = getRandomNumber(forbiddenNumbers);
cout << GridArr[i][j] << " ";
}
cout << endl;
}
}
int getRandomNumber(map<int, bool> forbiddenNumbers) {
int allowedValues[5 - forbiddenNumbers.size()];

int pos = 0;
for (int i = 1; i < 6; i++) {
if (forbiddenNumbers.count(i) > 0) {
// if this number is forbidden, don't add it to the allowed values array
continue;
}
allowedValues[pos] = i;
pos++;
}

// return a value from the allowed values
return allowedValues[rand() % pos];
}

相关内容

最新更新