[英]Generating Unique Random Numbers in Arrays C++
我已經在其中編碼了3個隨機整數的數組。 關鍵是,盡管我希望3個隨機整數彼此不同(唯一的隨機數)。 我的問題是,即使數字是唯一的,我仍然會從中得到“不好的”讀數。 我用時間(NULL)播種隨機數,因此,我在每個聲明之間放置了一個Sleep(x)函數以增加數字的多樣性。 以下代碼是main()函數中的所有代碼。 出於測試目的,我沒有在代碼中包含break語句,因此可以反復測試程序。
srand((unsigned)time(NULL));
while(true)
{
//Generate 3 numbers
int a = rand() % 7 + 1;
Sleep(1000);
int b = rand() % 8 + 1;
Sleep(1000);
int c = rand() % 9 + 1;
int array[3] = { a , b , c };
//Check the numbers to make sure none of them equal each other
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "bad" << endl;
system("pause");
system("cls");
}
else
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "good" << endl;
system("pause");
system("cls");
}
}
system("pause");
return 0;
當前檢查的問題是它檢查由隨機值表示的索引 ,而不是前三個元素的隨機值本身。
只需更換
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
與
if( (array[0] == array[1]) || (array[0] == array[2]) || (array[1] == array[2]) )
要不就
if(a == b || a == c || b == c)
似乎您正在使用Sleep
,這是Windows特定的功能,與C庫無關。 srand
影響rand()
返回的序列,如果給srand()
相同的種子,則該序列是可重復的。
其次,您存儲在a
, b
和c
的隨機數范圍可能會導致在此行中超出范圍的數組訪問:
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
array
只有3個元素,但是a
, b
和c
值可以更高。
由於您使用的是C ++,因此請考慮利用C ++標准庫。
首先創建一個指定大小的向量,並使用std::iota
將其填充為[0,10)范圍內的值。
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 0);
然后,我們使用std::random_shuffle
重新排列值。
std::random_shuffle (v.begin(), v.end());
並選擇前三個值:
for (int i = 0; i < 3; ++i)
std::cout << v[i] << " ";
我會做這樣的事情:
int a = rand() % 7 + 1;
int b = rand() % 8 + 1;
while( a == b )
b = rand() % 8 + 1;
int c = rand() % 9 + 1;
while(( a == c ) || ( b == c ))
c = rand() % 9 + 1;
int array[3] = { a , b , c };
您檢查的“不良價值”應為:
如果((a == b)||(a == c)||(b == c))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.