我無法生成唯一不會爲此賓果遊戲主板重複的值。我的代碼相對簡單:我使用嵌套for循環來生成一些打印語句的值;在每次嵌套迭代時,我會檢查數組中是否存在生成的值。如果存在,則返回true,並且生成的值將選擇一個新的隨機數。我認爲通過在每次迭代時啓動srand(),並使用循環中的count作爲它的種子,我將能夠實現這一點。不幸的是,這似乎不太可能。賓果遊戲板:生成唯一值
這是如何實現的呢?
我的代碼:
#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);
}
你在找一個沒有重複的隨機生成器嗎?爲什麼不只是做一個贖金置換,然後迭代地選擇元素? – amit