【java】指定確率により確率ランダム分布を実現

17080 ワード

【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 {
	//Dubbo          
    public static Integer WeightFifter(List<RandomTest> list){
        //  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 ++){
        	//       <   [j]         ,             [j] 
            if (random - list.get(j).getProbability()<0){
                return j;
            //       >   [j]          ,              [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