// Arup Guha
// 4/30/2018
// Solution to 2016 AP Computer Science FR Question 4: String Formatter

import java.util.*;

public class StringFormatter {

	public static String[] ex1 = {"AP", "COMP", "SCI", "ROCKS"};
	public static String[] ex2 = {"GREEN", "EGGS", "AND", "HAM"};
	public static String[] ex3 = {"BEACH", "BALL"};

	public static void main(String[] args) {

		// Example 1
		ArrayList<String> tmp = new ArrayList<String>();
		for (String s: ex1) tmp.add(s);
		System.out.println(format(tmp, 20));

		// Example 2
		tmp.clear();
		for (String s: ex2) tmp.add(s);
		System.out.println(format(tmp, 20));

		// Example 3
		tmp.clear();
		for (String s: ex3) tmp.add(s);
		System.out.println(format(tmp, 20));
	}

	// Returns the sum of the lengths of the words in wordList.
	public static int totalLetters(List<String> wordList) {
		int res = 0;
		for (String s: wordList)
			res += s.length();
		return res;
	}

	// Returns the basic gap width - just do int division btw spaces left and # of gaps.
	public static int basicGapWidth(List<String> wordList, int formattedLen) {
		return (formattedLen-totalLetters(wordList))/(wordList.size()-1);
	}

	// Returns the left over # of spaces after using the basic gap width.
	public static int leftoverSpaces(List<String> wordList, int formattedLen) {
		return (formattedLen-totalLetters(wordList))%(wordList.size()-1);
	}

	// Returns the formatted string.
	public static String format(List<String> wordList, int formattedLen) {

		// Just so I don't have to type these really long things...
		int basic = basicGapWidth(wordList, formattedLen);
		int extra = leftoverSpaces(wordList, formattedLen);

		// Just add this first.
		String res = wordList.get(0);

		// Loop through each word.
		for (int i=1; i<wordList.size(); i++) {

			// Calculate the number of spaces.
			int numSp = i <= extra ? basic+1 : basic;

			// Add the spaces.
			for (int j=0; j<numSp; j++) res += " ";

			// Now add the next word.
			res += wordList.get(i);
		}

		return res;
	}
}
