Sea*_*nch 8 c++ random algorithm
在我的算法中,我有两个值,我需要随机选择,但每个值必须选择预定次数.
到目前为止,我的解决方案是将选项放入向量中正确的次数,然后将其洗牌.在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());
Run Code Online (Sandbox Code Playgroud)
然后我保留一个迭代器choices
,每当我需要一个新的迭代器时,我会增加迭代器并获取该值.
这有效,但似乎可能有一种更有效的方式.因为我总是知道我将使用的每个值中有多少我想知道是否有更多的算法方法来执行此操作,而不仅仅是存储值.
Tom*_*icz 10
你不必要地使用这么多内存.你有两个变量:
int number_of_choice1s = 5;
int number_of_choice2s = 1;
Run Code Online (Sandbox Code Playgroud)
现在简单地随机化:
int result = rand() % (number_of_choice1s + number_of_choice2s);
if(result < number_of_choice1s) {
--number_of_choice1s;
return choice1;
} else {
--number_of_choice2s;
return choice2;
}
Run Code Online (Sandbox Code Playgroud)
这可以很好地扩展两百万随机调用.