// Program to test solutions to problem #8 on the cse142 midterm, fall 2015. // Fill in your solution to sameDashes, then compile and run the program. import java.util.*; public class Test8 { public static boolean sameDashes(String s1, String s2) { // fill in your solution here // you can also rename the parameters above } // this is the sample solution public static boolean sameDashes2(String str1, String str2) { for (int i = 0; i < str1.length(); i++) { if (str1.charAt(i) == '-') { if (i >= str2.length() || str2.charAt(i) != '-') { return false; } } } for (int i = 0; i < str2.length(); i++) { if (str2.charAt(i) == '-') { if (i >= str1.length() || str1.charAt(i) != '-') { return false; } } } return true; } private static int count, failCount; private static Random r = new Random(); private static int DISPLAY = 20; // how many failed cases to display public static void main(String[] args) { for (int i = 0; i <= 5; i++) { test(i, i); } for (int j = 1; j <= 5; j++) { for (int i = 0; i <= 5; i++) { test(i + j, i); test(i, i + j); } } testOne("012345678901-", "0--"); testOne("0--", "012345678901-"); if (failCount == 0) { System.out.println("passed all tests"); } else { if (failCount > DISPLAY) { System.out.println("failed cases exeeds display max of " + DISPLAY); System.out.println(); } System.out.println("failed " + failCount + " of " + count + " tests"); } } public static void testOne(String s1, String s2) { count++; boolean display = failCount < DISPLAY; boolean answer = sameDashes2(s1, s2); try { boolean theirs = sameDashes(s1, s2); if (theirs != answer) { failCount++; if (display) { System.out.println("FAIL (\"" + s1 + "\", \"" + s2 + "\")"); System.out.println("correct = " + answer + ", theirs = " + theirs); System.out.println(); } } } catch (RuntimeException e) { failCount++; if (display) { int line = e.getStackTrace()[1].getLineNumber(); System.out.println("FAIL (\"" + s1 + "\", \"" + s2 + "\")"); System.out.println("threw " + e + " at line #" + line); System.out.println(); } } } public static void test(int len1, int len2) { test("", "", len1, len2); } public static void test(String s1, String s2, int count1, int count2) { if (count2 > 0) { test(s1, s2 + digit(), count1, count2 - 1); test(s1, s2 + "-", count1, count2 - 1); } else if (count1 > 0) { test(s1 + digit(), s2, count1 - 1, count2); test(s1 + "-", s2, count1 - 1, count2); } else { testOne(s1, s2); } } public static int digit() { return r.nextInt(2); } }