Skip to content
Browse files

Added additional methods to SourceOfRandomness: pick, pickUpTo, nextS…

…tring
  • Loading branch information...
1 parent 15337d2 commit e0efafba66331e7b997e747e00e143a852f376b6 @marcphilipp committed Nov 21, 2010
View
28 src/main/java/com/pholser/junit/parameters/random/AbstractJDKSourceOfRandomness.java
@@ -1,5 +1,11 @@
package com.pholser.junit.parameters.random;
+import static java.lang.Math.min;
+import static java.util.Arrays.asList;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import java.util.Random;
abstract class AbstractJDKSourceOfRandomness implements SourceOfRandomness {
@@ -57,11 +63,31 @@ public long nextLong() {
}
@Override
+ public String nextString() {
+ return new String(nextBytes(nextInt(1024)));
+ }
+
+ @Override
public void setSeed(long seed) {
random.setSeed(seed);
}
public <T> T oneOf(T... items) {
- return items[nextInt(items.length)];
+ return oneOf(asList(items));
+ }
+
+ public <T> T oneOf(List<T> items) {
+ return items.get(nextInt(items.size()));
}
+
+ public <T> List<T> pickUpTo(int number, List<T> items) {
+ return pick(nextInt(number), items);
+ }
+
+ public <T> List<T> pick(int number, List<T> items) {
+ List<T> itemsCopy = new ArrayList<T>(items);
+ Collections.shuffle(itemsCopy, random);
+ return itemsCopy.subList(0, min(number, items.size()));
+ }
+
}
View
33 src/main/java/com/pholser/junit/parameters/random/SourceOfRandomness.java
@@ -1,26 +1,37 @@
package com.pholser.junit.parameters.random;
+import java.util.List;
+
public interface SourceOfRandomness {
-
- boolean nextBoolean();
- void nextBytes(byte[] bytes);
+ boolean nextBoolean();
+
+ void nextBytes(byte[] bytes);
- byte[] nextBytes(int length);
+ byte[] nextBytes(int length);
- double nextDouble();
+ double nextDouble();
- float nextFloat();
+ float nextFloat();
- double nextGaussian();
+ double nextGaussian();
- int nextInt();
+ int nextInt();
- int nextInt(int n);
+ int nextInt(int n);
- long nextLong();
+ long nextLong();
- void setSeed(long seed);
+ void setSeed(long seed);
<T> T oneOf(T... items);
+
+ <T> T oneOf(List<T> items);
+
+ <T> List<T> pick(int number, List<T> items);
+
+ <T> List<T> pickUpTo(int number, List<T> items);
+
+ String nextString();
+
}

0 comments on commit e0efafb

Please sign in to comment.
Something went wrong with that request. Please try again.