Skip to content

Commit

Permalink
feat(utils): RandomUtils pickFromList method allowRepetitions option
Browse files Browse the repository at this point in the history
  • Loading branch information
lainio24 committed Jun 21, 2022
1 parent cc5fa25 commit 249c8c3
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions src/main/java/org/auioc/mcmod/arnicalib/utils/java/RandomUtils.java
Expand Up @@ -27,7 +27,7 @@ public static <T> T pickOneFromCollection(Collection<T> collection) {
return result;
}

public static <T> List<T> pickFromList(List<T> list, int N) {
public static <T> List<T> pickFromList(List<T> list, int N, boolean allowRepetitions) {
Validate.notEmpty(list, "The list must be not empty");

int size = list.size();
Expand All @@ -42,30 +42,44 @@ public static <T> List<T> pickFromList(List<T> list, int N) {
List<T> newList = new ArrayList<T>();

if (N == 1) {
newList.add(list.get(RANDOM.nextInt(size)));
newList.add(pickOneFromList(list, size));
} else {
List<Integer> targets = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
int target;
while (true) {
target = RANDOM.nextInt(size);
if (!targets.contains(target)) {
targets.add(target);
break;
if (allowRepetitions) {
for (int i = 0; i < N; i++) {
newList.add(pickOneFromList(list, size));
}
} else {
List<Integer> targets = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
int target;
while (true) {
target = RANDOM.nextInt(size);
if (!targets.contains(target)) {
targets.add(target);
break;
}
}
newList.add(list.get(target));
}
newList.add(list.get(target));
}
}

return newList;
}

public static <T> List<T> pickFromList(List<T> list, int N) {
return pickFromList(list, N, false);
}

public static <T> T pickOneFromList(List<T> list) {
Validate.notEmpty(list, "The list must be not empty");
return list.get(RANDOM.nextInt(list.size()));
}

private static <T> T pickOneFromList(List<T> list, int size) {
return list.get(RANDOM.nextInt(size));
}

// #endregion PickFromCollection

/*================================================================================================================*/
Expand Down

0 comments on commit 249c8c3

Please sign in to comment.