1
import java.util.Arrays;
2
import java.util.Random;
3
4
/**
5
* <code>RandomUtil</code> - Random Tool Class.
6
* @author SageZk
7
* @version 1.0
8
*/
9
public class RandomUtil {
10
11
private RandomUtil() {}
12
13
private static Random rnd = null;
14
15
/**
16
* 初始化隨機數發生器。
17
*/
18
private static void initRnd() {
19
if (rnd == null) rnd = new Random();
20
}
21
22
/**
23
* 計算并返回無重復值的以 <code>min</code> 為下限 <code>max</code> 為上限的隨機整數數組。
24
* @param min 隨機整數下限(包含)
25
* @param max 隨機整數上限(包含)
26
* @param len 結果數組長度
27
* @return 結果數組
28
*/
29
public static int[] getLotteryArray(int min, int max, int len) {
30
//參數校驗及性能優化
31
if (len < 0) return null; //長度小于 0 的數組不存在
32
if (len == 0) return new int[0]; //返回長度為 0 的數組
33
if (min > max) { //校正參數 min max
34
int t = min;
35
min = max;
36
max = t;
37
}
38
final int LEN = max - min + 1; //種子個數
39
if (len > LEN) return null; //如果出現 35 選 36 的情況就返回 null
40
//計算無重復值隨機數組
41
initRnd(); //初始化隨機數發生器
42
int[] seed = new int[LEN]; //種子數組
43
for (int i = 0, n = min; i < LEN;) seed[i++] = n++; //初始化種子數組
44
for (int i = 0, j = 0, t = 0; i < len; ++i) {
45
j = rnd.nextInt(LEN - i) + i;
46
t = seed[i];
47
seed[i] = seed[j];
48
seed[j] = t;
49
}
50
return Arrays.copyOf(seed, len); //注意:copyOf 需要 JRE1.6
51
}
52
53
//Unit Testing
54
public static void main(String[] args) {
55
final int N = 10000; //測試次數
56
for (int i = 0; i < N; ++i) {
57
int[] la = RandomUtil.getLotteryArray(1, 35, 7);
58
if (la == null) continue;
59
for (int v : la) System.out.printf("%0$02d ", v);
60
System.out.println();
61
}
62
}
63
64
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64
