用java实现抽奖概率算法
生活随笔
收集整理的這篇文章主要介紹了
用java实现抽奖概率算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
抽獎說明
某次抽獎獎金有10元,100元,1000元,每人僅限一次抽獎,用java代碼實現
代碼如下:
package com.xdl;import java.util.*;public class TestDemo {public static String weightRandom(Map<String, Integer> map) {//獲取map里的key值集合Set<String> keySet = map.keySet();List<String> weights = new ArrayList<>();for (Iterator<String> it = keySet.iterator(); it.hasNext(); ) {//循環獲取map里key值String weightStr = it.next();//獲取key對應的value值,即每個金額對應的次數int weight = map.get(weightStr);for (int i = 0; i < weight; i++) {//等于將90個'10元',9個'100元',1個'1000元'分別添加到weights集合中weights.add(weightStr);}}//抽獎時隨機獲取集合里(100個金額字符串集)的字符串的下標int idx = new Random().nextInt(weights.size());//返回對應的金額return weights.get(idx);}//測試方法如下public static void main(String[] args) {Map<String, Integer> map = new HashMap<>();//往map里添加的value值90,9,1代表著各自金額抽中的概率map.put("10元", 90);map.put("100元", 9);map.put("1000元", 1);/* //抽一次獎,看抽出金額是多少System.out.println(weightRandom(map));*///抽獎100次,看不同獎金分別出現多少次for (int i = 0; i < 10; i++) {System.out.println(weightRandom(map));}}}```總結
以上是生活随笔為你收集整理的用java实现抽奖概率算法的全部內容,希望文章能夠幫你解決所遇到的問題。