c++ - 随机选择两个值

标签 c++ algorithm random

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

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

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

最佳答案

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

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

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

关于c++ - 随机选择两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10541224/

相关文章:

c++ - 带有 MSG_PEEK 的 C 'recv' 不返回 -1

c++ - GCC 中不可避免的可变参数模板(与 CUDA 一起使用)?

c++ - 下面的算法如何实现?

c++ - VS2010中random_device的实现?

c++ - 在每台计算机上生成相同的随机排列

c++ - LSH 用于基于汉明距离的快速 NN 相似性搜索?

C++ 指向类名的指针数组

java - 可以在流上计算 SHA-1 算法吗?内存占用少?

php - 提高我的 ip 黑名单-白名单脚本的效率

c++ - 在C++中均匀生成随机数