第八个的代码: import java.util.HashMap; import java.util.Map; import java.util.Random; /** 有一个1-4的随机器rand4,如何实现1-6的随机器rand6,概率相同。拓展:rand X = func(rand Y),实现func函数* */ public class RandMain { static Map<Integer,Integer> map = new HashMap<>(); public static void main(String[] args) { map.put(1, 0); map.put(2, 0); map.put(3, 0); map.put(4, 0); map.put(5, 0); map.put(6, 0); for (int i = 0; i < 10000000; i++) { int rand = rand6(); map.put(rand, map.get(rand) + 1); } for(Map.Entry<Integer,Integer> entry : map.entrySet()){ System.out.println(entry.getKey() + ":" + entry.getValue()); } } private static int rand6() { int num = (rand4() - 1) * 4 + rand4(); while(num > 6){ num = (rand4() - 1) * 4 + rand4(); } return num; } private static int rand4() { return new Random().nextInt(4) + 1; } }
点赞 评论

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务