This chapter builds on the previous two chapters, creating a more complete composite object from the Outcome and Bin classes we have already defined. We’ll introduce some basic subclass constructor techniques, also.
The wheel has two responsibilities: it is a container for the Bins and it picks one Bin at random. We’ll also have to look at how to initialize the various Bins that comprise a standard Roulette wheel.
In this case, the choice of the winning Bin will be selected by a random numeric index. We need some kind of sequential collection.
This makes the java.util.Vector very appealing.
One consequence of using a sequential collection is that we have to choose an index for the various Bins. Each Bin contains a variety of individual Outcomes. However, each single number Outcome will be unique to each Bin.
The index values of 1 to 36 become the index to their respective Bins. The Bin at index 1 is the only bin which contains Outcome( "1", 35 ).
We have a small problem, however, with 0 and 00: we need two separate indexes. While 0 is a valid index, what do we do with 00?
Enumerate some possible solutions before reading on.
The random number generator in java.util.Random does everything we need. We can use the generator’s nextInt() method to return integers.
Testability. Note that testing a class using random numbers isn’t really the best policy. To do testing properly, we’ll need to create a non-random random number generator that we can use in place of the published library random number generator.
To create a non-random random-number generator, we can so something like the following.
Constructing the entire collection of Bins would be a tedious undertaking. We’ll apply a common OO principle of deferred binding and work on that algorithm later, after we have the basic design for the Wheel finished.
Contains the individual Bin instances.
java.util.Vector. This is always a new Vector( 38 ).
|Parameter:||rng (java.util.Random) – A “random” number generator. For testing, this may be a non-random number generator.|
Creates a new wheel with 38 empty Bins. It will also create a new random number generator instance.
At the present time, this does not do the full initialization of the Bins. We’ll rework this in a future exercise.
Generates a random number between 0 and 37, and returns the randomly selected Bin.
Be sure to note that the Random.nextInt() method uses the size of the bins collection to return values from 0 to the size of the collection. Typically there are 38 values, numbered from 0 to 37.
|Returns:||A Bin selected at random from the wheel.|
We need a controlled kind of random number generation for testing purposes.
We’ll define a class NonRandom that extends java.util.Random, but provides a more testable sequence of values. One approach is to simply return a given integer value.
There are three deliverables for this exercise. The new class and the unit test will have Javadoc comments or Python docstrings.