package ua.nure.jfn.task3;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Part2 {

	private static final String PATH = "part2.txt";

	public static void main(String[] args) {
		String lines = Utils.getContent(PATH);
		for (int j = 1; j < 10; j++)
			System.out.println(convert(lines, j));
	}

	public static String convert(String input, int k) {
		int lengths = 0;

		for (String word : input.split(" "))
			lengths |= 1 << (word.length() - 1);

		int kLength = 0;
		int currLength = 0;

		for (; lengths > 0 && currLength != k; lengths >>= 1) {
			kLength++;

			if ((lengths & 1) == 1)
				currLength++;
		}

		if (currLength != k)
			kLength = 0;

		Matcher matcher = Pattern.compile(String.format("(?<=^|\\s)(\\S{%d})(?=$|\\s)", kLength)).matcher(input);

		String result = "";
		while (matcher.find())
			if (!result.matches(".*(?<=^|\\s)" + matcher.group(1) + "(?=$|\\s).*"))
				result += " " + matcher.group(1);

		if (result != "")
			result = k + ":" + result;

		return result;
	}

}
