Java简单实现概率与区间范围⽣成算法
利⽤BigDecimal中multiply乘法⽅法 ⼀个基准范围*百分⽐
public static void main(String[] args){
int mulriple =10000;
List<LotteryItem> lotteryItems =new ArrayList<>();
LotteryItem lotteryItem1 =new LotteryItem();
lotteryItem1.setId(1);
lotteryItem1.setPercent(new BigDecimal(0.02));
lotteryItems.add(lotteryItem1);
LotteryItem lotteryItem2 =new LotteryItem();
lotteryItem2.setId(2);
lotteryItem2.setPercent(new BigDecimal(0.09));
lotteryItems.add(lotteryItem2);
LotteryItem lotteryItem3 =new LotteryItem();
lotteryItem3.setId(3);
lotteryItem3.setPercent(new BigDecimal(0.2));
lotteryItems.add(lotteryItem3);
LotteryItem lotteryItem4 =new LotteryItem();
lotteryItem4.setId(4);
lotteryItem4.setPercent(new BigDecimal(0.5));
lotteryItems.add(lotteryItem4);
int lastScope =0;
Collections.shuffle(lotteryItems);
Map<Integer,int[]> awardItemScope =new HashMap<>();
for(LotteryItem item : lotteryItems){
int currentScope = lastScope +new Percent().floatValue()).multiply(new BigDecimal(mulriple)).intValue(); awardItemScope.Id(),new int[]{lastScope +1, currentScope});
lastScope = currentScope;
}
System.out.String());
int luckyNumber =new Random().nextInt(lastScope);
int luckyPrizeId =0;
if(!awardItemScope.isEmpty()){
Set<Map.Entry<Integer,int[]>> set = Set();
for(Map.Entry<Integer,int[]> entry : set){
if(luckyNumber >= Value()[0]&& luckyNumber <= Value()[1]){
luckyPrizeId = Key();
break;
}
}
}
System.out.println(luckyPrizeId);
}
其中,实体类:
public class LotteryItem {
private Integer id;
private BigDecimal percent;
public Integer getId(){
return id;
bigdecimal转换为integer}
public void setId(Integer id){
this.id = id;
}
public BigDecimal getPercent(){
return percent;
}
public void setPercent(BigDecimal percent){
this.percent = percent;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论