Java实现抽奖算法的示例代码
时间:2022-12-09 09:56:09|栏目:JAVA代码|点击: 次
一、题目描述
题目: 小虚竹为了给粉丝送福利,决定在参与学习打卡活动的粉丝中抽一位幸运粉丝,送份小礼物。为了公平,要保证抽奖过程是随机的。
二、解题思路
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; } }