RandomStringChooser is #1 from the from the 2016 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap16_frq_computer_science_a.pdf

Part (a) RandomStringChooser class

public class RandomStringChooser
{
    private ArrayList<String> valuesRemaining;

    public RandomStringChooser(String[] values)
    {
        valuesRemaining = new ArrayList<String>();

        for(String value : values)
            valuesRemaining.add(value);
    }

    public String getNext()
    {
        if(valuesRemaining.size() == 0)
            return "NONE";

        int index = (int) (Math.random() * valuesRemaining.size());
        return valuesRemaining.remove(index);
    }
}

An ArrayList is an appropriate instance variable type since it allows removal of selected elements.

For more on working with Math.random() see Generating numbers with Math.random().

See Class writing order for a technique to respond to AP CS FR that request an entire class.

Part (a) RandomStringChooser class (alternate solution)

public class RandomStringChooser
{
    private String[] values;
    private int valuesRemaining;

    public RandomStringChooser(String[] vals)
    {
        values = new String[vals.length];

        for(int i = 0; i < values.length; i++)
            values[i] = vals[i];

        valuesRemaining = values.length;
    }

    public String getNext()
    {
        if(valuesRemaining == 0)
            return "NONE";

        int index = (int) (Math.random() * valuesRemaining);

        String selected = values[index];
        values[index] = values[valuesRemaining - 1];

        valuesRemaining--;

        return selected;
    }
}

An array can be used as an instance variable. Some effort is then required to ensure that each element can be selected only once. Note that the problem prohibits modification of the parameter passed to the constructor, so a copy must be made.

Part (b) RandomLetterChooser constructor

public RandomLetterChooser(String str)
{
    super(getSingleLetters(str));
}

It is permissible to call a static method within a call to a superclass constructor.

Alternatively, nothing in the problem description appears to prohibit declaring additional methods in part (a). A default constructor and a mutator method that accepts an array could be created.

See Inheritance and polymorphism for details including how to write subclasses and subclass constructors.

2016 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on RandomStringChooser