Skip to content

Commit

Permalink
MCCollections: Added more random element getters
Browse files Browse the repository at this point in the history
  • Loading branch information
xDec0de committed Jul 14, 2024
1 parent 2282920 commit 035556d
Showing 1 changed file with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -445,11 +445,36 @@ public static <E> boolean contains(@Nonnull Iterable<E> iterable, @Nonnull Predi

// Element getters - Random //

@Nullable
public static <E> E getRandom(@Nonnull E[] array) {
return array[MCNumbers.random().nextInt(0, array.length)];
}

@Nullable
public static <E> E getRandom(@Nonnull Collection<E> collection) {
return get(collection, MCNumbers.random(0, collection.size()));
return get(collection, MCNumbers.random().nextInt(0, collection.size()));
}

@Nullable
public static <E> E getRandom(@Nonnull List<E> list) {
return list.get(MCNumbers.random(0, list.size()));
return list.get(MCNumbers.random().nextInt(0, list.size()));
}

@Nonnull
public static <E> List<E> getRandom(@Nonnull Collection<E> collection, @Positive int amount, boolean allowDuplicates) {
if (amount >= collection.size())
return new ArrayList<>(collection);
final List<E> res = new ArrayList<>(amount);
while (res.size() != amount) {
final E element = getRandom(collection);
if (allowDuplicates || !res.contains(element))
res.add(element);
}
return res;
}

@Nonnull
public static <E> List<E> getRandom(@Nonnull Collection<E> collection, @Positive int amount) {
return getRandom(collection, amount, false);
}
}

0 comments on commit 035556d

Please sign in to comment.