gpt4 book ai didi

iphone - 根据概率随机选择项目

转载 作者:行者123 更新时间:2023-11-29 03:47:59 29 4
gpt4 key购买 nike

我有一个元素数组。每个元素都有一个附加的概率值。假设我有一系列苹果,红色、黄色、绿色、蓝色等。

- (Apple *)pickRandomApple
{
Apple *red = [Apple redApple];
Apple *green = [Apple greenApple];
Apple *yellow = [Apple yellowApple];
Apple *blue = [Apple blueApple];

red.probability = 0.23f;
green.probability = 0.85f;
yellow.probability = 0.1f;
blue.probability = 0.5f;
NSArray *array = @[red,green,blue,yellow];

return array[arc4random()%array.count];
}

我想根据概率属性随机选择一个苹果。我怎样才能做到这一点?

谢谢!

最佳答案

一种可能的解决方案是将项目(概率*精度)次添加到数组中并对其使用随机。

否则你可以总结概率并定义区域

double max = (red.probability + green.probability + yellow.probability 
+ blue.probability) * 100.f;

int random = arc4random()%(int)max;

if(random < red.probability * 100)
return red;
else if(random < (red.probability + blue.probability) * 100)
return blue:
...

等等。

也可以为此创建一个 for 循环:)

更新

double max = (red.probability + green.probability + yellow.probability 
+ blue.probability) * 100.f;
// max = (0.23 + 0.85 + 0.1 + 0.5) * 100; // = 1.68 * 100 = 168

int random = arc4random()%(int)max;

if(random < red.probability * 100) // area 0 - 23
return red;
else if(random < (red.probability + blue.probability) * 100) // area 24 - 108
return blue:
...

在循环中你可以保存一个 currentValue 变量

double max = (red.probability + green.probability + yellow.probability 
+ blue.probability) * 100.f;
// max = (0.23 + 0.85 + 0.1 + 0.5) * 100; // = 1.68 * 100 = 168

int random = arc4random()%(int)max;
int currentValue = 0;

for(Apple *apple in array)
{
currentValue += (int)(apple.probability * 100.f);
if(random <= currentValue)
return apple;
}

只需用测试值尝试一下,如果它没有按您希望的方式工作,请告诉我您错过了什么:)

关于iphone - 根据概率随机选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17467796/

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