Java 實現大轉盤抽獎 JAVA中的Random()函數

須要用到 JAVA中的Random()函數html

注意:大轉盤抽獎各獎項中獎機率之和爲 1。獎品列表中的機率爲累加機率,須要按照添加進列表的順序進行累加,添加順序不作要求。java

實際中使用須要考慮獎品數量限制等業務需求,該代碼只是個簡單的抽獎demo。dom

獎品數量限制的話,若是須要保證剩餘獎品機率比例不變,須要從新構建獎品列表。函數

package com.wangbo.choujiang;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 大轉盤抽獎
 * @author wangbo
 * @date 2019-05-22 14:54:47
 */
public class Test1 {

    public static void main(String[] args) {

        List<Award> awardList = new ArrayList<Award>();
        Award award1 = new Award();
        award1.setAwardName("手機");//10%
        award1.setProbability(0.1);
        awardList.add(award1);
        
        Award award2 = new Award();
        award2.setAwardName("水杯");//20%
        award2.setProbability(0.2+0.1);//機率加上上一個獎品的機率(累加)
        awardList.add(award2);
        
        Award award4 = new Award();
        award4.setAwardName("鼠標");//10%
        award4.setProbability(0.1+0.2+0.1);
        awardList.add(award4);
        
        Award award5 = new Award();
        award5.setAwardName("謝謝惠顧");//60%
        award5.setProbability(1d);//最後一個確定是1
        awardList.add(award5);
        
        Random random = new Random();
        int a = 0,b = 0,c = 0,d = 0;
        for (int i = 0; i < 10000; i++) {
            
            Double userSelect = random.nextDouble();//0.0-1.0的double隨機數(不包括1.0)
            String awardName = duageAward(userSelect, awardList);
            //信息統計
            if ("手機".equals(awardName)) {
                a++;
            }else if ("水杯".equals(awardName)) {
                b++;
            }else if ("鼠標".equals(awardName)) {
                c++;
            }else if ("謝謝惠顧".equals(awardName)){
                d++;
            }
        }
        System.out.println("手機 " + a + " 次");
        System.out.println("水杯 " + b + " 次");
        System.out.println("鼠標 " + c + " 次");
        System.out.println("謝謝惠顧 " + d + " 次");
    }
    
    /**
     * 選獎品
     * @param userSelect
     * @param awardList
     * @return
     */
    public static String duageAward(Double userSelect, List<Award> awardList){
        for (Award award : awardList) {
            if(userSelect < award.getProbability()){
                return award.getAwardName();
            }
        }
        return null;
    }
    
}


class Award{
    private String awardName;
    private Double probability;
    public String getAwardName() {
        return awardName;
    }
    public Double getProbability() {
        return probability;
    }
    public void setAwardName(String awardName) {
        this.awardName = awardName;
    }
    public void setProbability(Double probability) {
        this.probability = probability;
    }
    
}

運行結果:post

相關文章
相關標籤/搜索