私のアルゴリズムでは、ランダムに選択する必要がある 2 つの値がありますが、それぞれを所定の回数選択する必要があります。
これまでのところ、私の解決策は、選択肢をベクトルに正しい回数入れてからシャッフルすることです。C++ の場合:
// Example choices (can be any positive int)
int choice1 = 3;
int choice2 = 4;
int number_of_choice1s = 5;
int number_of_choice2s = 1;
std::vector<int> choices;
for(int i = 0; i < number_of_choice1s; ++i) choices.push_back(choice1);
for(int i = 0; i < number_of_choice2s; ++i) choices.push_back(choice2);
std::random_shuffle(choices.begin(), choices.end());
次に、イテレータを保持しchoices
、新しいイテレータが必要になるたびに、イテレータを増やしてその値を取得します。
これはうまくいきますが、もっと効率的な方法があるようです。使用する各値の数を常に知っているので、値を保存するだけでなく、これを行うためのよりアルゴリズム的な方法があるかどうか疑問に思っています。