WordPairList free response answer 7

WordPairList free response problem from the 2018 AP Computer Science A Exam.

WordPairList is #2 from the from the 2018 AP Computer Science A Free Response problems.


Part (a) – WordPairList constructor

public WordPairList(String[] words)
  allPairs = new ArrayList<WordPair>();

  for(int i = 0; i < words.length; i++)
    for(int j = i + 1; j < words.length; j++)
      allPairs.add(new WordPair(words[i], words[j]));

Part (b) – numMaches method

public int numMatches()
  int matches = 0;

  for(WordPair wp : allPairs)

  return matches;

7 thoughts on “WordPairList free response answer

  1. Reply Angel Perez May 17,2018 3:45 pm

    Shouldn’t i < words.length – 1 for WordPairList?

    • Reply Brandon Horn May 17,2018 3:55 pm

      It could be, but since j starts at i+1 anyway, it doesn’t matter.

      My thought process was: Visit each word then visit the words after it. I wrote the code based on that. The last word has no words after it.

      I could definitely see: Visit each word except the last…

  2. Reply Angel Perez May 17,2018 4:04 pm

    What if length is, say, 5. i would go from 0 to 4, wouldn’t j try to access 4+1 giving out of bounds?

    • Reply Brandon Horn May 17,2018 4:07 pm

      No. The loop condition is checked prior to the first run of the loop body. j would be set to an invalid index, but the body of the inner loop would never run and the invalid index would never be accessed.

  3. Reply Angel Perez May 17,2018 4:07 pm

    Ah, never mind. I see. Thank you.

  4. Reply Jishan May 17,2018 11:40 pm

    I forgot I dealing with objects. So for part a I have everything same as you. However, I had


    And for part b, I forgot wordPairList is an object and treated it as a string arraylist
    int count;
    for(int i = 0; i < allPairs.length-1;i+=2){
    return count;

    Do you think I lost a lot of points because I misinterpreted the question ?

  5. Reply Ben R May 18,2018 8:48 am

    I used an array instead of an array list, with length of the wordlist. I know that its not the best way to do it. would i get full credit or not, and if not what would the deductions be for. I mean everything would work as intended, the only difference is that the array would have extra empty spots. I guess it may be -1, but could they take off more points and does an array cause any other errors?
    I also did array[i] = instead of list.add

Leave a Reply