// Program to test solutions to problem #2 on the cse143 midterm, winter 2018. // Fill in your solution to groupChars, then compile and run the program. import java.util.*; public class Test2 { public static String groupChars(String s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static String groupChars2(String s) { if (s.length() == 0) { return "*"; } else if (s.length() < 3) { return "[" + s + "]"; } else { int last = s.length() - 1; return "(" + s.charAt(0) + groupChars(s.substring(1, last)) + s.charAt(last) + ")"; } } private static int testCount; private static int failCount; public static final int ERRORS_MAX = 25; public static void main(String[] args) { String[] data = {"", "a", "5", " ", "ab", ", ", "abc", "a b", "abcde", "a b ", "12345", "1 3 5", " 2 4 ", "123456", "1234567", "12345678", "123456789", "a", "the", "rain", "in", "Spain", "falls", "mainly", "recursively!"}; for (String s : data) { test(s); } if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(String s) { System.out.println("testing groupChars(\"" + s + "\")"); String result1 = groupChars2(s); boolean fail = false; try { String result2 = groupChars(s); if (!result1.equals(result2)) { fail = true; System.out.println("result should be \"" + result1 + "\", yours = \"" + result2 + "\""); } } catch (RuntimeException e) { int line = e.getStackTrace()[1].getLineNumber(); System.out.println("threw " + e + " at line #" + line); fail = true; } testCount++; if (fail) { System.out.println("failed"); failCount++; if (failCount > ERRORS_MAX) { System.out.println("exceeds " + ERRORS_MAX + " errors"); System.out.println("with " + testCount + " correct"); System.exit(0); } } else { System.out.println("passed"); } System.out.println(); } }