Sprint View

2016 FRQ 4

11 min read

Prompt & Questions

AP FRQ Q4

(a) Write the StringFormatter method totalLetters, which returns the total number of letters in the words in its parameter wordList. For example, if the variable List words is ["A", "frog", "is"], then the call StringFormatter.totalLetters (words) returns 7. You may assume that all words in wordList consist of one or more letters.
Complete method totalletters below.

  • Returns the total number of letters in wordList.
  • Precondition: wordList contains at least two words, consisting of letters only. public static int totalletters (List wordList)

(b) Write the StringFormatter method basicGapWiath, which returns the basic gap width as defined earlier.

Class Information

  • public class StringFormatter
  • public static int totalLetters(List<String> wordList)
  • public static int basicGapWidth(List<String> wordList, int formattedLen)
  • public static int leftoverSpaces(List<String> wordList, int formattedLen)
  • public static String format(List<String> wordList, int formattedLen)

Assume that totalLetters works as specified regardless of what you wrote in part (a). You must use totalLetters appropriately to receive full credit.

Complete method basicGapwidth below.

  • Returns the basic gap width when wordList is used to produce a formatted string of formattedLen characters.
  • Precondition: wordList contains at least two words, consisting of letters only.
  • formattedlen is large enough for all the words and gaps.

(c) Write the StringFormatter method format, which returns the formatted string as defined earlier. The StringFormatter class also contains a method called leftoverSpaces, which has already been implemented. This method returns the number of leftover spaces as defined earlier and is shown below.

  • Returns the number of leftover spaces when wordList is used to produce a formatted string of formattedLen characters.
  • Precondition: wordList contains at least two words, consisting of letters only formattedlen is large enough for all the words and gaps.

Public static int leftoverSpaces (List wordList, int formattedLen) {/ * implementation not shown * / }

Class Information

  • public class StringFormatter
  • public static int totalletters (List<String > wordList)
  • public static int basicGapWidth (List<String> wordList, int formattedLen)
  • public static int leftoverSpaces (List<String > wordList, int formattedLen)
  • public static String format (List<String > wordList, int formattedLen)

Assume that basicGapWidth works as specified, regardless of what you wrote in part (b). You must use basicGapWidth and leftoverSpaces appropriately to receive full credit. Complete method format below.

  • Returns a formatted string consisting of the words in wordList separated by spaces.
  • Precondition: The wordList contains at least two words, consisting of letters only. formattedLen is large enough for all the words and gaps.
  • Postcondition: All words in wordList appear in the formatted string.
    • The words appear in the same order as in wordList.
    • The number of spaces between words is determined by basicGapWidth and the distribution of leftoverSpaces from left to right, as described in the question.

public static String format (List<String › wordList, int formattedLen)

Scoring Guide

Part (a) totalLetters (2 points)

Intent: Calculate the total number of letters in a list of words

  • +1 Accesses all strings in wordList and adds length of each to accumulated count (no bounds errors)
  • +1 Initializes and returns accumulated count

Part (b) basicGapWidth (2 points)

Intent: Calculate the minimum number of spaces (basic gap width) to be placed between each word in the formatted string

  • +1 Calls totalLetters correctly and uses result
  • +1 Returns correct calculated value

Part (c) format (5 points)

Intent: Return a formatted string consisting of words from wordList separated by one or more spaces

  • +1 Calls basicGapWidth and leftoverSpaces correctly and uses results
  • +1 Adds all strings in wordList to formatted string in original order (no bounds errors)
  • +1 Inserts basicGapWidth spaces between each pair of words in formatted string
  • +1 Inserts one space between first leftoverSpaces pairs of words in formatted string
  • +1 Initializes and returns formatted string (no extra or deleted characters)

Explanation

Part (a): totalLetters

The Simple Explanation

Think of this as a counting task. You have a bucket of words, and you need to count every single letter in every word to find the grand total.

The Proper Explanation

To implement this, you must iterate through the List<String> wordList. As you access each string, you call the .length() method to determine how many characters it contains. This value is added to an “accumulator” variable (a sum).

Initialization: You must start your sum at 0. The Loop: A standard for loop or an enhanced for-each loop is used to visit every element. The Return: Once the loop finishes, you return the final accumulated integer.


Part (b): basicGapWidth

The Simple Explanation

Imagine you are trying to fit words onto a line of a specific length. After placing the words, you see how much empty space is left. You then divide that empty space by the number of “gaps” between the words to see the minimum amount of space each gap gets.

The Proper Explanation

This method requires a mathematical calculation based on three variables: the total line length (formattedLen), the total letters, and the number of gaps.

Mandatory Step: You must call totalLetters(wordList) to get the count of characters. Calculate Total Spaces: Subtract the total letters from formattedLen. Calculate Gaps: In a list of words, there are always gaps. The Division: Divide the total spaces by the number of gaps. Because both are integers, Java will perform integer division, which correctly gives the “minimum” (floor) number of spaces for each gap.

Code Runner Challenge

FRQ Boilerplate Code

View IPYNB Source
graph TD
    A[wordList: List of Strings] --> B(totalLetters)
    B --> C[Sum of lengths of all strings in wordList]
    
    subgraph Part B: basicGapWidth
    D[formattedLen]
    C --> E[Total Spaces = formattedLen - totalLetters]
    D --> E
    F[Number of Gaps = wordList.size - 1]
    E --> G{Integer Division}
    F --> G
    G --> H[Return basicGapWidth]
    end
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Part (c): format

The Simple Explanation

This is where you build the actual string. You place the first word, then add the “basic” amount of spaces. If there were any “leftover” spaces that didn’t divide evenly in Part (b), you tuck one extra space into the current gap. You repeat this until you reach the last word.

The Proper Explanation

The implementation uses a “fencepost” algorithm—meaning you handle the last word differently to avoid adding trailing spaces at the end of the string.

  1. Preparation: Call basicGapWidth and leftoverSpaces to get the necessary measurements.
  2. The Loop: Iterate from the first word up to (but not including) the last word.
  3. Building Gaps:
    • Append the current word to your result string.
    • Append the basicGapWidth number of spaces using a small nested loop.
    • Distribute Leftovers: Check if leftoverSpaces is greater than 0. If it is, append one extra space and decrement the leftoverSpaces counter. This ensures leftover spaces are added “left to right”.
  4. The “Fencepost”: After the loop, append the very last word from the list to finish the string.

Code Runner Challenge

Total Letters Method

View IPYNB Source
flowchart TD
    Start([Start format method]) --> Init[Initialize empty formatted String]
    Init --> GetVals[Call basicGapWidth and leftoverSpaces]
    
    subgraph Loop: Process first N-1 words
    Step1[Get word at index i] --> Step2[Add word to String]
    Step2 --> Step3[Add basicGapWidth spaces]
    Step3 --> LeftoverCheck{Is leftoverSpaces > 0?}
    LeftoverCheck -- Yes --> AddExtra[Add 1 extra space & decrement leftovers]
    AddExtra --> NextIter[Increment i]
    LeftoverCheck -- No --> NextIter
    end
    
    NextIter --> FinalWord[Add the very last word from wordList]
    FinalWord --> Return[Return final formatted String]
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

FRQ

// CODE_RUNNER: <challenge text>

Code Runner Challenge

Basic Gap Width Method

View IPYNB Source
// CODE_RUNNER: FRQ Boilerplate Code

import java.util.List;
import java.util.Arrays;

public class Main {
    public static int totalLetters(List<String> wordList) {
        // HINT: Initialize a counter to 0
        // Loop through each word in wordList
        // Add the length of each word to the counter
        // Return the total
        return 0; // TODO: Replace with actual code
    }

    public static int basicGapWidth(List<String> wordList, int formattedLen) {
        // HINT: 
        // 1. Call totalLetters(wordList) to get total letters
        // 2. Subtract total letters from formattedLen to get total spaces
        // 3. Divide by (wordList.size() - 1) to get gap width
        return 0; // TODO: Replace with actual code
    }

    public static int leftoverSpaces(List<String> wordList, int formattedLen) {
        // HINT: 
        // 1. Compute total letters using totalLetters(wordList)
        // 2. Compute total spaces: formattedLen - total letters
        // 3. Compute leftover spaces: total spaces % (wordList.size() - 1)
        return 0; // TODO: Replace with actual code
    }

    public static String format(List<String> wordList, int formattedLen) {
        // HINT:
        // 1. Get gap width using basicGapWidth(wordList, formattedLen)
        // 2. Get leftover spaces using leftoverSpaces(wordList, formattedLen)
        // 3. Loop through words, append each word and gap spaces
        // 4. Distribute leftover spaces from left to right
        return ""; // TODO: Replace with actual code
    }

    // =========================
    // MAIN: Test your methods
    // =========================
    public static void main(String[] args) {
        List<String> words = Arrays.asList("This", "is", "a", "test");
        int formattedLen = 20;

        // Test totalLetters
        System.out.println("Total letters: " + totalLetters(words));

        // Test basicGapWidth
        System.out.println("Basic gap width: " + basicGapWidth(words, formattedLen));

        // Test leftoverSpaces
        System.out.println("Leftover spaces: " + leftoverSpaces(words, formattedLen));

        // Test format
        System.out.println("Formatted line: \"" + format(words, formattedLen) + "\"");
    }
}

Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Official Solution

Part A

// CODE_RUNNER: <challenge text>

Code Runner Challenge

Integration

View IPYNB Source
// CODE_RUNNER: Total Letters Method

import java.util.List;
import java.util.Arrays;

public class Main {

    // Total letters method implementation as given by collegeboard
    public static int totalLetters(List<String> wordList) {
        int total = 0;
        for (String word : wordList) {
            total += word.length();
        }
        return total;
    }

    // Testing the method
    public static void main(String[] args) {
        System.out.println(totalLetters(Arrays.asList("hello", "world", "java")));
    }
}

Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

// CODE_RUNNER: <challenge text>

Part B

// CODE_RUNNER: Basic Gap Width Method

import java.util.List;
import java.util.Arrays;

public class Main {

    // Original method, exactly as written from collegeboard
    public static int basicGapWidth(List<String> wordList, int formattedLen) {
        return (formattedLen - totalLetters(wordList)) / (wordList.size() - 1);
    }

    // A minimal totalLetters method, required for your code to compile
    public static int totalLetters(List<String> wordList) {
        int total = 0;
        for (String word : wordList) {
            total += word.length();
        }
        return total;
    }

    // Main method to test basicGapWidth
    public static void main(String[] args) {
        List<String> words = Arrays.asList("This", "is", "a", "test");
        int formattedLen = 20;

        int gapWidth = basicGapWidth(words, formattedLen);
        System.out.println("Basic gap width: " + gapWidth); // Expected output: 4
    }
}

Main.main(null);

// CODE_RUNNER: <challenge text>

Part C

// CODE_RUNNER: Integration

import java.util.List;
import java.util.Arrays;

public class Main {

    // implementations of past methods so code runs
    public static int totalLetters(List<String> wordList) {
        int total = 0;
        for (String word : wordList) {
            total += word.length();
        }
        return total;
    }

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

    public static int leftoverSpaces(List<String> wordList, int formattedLen) {
        return (formattedLen - totalLetters(wordList)) % (wordList.size() - 1);
    }

    // Your original method solution from collegeboard
    public static String format(List<String> wordList, int formattedLen) {
        String formatted = "";
        int gapWidth = basicGapWidth(wordList, formattedLen);
        int leftovers = leftoverSpaces(wordList, formattedLen);
        for (int w = 0; w < wordList.size() - 1; w++) {
            formatted = formatted + wordList.get(w);
            for (int i = 0; i < gapWidth; i++) {
                formatted = formatted + " ";
            }
            if (leftovers > 0) {
                formatted = formatted + " ";
                leftovers--;
            }
        }
        formatted = formatted + wordList.get(wordList.size() - 1);
        return formatted;
    }

    // Main method to test format
    public static void main(String[] args) {
        List<String> words = Arrays.asList("This", "is", "a", "test");
        int formattedLen = 20;

        String formattedLine = format(words, formattedLen);
        System.out.println("Formatted line: '' + formattedLine + '' ");
    }
}

Main.main(null);

Course Timeline