Skip to content

Instantly share code, notes, and snippets.

@CompSciRocks
Last active November 28, 2018 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CompSciRocks/31bcbecac962228883c4bf15d3963e07 to your computer and use it in GitHub Desktop.
Save CompSciRocks/31bcbecac962228883c4bf15d3963e07 to your computer and use it in GitHub Desktop.
Working solution to the 2016 AP Computer Science Free Response Question String Formatter - https://compsci.rocks/string-formatter-solution/
public static int leftoverSpaces( List<String> wordList, int formattedLen ) {
/* Implementation not shown */
return formattedLen - totalLetters( wordList ) - ( basicGapWidth( wordList, formattedLen ) * wordList.size() - 1 );
}
public static int totalLetters( List<String> wordList ) {
/* Part A */
int let = 0;
for ( String word : wordList ) {
let += word.length();
}
return let;
}
public static int basicGapWidth( List<String> wordList, int formattedLen ) {
/* Part B */
return ( formattedLen - totalLetters( wordList ) ) / ( wordList.size() - 1 );
}
public static String format( List<String> wordList, int formattedLen ) {
/* Part C */
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.trim();
}
public class StringFormatter {
public static int totalLetters( List<String> wordList ) {
/* Part A */
}
public static int basicGapWidth( List<String> wordList, int formattedLen ) {
/* Part B */
}
public static int leftoverSpaces( List<String> wordList, int formattedLen ) {
/* Implementation not shown */
}
public static String format( List<String> wordList, int formattedLen ) {
/* Part C */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment