// This class uses a queue to store groups of permutations of the numbers 1 - 7. import java.util.Random; public class GrabBag { private int[] bag_queue; private int beg, end, count; public GrabBag() { bag_queue = new int[14]; beg = end = count = 0; // Load up fourteen numbers enqueueSeven(); enqueueSeven(); } // Get the next number in the bag. public int getNext() { return dequeue(); } // Add one number to the end of the queue private void enqueue(int i) { bag_queue[end] = i; end = (end+1)%14; count++; } // Get one number from the beginning of the queue private int dequeue() { int retval = bag_queue[beg]; beg = (beg+1)%14; count--; // If the bag has less than seven numbers left, get seven more if (count < 7) enqueueSeven(); return retval; } // Method to permute the numbers 1 - 7 and enqueue them. private void enqueueSeven() { Random rand = new Random(); int[] numbers = new int[7]; int n; for (int i = 0; i < 7; i++) { n = rand.nextInt(7) + 1; numbers[i] = n; // Make sure our new number isn't already in the array, // and correct if it is. for (int j = 0; j < i; j++) { if (numbers[j] == n) { n = (n%7)+1; j = -1; } else numbers[i] = n; } } for (int i = 0; i < 7; i++) enqueue(numbers[i]); } }