// Program to test solutions to problem #2 on the cse143 midterm, autumn 2014. // Fill in your solution to collapseSequences, then compile and run the // program. import java.util.*; public class Test2 { public static String collapseSequences(String s, char ch) { // fill in your solution here // you can also rename the parameters above } // this is the sample solution public static String collapseSequences2(String s, char ch) { if (s.length() < 2) { return s; } else { char first = s.charAt(0); if (first == ch && first == s.charAt(1)) { return collapseSequences2(s.substring(1), ch); } else { return s.charAt(0) + collapseSequences2(s.substring(1), ch); } } } private static int testCount; private static int failCount; public static void main(String[] args) { test("", 'a'); test("a", 'a'); test("a", 'b'); test("aa", 'a'); test("ab", 'a'); test("ba", 'a'); test("aab", 'a'); test("baa", 'a'); test("aabb", 'a'); test("abaabaaabaaaab", 'a'); test("abbaabbbaaabbb", 'a'); test("-this----has maaany--dashes---", '-'); test("eecckk!!, he's meeeping meep", 'e'); if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(String s, char target) { System.out.println("testing collapseSequences(\"" + s + "\", '" + target + "')"); String result1 = collapseSequences2(s, target); boolean fail = false; try { String result2 = collapseSequences(s, target); if (!result1.equals(result2)) { fail = true; System.out.println("result should be \"" + result1 + "\", yours = \"" + result2 + "\""); } } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println("threw " + e + " at line #" + line); fail = true; } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }