Advertisement
sci4me

RandomBucket

Jan 13th, 2015
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. public final class RandomBucket
  2. {
  3.     private final Random random;
  4.     private final int min;
  5.     private final int max;
  6.     private final List<Integer> bucket;
  7.  
  8.     public RandomBucket(final int max)
  9.     {
  10.         this(0, max);
  11.     }
  12.  
  13.     public RandomBucket(final int min, final int max)
  14.     {
  15.         this.random = new Random();
  16.         this.min = min;
  17.         this.max = max;
  18.         this.bucket = new ArrayList<Integer>();
  19.  
  20.         this.fillIfNeeded();
  21.     }
  22.  
  23.     private void fillIfNeeded()
  24.     {
  25.         if (this.bucket.size() != 0)
  26.             return;
  27.  
  28.         for (int i = this.min; i < this.max; i++)
  29.             this.bucket.add(i);
  30.     }
  31.  
  32.     public int next()
  33.     {
  34.         this.fillIfNeeded();
  35.  
  36.         final int index = this.random.nextInt(this.bucket.size());
  37.         return this.bucket.remove(index);
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement