Hi Divya,
We keep up with all the previously generated numbers in Set ints. A Set by definition does not allow for duplicate entries so all we have to do is check if the value has already been added to it and if it has continue looping until we generate a value that is not in it. This is what I meant by a naive approach since it is a grossly inefficient way to accomplish our task. Note that you cannot add primitives like int to a
Java Set so we create an Integer object which is Java's wrapper for int. The crux of all this is in the following:
The line if (! ints.contains(i)) checks that the newly generated random int is not already in the Set. If this conditional evaluates true, we add the Integer to the Set, make our return value (r) equal to the intValue() and break out of the loop; otherwise we iterate the loop again.
Note that when our nextInt() returns -1, then all the possibilities have been generated. At this point the instantiation of UniqueRandomInt is no longer useful and you will have to construct a new one if need be. Of course you could add a clear() method to restart the process and in it call ints.clear() to remove everything from the Set. You could also add a method called setRange(int range), which would set high to range (this.high = range).
Hope this is helpful,
Michael Morris
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher