// Program to test solutions to problem #2 on the cse143 midterm, winter 2020. // Note that it does not test whether the method throws proper exceptions. // Fill in your solution to maxDigits, then compile and run the program. import java.util.*; import java.io.*; public class Test2 { public static int maxDigits(int x, int y) { // fill in your solution here // you can also rename the parameters above } private static int maxDigits(int n, int m, int result) { System.out.println("result = " + result); if (n < 10 && m < 10) { if (n % 10 > m % 10) { return result + n; } else { return result + m; } } else { if (n % 10 > m % 10) { return result + 10 * (n % 10) + 100 * maxDigits(n / 10, m / 10, result); } else { return result + 10 * (m % 10) + 100 * maxDigits(n / 10, m / 10, result); } } } // this is the sample solution public static int maxDigits2(int x, int y) { if (x < 0 || y < 0) { throw new IllegalArgumentException(); } if (x == 0 && y == 0) { return 0; } else { return 10 * maxDigits2(x / 10, y / 10) + Math.max(x % 10, y % 10); } } private static int testCount; private static int failCount; public static void main(String[] args) { test(3509, 6238); test(70519, 89420615); test(5555, 372); test(246802468, 135797531); test(128, 394); test(2384, 12); test(9, 318); test(8, 5); test(42, 95); test(42, 7596); test(7, 0); test(4723, 9815); test(0, 0); test(444, 318); test(4, 8982); test(17, 22566); test(375, 59119); test(246, 8642); if (failCount == 0) { System.out.println("passed all " + testCount + " tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int x, int y) { testOne(x, y); if (x != y) { testOne(y, x); } } public static void testOne(int x, int y) { testCount++; int result1 = maxDigits2(x, y); System.out.println("maxDigits(" + x + ", " + y + ") = " + result1); boolean fail = false; try { int result2 = maxDigits(x, y); if (result1 != result2) { fail = true; System.out.println("yours = " + result2); } } catch (RuntimeException e) { System.out.println("threw " + e); fail = true; } if (!fail) { System.out.println("passed"); } else { failCount++; System.out.println("failed"); } System.out.println(); } }