Other 2016 FR Questions FR other years Be Prepared Home
A-4
Part (a)
  public static int totalLetters(List wordList)
  {
    int count = 0;

    for (String word : wordList)
      count += word.length();

    return count;
  }


Part (b)
  public static int basicGapWidth(List wordList,
                                  int formattedLen)
  {
    return (formattedLen - totalLetters(wordList)) / (wordList.size() - 1); 1
  }
Notes:
  1. The number of gaps is one less than the number of words


Part (c)
  public static String format(List<String> wordList, int formattedLen)
  {
    int gapWidth = basicGapWidth(wordList, formattedLen); 1
    String gap = "";
    for (int count = 0; count < gapWidth; count++)
      gap += " ";

    int extraSpaces = leftoverSpaces(wordList, formattedLen);

    String formattedStr = "";

    for (int i = 0; i < wordList.size() - 1; i++)
    {
      formattedStr += wordList.get(i) + gap;
      if (extraSpaces > 0) 2
      {
        formattedStr += " ";
        extraSpaces--;
      }
    }
    formattedStr += wordList.get(wordList.size() - 1); 3

    return formattedStr;
  }
Notes:
  1. It makes sense to form the basic gap string first.
  2. Add an extra space if there are any left.
  3. Or:
        ...
        String formattedStr = wordList.get(0);
    
        for (int i = 1; i < wordList.size(); i++)
        {
          if (extraSpaces > 0)
          {
            formattedStr += " ";
            extraSpaces--;
          }
          formattedStr += gap + wordList.get(i);
        }

Other 2016 FR Questions | Back to Contents

Copyright © 2016 by Skylight Publishing
support@skylit.com