RandomLetterChoose AP A-thoughts and analysis

One of the 2016 AP Computer Science A questions, RandomLetterChooser ,  asked students to write a class declaration from scratch.

The constructor receives a parameter of non-null Strings

The class has a  getNext()  method that returns a random String  from that list . Each element in the list can only be returned once, and after all of the elements have been returned, the getNext()  method returns “NONE.”

There are many ways that students can solve this AP question and there are also many common pitfalls including

  • aliasing the constructor’s parameter
  • failing to ensure that all elements of the list have been returned prior to “NONE”

Students can also make their lives much more difficulty by  their choice of data structure.  In particular, an array makes this much more challenging than an ArrayList (the ArrayList code is at the very bottom btw)

Let’s examine several solutions to the first part of this question; some are 100% correct; some are partly correct.

Example Codeset 1:

What do you think about the code below?

Well, there are two major problems with the first example above

  1. this.words  becomes an alias of the parameter. So the student would lose points for modifying the original data structure.
  2.  The logic for returning “NONE” is flawed. After all of the array values are changed to “null”, there is no way to get out of the loop on lines 18-19  that randomly selects elements in the array over and over again.

Score on the first part : 5 out of 7 (-1 for modifying original data, -1 for not ensuring a correct return value)

Ok, so let’s give this another try and see if we can’t fix these errors

Example Codeset 2:

What do you think about the code below?

Hint: the only changes are in the constructor.

So,  unlike the first example, here we are not creating an alias of the parameter  (we’re making a copy into a new array) , so our only problem is the fact that we still run into an infinite loop after we have returned all the random values..

hmmm….

Score on the first part : 6 out of 7 (-1 for not ensuring a correct return value)

Example Codeset 3:

What do you think about the code?

Yes, a lot has changed here and codeset3 works fine . We create a copy of the original data structure (so don’t lose points for modifying original data) and we correctly resize our array over and over, shrinking it by 1 by removing the value that we’ll return.

Score on the first part : 7 out of 7

 

Score on the first part : 7 out of 7

 

As you can see from the code above, an arraylist greatly simplifies the solution  but most students did not see that this data structure was much more ideal for the question and, instead, decided to use arrays.