java概率选择,java – 如何选择一个项目的概率?

因此,每个项目存储一个标记其相对概率的数字,例如,如果您有3个项目,一个应该是两个可能被选择为其他两个,那么你的列表将有:

[{A,1},{B,1},{C,2}]

然后将列表的数字相加(即在我们的例子中为4)。

现在生成一个随机数并选择该索引。

int index = rand.nextInt(4);

返回数字,使索引在正确的范围内。

Java代码:

class Item {

int relativeProb;

String name;

//Getters Setters and Constructor

}

...

class RandomSelector {

List items = new List();

Random rand = new Random();

int totalSum = 0;

RandomSelector() {

for(Item item : items) {

totalSum = totalSum + item.relativeProb;

}

}

public Item getRandom() {

int index = rand.nextInt(totalSum);

int sum = 0;

int i=0;

while(sum < index ) {

sum = sum + items.get(i++).relativeProb;

}

return items.get(Math.max(0,i-1));

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值