題目: 小虛竹為了給粉絲福利,決定在參與學習打卡活動的粉絲中抽一位幸運粉絲,送份小禮物。為了公平,要確保抽獎過程是隨機的。
1、把參與的人員加到集合中
2、使用Random物件取得隨機數
#3、把隨機數當下標,取得集合中的幸運用戶
public class Basics28 { public static void main(String[] args) { List<String> luckUserNames = getLuckUserNames(); Random random = new Random(); int luckNum = random.nextInt(6); System.out.println("幸运的未来大佬是:"+luckUserNames.get(luckNum)); } private static List<String> getLuckUserNames(){ List<String> luckUserNames = new ArrayList<String>(); luckUserNames.add("李慢慢_"); luckUserNames.add("TryAgain-"); luckUserNames.add("team_dog"); luckUserNames.add("Jasonakeke"); luckUserNames.add("学好c语言的小王同学"); luckUserNames.add("Ara~追着风跑"); return luckUserNames; } }
隨機次數太少,需要優化
需要列出所有人隨機命中的次數,顯示出來,比較公開公平
public class LuckDraw { public static void main(String[] args) { List<String> luckUserNames = getLuckUserNames(); Random random = new Random(); //key:luckNum ,value:count Map<Integer,Integer> luckNumMap = new HashMap<Integer, Integer>(); for (int i = 0; i < 100; i++) { int luckNum = random.nextInt(4); Integer count = luckNumMap.get(luckNum); if(count==null){ count = 0; } ++count; luckNumMap.put(luckNum,count); } Integer maxLuckNum = 0; Integer maxCount =0; for(Integer luckNum:luckNumMap.keySet()){ if(maxCount<luckNumMap.get(luckNum)){ maxCount = luckNumMap.get(luckNum); maxLuckNum = luckNum; } System.out.println(luckUserNames.get(luckNum)+"同学的幸运值:"+luckNumMap.get(luckNum)); } System.out.println("本周学习打卡积分第一且是幸运的未来大佬是:"+luckUserNames.get(maxLuckNum)); } private static List<String> getLuckUserNames(){ List<String> luckUserNames = new ArrayList<String>(); luckUserNames.add("学好c语言的小王同学"); luckUserNames.add("Ara~追着风跑"); luckUserNames.add("李慢慢_"); luckUserNames.add("Jasonakeke"); return luckUserNames; } }
以上是Java中如何實作抽獎功能的演算法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!