随机选择两个值

时间:2012-05-10 19:56:19

标签: c++ algorithm random

在我的算法中,我有两个值,我需要随机选择,但每个值必须选择预定的次数。

到目前为止,我的解决方案是将选项放入向量中正确的次数,然后将其随机播放。在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,每当我需要一个新的迭代器时,我会增加迭代器并获取该值。

这有效,但似乎可能有更有效的方式。因为我总是知道我将使用的每个值中有多少我想知道是否有更多的算法方法来执行此操作,而不仅仅是存储值。

3 个答案:

答案 0 :(得分:10)

你不必要地使用这么多内存。你有两个变量:

int number_of_choice1s = 5;
int number_of_choice2s = 1;

现在简单地随机化:

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;
}

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

答案 1 :(得分:1)

你可以更简单地写一下:

std::vector<int> choices(number_of_choice1s, choice1);
choices.resize(number_of_choice1s + number_of_choice2s, choice2);
std::random_shuffle(choices.begin(), choices.end());

答案 2 :(得分:0)

有偏见的随机分布将在结果集上保持某种顺序(选择次数最多的选择次要选择的次数越来越少),这会产生偏差的结果(特别是如果你有多少时间)选择第一个值与第二个值相比较大,你最终会得到类似{1,1,1,2,1,1,1,1,2}的东西。

这是代码,看起来很像@Tomasz Nurkiewicz编写的代码,但是使用简单的偶数/奇数,应该有大约50/50的机会选择任一值。

int result = rand();

if ( result & 1  &&  number_of_choice1s > 0)
{
number_of_choice1s--;
return choice1;
}else if (number_of_choice2s>0)
{
number_of_choice2s--;
return choice2;
}
else
{
return -1;
}