The Die class, shown below, represents a die.

public class Die
{
    /** The number of sides */
    private int sides;

    /**
     * Creates a Die with the specified number of sides
     * @param s the number of sides
     */
    public Die(int s)
    {
        sides = s;
    }
    
    /**
     * Rolls the die, returning a random side
     * @return a random side
     */
    public int roll()
    {
        return (int) (Math.random() * sides) + 1;
    }
}

You will write WeightedDie, which is a subclass of Die.

A WeightedDie has a weight that favors a certain side. When a WeightedDie is rolled, the weight increases the chance that the favored side number is returned. The algorithm below is used to roll a WeightedDie.

if(a random number is less than the weight)
    return the favored side
else
    roll like a Die

The WeightedDie class contains an additional method, getFavoredSide, that returns the favored side.

The following table contains a sample code execution sequence and the corresponding results. The code execution sequence appears in a class other than Die or WeightedDie.

Statement Return value (blank if no value) Explanation
Die d =
    new WeightedDie(6, 3, 0.1);
Constructs a 6 sided die favoring side 3 with a weight of 0.1
d.roll(); One of: 1, 2, 3, 4, 5, or 6 Side 3 is favored, but any of the 6 sides could be returned.
WeightedDie wd2 =
    new WeightedDie(6, 2, 1.0);
Constructs a 6 sided die favoring side 2 with a weight of 1.0
wd2.roll(); 2 A weight of 1.0 guarantees that the favored side, 2, will be returned on every roll.
wd2.getFavoredSide(); 2 Side 2 is favored.

Write the complete WeightedDie class. Your implementation must meet all specifications and conform to the examples shown in the preceding table.

The WeightedDie class must not duplicate state or behavior from Die.

Solution & comments

See the WeightedDie solution or review it with AP CS Tutor Brandon Horn.

Comment on WeightedDie