题目: 小虚竹为了给粉丝送福利,决定在参与学习打卡活动的粉丝中抽一位幸运粉丝,送份小礼物。为了公平,要保证抽奖过程是随机的。
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中文网其他相关文章!