From e60fe994106b55b5a4e36bd64917572050c8fea8 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Fri, 15 Mar 2019 19:01:34 +0100 Subject: [PATCH] Add random item selection from Set --- .../fr/pandacube/java/util/RandomUtil.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/fr/pandacube/java/util/RandomUtil.java b/src/main/java/fr/pandacube/java/util/RandomUtil.java index a53d1bb..3a7215a 100644 --- a/src/main/java/fr/pandacube/java/util/RandomUtil.java +++ b/src/main/java/fr/pandacube/java/util/RandomUtil.java @@ -2,6 +2,7 @@ package fr.pandacube.java.util; import java.util.List; import java.util.Random; +import java.util.Set; public class RandomUtil { @@ -22,5 +23,24 @@ public class RandomUtil { public static T listElement(List arr) { return arr.get(rand.nextInt(arr.size())); } + + /** + * Returns a random value from a set. + * + * May not be optimized (Actually O(n) ) + * @param arr + * @return + */ + public static T setElement(Set set) { + if (set.isEmpty()) + throw new IllegalArgumentException("set is empty"); + int retI = rand.nextInt(set.size()), i = 0; + for (T e : set) { + if (retI == i) + return e; + i++; + } + throw new RuntimeException("Should never go to this line of code"); + } }