Random Integers

The next example shows how to select randomly from a collection of mock integers. The code is in examples/java/Random.java, and is paraphrased here. While this example uses integers, the principle applies to collections of any type.

A RandomIterator named iter is created against an Ints collection. All values in the collection are selected randomly with replacement, and printed. To select with replacement means that each value is, in effect, put back into the collection after it is selected. So it has an equal liklihood of being selected next. Selection without replacement means that each value selected from the collection is not put back, so it will not be reselected until all values have been selected (and the iterator is reset).

    
    RandomIterator iter = new RandomIterator ();
    iter.setCollection (new Ints ("[0,9]"));

    // with replacement
    iter.setReplace (true);
    System.out.println ("ints with replacement");
    for (int i = 0; i < 3; i++)
    {
	iter.reset ();
	while (iter.hasNext ())
	    System.out.print (iter.getNextValue () + " ");
	System.out.println ();
    }

    // without replacement
    iter.setReplace (false);
    System.out.println ("ints without replacement");
    for (int i = 0; i < 3; i++)
    {
	iter.reset ();
	while (iter.hasNext ())
	    System.out.print (iter.getNextValue () + " ");
	System.out.println ();
    }
    
  

The iterator runs over the collection three times, in the for loop. The iterator is reset before each run. These runs happen twice: once with replacement, and once without. The results are:

    
    ints with replacement
    0 8 9 7 5 3 1 1 9 4 
    7 7 3 2 5 4 4 5 1 0 
    3 8 4 7 2 0 3 2 2 3 
    ints without replacement
    5 1 3 0 2 4 8 7 9 6 
    9 7 8 5 0 4 3 6 1 2 
    6 8 2 3 7 4 5 9 0 1 
    
  

Note that selection without replacement is implemented by building an array in memory of all collection values. This lets the code decide which values have already been selected. It is not a problem for reasonably sized collections, but may be expensive for large collections.