我无法生成不会重复此宾果板的唯一值。我的代码比较简单:我使用嵌套的 for 循环来生成带有一些打印语句的值;在每次嵌套迭代时,我都会检查生成的值是否存在于数组中。如果存在,则返回true,并且生成的值选择一个新的随机数。我认为通过在每次迭代时启动 srand() 并使用循环中的计数作为其种子,我将能够实现这一点。不幸的是,这似乎不太可能。
这是如何实现的?
我的代码:
#define MAX 100
#define MIN 1
using std::vector;
bool Board::checkValues(unsigned int array[], unsigned int valueToCheck)
{
int len = sizeof(array) / sizeof(int);
bool numberExists = false;
static int repeatCount = 0;
for(int i = 1; i < len; i++)
{
if (valueToCheck == array[i])
{
numberExists = true;
repeatCount++;
break;
}
}
return numberExists;
}
Board::Board(unsigned int numberOfRows, unsigned int numberOfColumns)
{
this->numRows = numberOfRows;
this->numColumns = numberOfColumns;
for (int i = 0; i < this->numRows; i++)
{
this->board.push_back(vector<unsigned int>(this->numColumns, 0));
}
this->valuesVisited[numberOfRows * numberOfColumns];
}
void Board::generate()
{
int repeatCount = 0;
for(int i = 0; i < this->numRows; i++)
{
bool atMid = false;
if (i == this->numRows / 2 - 1)
{
atMid = true;
}
for(int j = 0; j < this->numColumns; j++)
{
if (atMid && j == this->numColumns / 2 - 1)
{
printf(" Free ");
continue;
}
int seed = (i + 1) * (j + 1);
unsigned int randNumber = generateRand(MIN, MAX, seed);
bool numberExists = checkValues(this->valuesVisited, randNumber);
if (numberExists)
{
//int equation = (randNumber % 10) + (i * j) / (randNumber + randNumber);
randNumber = generateRand(MIN, MAX, seed) - (i * j);
repeatCount++;
}
this->valuesVisited[(i + 1) * (j + 1)] = randNumber;
this->board[i][j] = randNumber;
printf(" %d ", board[i][j]);
}
std::cout << "\n\n";
}
printf("You have %d repeats", repeatCount);
}