gpt4 book ai didi

c++ - 随机选择两个值

转载 作者:可可西里 更新时间:2023-11-01 17:38:21 28 4
gpt4 key购买 nike

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

到目前为止,我的解决方案是将选项按正确次数放入 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com