StringFormatter free response answer 3

StringFormatter free response problem from the 2016 AP Computer Science A Exam.

StringFormatter is #4 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) – totalLetters method

public static int totalLetters(List<String> wordList)
{
  int letters = 0;
  
  for(String word : wordList)
    letters += word.length();

  return letters;
}

Part (b) – basicGapWidth method

public static int basicGapWidth(List<String> wordList,
                                int formattedLen)
{
  int gaps = wordList.size() - 1;
  int spaces = formattedLen - totalLetters(wordList);
  return spaces / gaps;
}

I checked my logic for this on all 3 of the examples before I wrote the code. The examples often include special cases and are invaluable for checking logic.

Part (c) – format method

public static String format(List<String> wordList, int formattedLen)
{
  int width = basicGapWidth(wordList, formattedLen);
  int leftoverRemaining = leftoverSpaces(wordList, formattedLen);
  
  String formatted = "";
  for(int i = 0; i < wordList.size() - 1; i++)
  {
    formatted += wordList.get(i);
    
    for(int s = 1; s <= width; s++)
      formatted += " ";
    
    if(leftoverRemaining > 0)
    {
      formatted += " ";
      leftoverRemaining--;
    }
  }
  
  formatted += wordList.get(wordList.size() - 1);

  return formatted;
}

The loop to append the basic number of spaces could be moved outside the loop through wordList. I left my original solution since it made sense to me when I wrote it.

This problem requires careful allocation of spaces and careful consideration of the last word.

As the first set of comments below indicates, I got sloppy and wrote a loop without thinking about the bounds. Whenever you do this, you run the risk of being off by 1. (The solution above is correct.)

3 thoughts on “StringFormatter free response answer

  1. Jim Huggins May 5,2016 4:57 pm

    I think this puts extra padding at the end of the string ….

    • Brandon Horn May 5,2016 5:03 pm

      Just caught that during testing.

    • Brandon Horn May 5,2016 5:08 pm

      Jim is referring to my original solution using a foreach loop. The revised solution above is correct.

Comments are closed.