Home >Java >javaTutorial >How to implement the lottery function algorithm in Java?
Topic: In order to give benefits to fans, Xiao Xuzhu decided to draw a lucky fan among the fans who participated in the learning check-in activity and give him a small gift. For the sake of fairness, the lottery process must be random.
1. Add participants to the collection
2. Use Random object to obtain random numbers
3. The random number is used as the subscript to obtain the lucky user in the set
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; } }
The number of random hits is too few and needs to be optimized
The number of random hits for everyone needs to be listed and displayed, which is more open and fair
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; } }
The above is the detailed content of How to implement the lottery function algorithm in Java?. For more information, please follow other related articles on the PHP Chinese website!