特定のゲームのコードの一部として、ベクトルに4つの一意の乱数を生成したいとします。ベクトルに一意の乱数を挿入する
このコードは、繰り返し再生された後、アプリケーションがクラッシュする(応答しない)場合に機能します。
if-conditionはfor-loopが同じ数字をベクトルに挿入するのを防ぐが、rand()
経由で一意の数字を生成するまで、for-loopにかかる時間はどのくらいかかりますか? どのようにsrand(time(NULL))
とrand()
は、システム時間に応じてランダムな値を作成するために一緒に動作しますか?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
//plays bulls and cows
int main() {
srand(time(NULL));
string play="yes";
int nums=4; // number of values in an answer (must NOT exceed 10)
vector<int> answer;
while (play=="yes" || play=="YES" || play=="Y" || play=="Yes" || play=="y") { //plays the game
answer.push_back(rand()%10+1);
do { //fills vector with unique random numbers
for (int i=1; i<nums; i++) {
answer.push_back(rand()%10+1);
if (answer[i]==answer[i-1]) {
i=i-1;
continue;
}
}
} while (answer.size()!=nums);
for (int i=0; i<nums; i++) {
cout<<answer[i];
}
cout<<"Do you want to play again?"<<'\n';
cin>>play;
answer.clear();
} //game ends
if (play=="no" || play=="n" || play=="No" || play=="NO" || play=="N") { //terminates and checks for exceptions
cout<<"Thank you for playing!"<<'\n';
return 0;
} else {
cerr<<"Error: wrong input. Terminating."<<'\n';
return 0;
}
return 0; //safety return
}
をまた、私はより良い、C++ 11の方法が存在しているはずこれを行うには、私はこのようにする必要があります。 – bruneleski
'std :: vector'の代わりに' std :: set'を使うことを検討してください。セットはユニークな値だけを格納します: 'std :: set answer; while(answer.size()<5)answer.insert(your_random_number); ' –
PaulMcKenzie
これはクールです。しかし、今はベクターで作業しています。セットを受け入れるかどうかは不明です。 (物の運動種) – bruneleski