// Program to test solutions to problem #8 on the cse142 midterm, winter 2018. // Fill in your solution to digitsInARow, then compile and run the program. import java.util.*; public class Q8Verifier { public static int digitsInARow(int n) { // fill in your solution to Q8 here } // this is the sample solution public static int digitsInARow2(int n) { int count = 1; int max = 1; int last = n % 10; n /= 10; while (n > 0) { int next = n % 10; if (next == last) { count++; if (count > max) { max = count; } } else { count = 1; } last = next; n /= 10; } return max; } private static int count, failCount; private static Random r; public static final int ERRORS_MAX = 20; public static void main(String[] args) { failCount = 0; r = new Random(); for (int i = 0; i <= 10; i++) { test(i); } if (failCount == 0) { System.out.println("PASSED all " + count + " tests"); } } public static void test(int i) { int[] data = new int[i]; test(data, 0); } public static void test(int[] data, int index) { if (index == data.length) { // System.out.println("Testing " + Arrays.toString(data)); count++; int num = 0; for (int i = 0; i < data.length; i++) { num *= 10; num += data[i]; } boolean fail = false; RuntimeException except = null; int result1 = 0, result2 = 0; try { result1 = digitsInARow(num); } catch (RuntimeException e) { fail = true; except = e; } result2 = digitsInARow2(num); fail = fail || result1 != result2; if (fail) { if (except != null) { StackTraceElement[] trace = except.getStackTrace(); int line = trace[0].getLineNumber(); System.out.println("FAIL with exception for " + num + " at line#" + line); } else { System.out.println("FAIL for " + num); } System.out.println("Correct: " + result2); System.out.println("Yours : " + result1); System.out.println(); failCount++; if (failCount > ERRORS_MAX) { System.out.println("exceeds " + ERRORS_MAX + " errors"); System.out.println("with " + count + " correct"); System.exit(0); } } } else { for (int i = 1; i <= data.length - index; i++) { int digit = r.nextInt(10); for (int j = index; j < index + i; j++) { data[j] = digit; } test(data, index + i); } data[index] = r.nextInt(10); test(data, index + 1); } } }