On the old PLATO multi-user system that Mr. Paley used
back in the 1980s, when dinosaurs roamed the earth and
Klingons did not have prosthetic foreheads, there was a
truly bizarre programming language called Tutor.
(To quote Dave Barry, "I'm not making this up.")
Tutor had over 100 commands dedicated to handling user
inputs. All you had to do was remember about 40 of them
and you were OK. Mostly.
Tutor also had a command called randp which produced
a random number between 1 and a specified number. You could
think of it as a special type of Random object which kept
track of which numbers had already been selected so that
there would be no repeats. If randp were invoked
after all the numbers were used up, it returned 0.
Here is a sample usage:
int x;
Randp rand = new Randp(6);
x = rand.nextInt(); // randomly returns 5
x = rand.nextInt(); // randomly returns 2
x = rand.nextInt(); // randomly returns 6
x = rand.nextInt(); // randomly returns 4
x = rand.nextInt(); // randomly returns 1
x = rand.nextInt(); // randomly returns 3
x = rand.nextInt(); // returns 0
x = rand.nextInt(); // returns 0
Note that the Randp object never rejects a randomly generated
number before finding one that works. That is to say, it
never fails to find a new, unique number on its first try.
When it runs out of numbers, the object is essentially useless.
Your mission is to write a Randp class with a nextInt() method.
To do this, you should use an array of n elements to
keep track of which numbers have already been selected.
You will also need a private int called numsLeft which
keeps track of the number of unselected numbers.
nextInt() must be written so that its order of growth is O(1).
Randp should NOT extend Random. It is OK for Randp to use
Math.random() or a private object of type Random.
Here is starter code for this problem:
public class Randp {
private int[] nums;
private int numsLeft;
public Randp(int n) {
YOUR_CODE_HERE
}
private void initNums(int n) {
YOUR_CODE_HERE
}
public int nextInt() {
// Math.random() should never be called more than once
// when this method is called. Recursion is not allowed.
YOUR_CODE_HERE
}
}
You may wish to add other methods. What you cannot do is
create any other array, ArrayList, or other data structure.
You also cannot create any oher fields or change the data type
of any existing field. You get nums and numsLeft and that's it.
As always, work with your group mate(s)!