【java】根据指定概率,实现概率随机分布
实体类【RandomTest】
package com.snailDream;
public class RandomTest {
String name;
Integer probability;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getProbability() {
return probability;
}
public void setProbability(Integer probability) {
this.probability = probability;
}
@Override
public String toString() {
return "RandomTest{" +
"name='" + name + '\'' +
", probability=" + probability +
'}';
}
}
随机算法类【WeightFifter】
package com.snailDream;
import java.util.List;
public class Weight {
public static Integer WeightFifter(List<RandomTest> list){
Integer weight = list.stream().mapToInt(RandomTest::getProbability).sum();
int random=(int)Math.floor(Math.random() * weight);
for (Integer j = 0 ; j < list.size() ; j ++){
if (random - list.get(j).getProbability()<0){
return j;
}else{
random -= list.get(j).getProbability();
}
}
return null;
}
}
测试类
public static void main(String[] args) {
RandomTest randomTestA = new RandomTest();
randomTestA.setName("A10概率");
randomTestA.setProbability(10);
RandomTest randomTestB = new RandomTest();
randomTestB.setName("B30概率");
randomTestB.setProbability(30);
RandomTest randomTestC = new RandomTest();
randomTestC.setName("C60概率");
randomTestC.setProbability(60);
List<RandomTest> list = new ArrayList<>();
list.add(randomTestA);
list.add(randomTestB);
list.add(randomTestC);
Integer a=0;
Integer b=0;
Integer c=0;
Integer k = 1000;
for (int i = 0 ; i < k ; i++){
Integer pro = list.get(Weight.WeightFifter(list)).getProbability();
if (pro == 10) {a+=1;continue;}
if (pro == 30) {b+=1;continue;}
if (pro == 60) {c+=1;continue;}
}
System.out.println(k+"次内 ,10% 概率出现:"+ a);
System.out.println(k+"次内 ,30% 概率出现:"+ b);
System.out.println(k+"次内 ,60% 概率出现:"+ c);
}
测试结果
1000次内 ,10% 概率出现:96次
1000次内 ,30% 概率出现:321次
1000次内 ,60% 概率出现:583次
1000次内 ,10% 概率出现:112次
1000次内 ,30% 概率出现:291次
1000次内 ,60% 概率出现:597次
1000次内 ,10% 概率出现:105次
1000次内 ,30% 概率出现:303次
1000次内 ,60% 概率出现:592次
1000次内 ,10% 概率出现:108次
1000次内 ,30% 概率出现:308次
1000次内 ,60% 概率出现:584次
1000次内 ,10% 概率出现:94次
1000次内 ,30% 概率出现:307次
1000次内 ,60% 概率出现:599次