随机选择两个值

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)

这可以很好地扩展两百万随机调用.

  • 除非选择的数量均分为"RAND_MAX + 1",否则不能使用`%`或`/`生成无偏选择.StackOverflow上有很多关于生成无偏差随机选择的帖子.我不确定这里有多重要,因为选择的数量在不断变化. (3认同)
  • 但请注意,如果您的标准库碰巧有一个糟糕的`rand`实现(例如,线性同余具有较小的模数),使用这样的'%`会引入偏差.另外,`RAND_MAX`可能小到32767(微软标准库中的`rand`具有此属性),如果您有大量选择,您将完全失败. (2认同)