-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomUtil.java
executable file
·97 lines (79 loc) · 2.39 KB
/
RandomUtil.java
1
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package javaToolkit.lib.utils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class RandomUtil {
public Object getARandomElement(List<?> givenList) {
Random rand = new Random();
Object randomElement = givenList.get(rand.nextInt(givenList.size()));
return randomElement;
}
public List<Object> randomSelectWithRepeat(List<Object> givenList, int numberOfElements) {
Random rand = new Random();
List<Object> selectedEles = new ArrayList<>();
for (int i = 0; i < numberOfElements; i++) {
int randomIndex = rand.nextInt(givenList.size());
Object randomElement = givenList.get(randomIndex);
selectedEles.add(randomElement);
}
return selectedEles;
}
public List<?> randomSelectWithoutRepeat(List<?> givenList, int numberOfElements) {
Random rand = new Random();
List<Object> selectedEles = new ArrayList<>();
for (int i = 0; i < numberOfElements; i++) {
int randomIndex = rand.nextInt(givenList.size());
Object randomElement = givenList.get(randomIndex);
selectedEles.add(randomElement);
givenList.remove(randomIndex);
}
return selectedEles;
}
/**
* include max and min
*
* @param min
* @param max
* @param k
* @return
*/
public static Set<Integer> randomGenerateKDistinctNumbers(int min, int max, int k) {
Random rand = new Random();
Set<Integer> selectedEles = new HashSet<>();
if (max - min < k) {
System.out.printf("Cannot generate %s between %s and %s\n", k, min, max);
System.exit(0);
}
while (selectedEles.size() < k) {
int randomNum = rand.nextInt((max - min) + 1) + min;
selectedEles.add(randomNum);
}
return selectedEles;
}
/**
* include max and min, not contain
*
* @param min
* @param max
* @param k
* @return
* @throws Exception
*/
public static Set<Integer> randomKDistinctNumsWithoutSpecificNum(int min, int max, int k, int withoutNum) throws Exception {
Random rand = new Random();
Set<Integer> selectedEles = new HashSet<>();
if (max - min < k) {
System.out.printf("Cannot generate %s between %s and %s\n", k, min, max);
throw new Exception("Cannot generate " + k + " between " + min + " and " + max + "\n");
}
while (selectedEles.size() < k) {
int randomNum = rand.nextInt((max - min) + 1) + min;
if (randomNum != withoutNum) {
selectedEles.add(randomNum);
}
}
return selectedEles;
}
}