Saturday, April 28, 2012

Unique Random Number Generator



package utilities;

import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * @author noel
 */
public class UniqueRandomNumber {

    public static class OutOfBoundsException extends Exception {

        public OutOfBoundsException() {
            super("Generator past bounds");
        }
    }
    private int size;
    private int counter = 0;
 
    private boolean hasNext = false;
    private ArrayList <Integer> listOfValues = new ArrayList<Integer>();
    public UniqueRandomNumber(int size){
        this.size = size;
        if (size > 0 ) hasNext = true;
        for (int i = 0; i < size; i++){
            listOfValues.add(i);
        }
        Collections.shuffle(listOfValues);
     
    }
    public int getNext() throws OutOfBoundsException{
        if (counter >= size) throw new OutOfBoundsException();
        int returnVal = listOfValues.get(counter);
        counter++;
        if (counter >= size) hasNext = false;
        return returnVal;
     
    }
         

    /**
     * @return the hasNext
     */
    public boolean hasNext() {
        return hasNext;
    }
 
 
}

No comments:

Post a Comment