|
| 1 | +package didipractice; |
| 2 | + |
| 3 | +/** |
| 4 | +* @Author: iqqcode |
| 5 | +* @Date: 2020-10-21 14:20 |
| 6 | +* @Description: |
| 7 | +*/ |
| 8 | + |
| 9 | +import java.util.*; |
| 10 | + |
| 11 | +public class Main { |
| 12 | + |
| 13 | + |
| 14 | +public static void main(String[] args) { |
| 15 | +int[] arr_five = new int[10]; |
| 16 | +for (int i = 0; i < arr_five.length; i++) { |
| 17 | +arr_five[i] = randFive(); |
| 18 | +} |
| 19 | + |
| 20 | +System.out.println("生成1-5的随机数: " + Arrays.toString(arr_five)); |
| 21 | + |
| 22 | + |
| 23 | +int[] arr_seven = new int[10]; |
| 24 | +for (int i = 0; i < arr_seven.length; i++) { |
| 25 | +arr_seven[i] = getRandomNumSevenI(); |
| 26 | +} |
| 27 | + |
| 28 | +// 测试统计 |
| 29 | +Map<Integer, Integer> map = new HashMap<>(); |
| 30 | +System.out.println("<<测试方法二>>"); |
| 31 | +for (int i = 0; i < 1000000; i++) { |
| 32 | + |
| 33 | +// 测试方法二 |
| 34 | +int temp = getRandomNumSevenII(); |
| 35 | + |
| 36 | +if(map.containsKey(temp)) { |
| 37 | +map.put(temp, map.get(temp) + 1); |
| 38 | +} else { |
| 39 | +map.put(temp, 1); |
| 40 | +} |
| 41 | +} |
| 42 | + |
| 43 | +map.forEach((key, value) -> { |
| 44 | +System.out.println(key + " -- 出现次数:" + value); |
| 45 | +}); |
| 46 | + |
| 47 | + |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | +* Random类产生随机数 |
| 52 | +* @param |
| 53 | +*/ |
| 54 | +public static int randFive() { |
| 55 | +Random random = new Random(); |
| 56 | +int rand_five = random.nextInt(5) + 1; |
| 57 | +return rand_five; |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | +* Math.random()产生随机数 |
| 62 | +* @param |
| 63 | +*/ |
| 64 | +public static int randFiveII(int[] arr) { |
| 65 | +int max = 5, min = 1; |
| 66 | +int rand_five = (int) (Math.random() * 5 + 1); |
| 67 | +return rand_five; |
| 68 | +} |
| 69 | + |
| 70 | +public static int randFiveIII() { |
| 71 | +int max = 100, min = 1; |
| 72 | +long randomNum = System.currentTimeMillis(); |
| 73 | +int rand_five = (int) (randomNum % (max - min) + min); |
| 74 | +//循环同一时间会产生相同的数 |
| 75 | +return rand_five; |
| 76 | +} |
| 77 | + |
| 78 | + |
| 79 | +/** |
| 80 | +* 调用randFive()来 等概率 产生 1-7 |
| 81 | +* @return |
| 82 | +*/ |
| 83 | +public static int getRandomNumSevenI() { |
| 84 | +while (true) { |
| 85 | +int randLowSeven = (randFive() - 1) * 5 + randFive(); |
| 86 | +if(randLowSeven <= 21) { |
| 87 | +return randLowSeven % 7 + 1; |
| 88 | +} |
| 89 | +} |
| 90 | +} |
| 91 | + |
| 92 | + |
| 93 | + |
| 94 | +public static int getRandomNumSevenII() { |
| 95 | +int randLowSeven = 0; |
| 96 | +while ((randLowSeven = randFive() * 5 + randFive()) > 26); |
| 97 | + |
| 98 | +return (randLowSeven - 3) / 3; |
| 99 | +} |
| 100 | + |
| 101 | + |
| 102 | + |
| 103 | + |
| 104 | +} |
0 commit comments