// Program to test solutions to problem #8 on the cse142 midterm, autumn 2013. // Fill in your solution to weave, then compile and run the program. import java.util.*; public class Test8 { public static int weave(int x, int y) { // fill in your solution here // you can also rename the parameters above } // this is the sample solution public static int weave2(int x, int y) { int result = 0; int multiplier = 1; while (x != 0 || y != 0) { result = result + multiplier * (x % 10 * 10 + y % 10); multiplier = multiplier * 100; x = x / 10; y = y / 10; } return result; } private static int count, failCount, reversed; public static void main(String[] args) { testBoth(128, 394); testBoth(2384, 12); testBoth(9, 318); testBoth(0, 1234); testBoth(1111, 2222); testBoth(11, 22222); testBoth(3, 8); testBoth(35, 82); testBoth(0, 0); testBoth(42, 42); if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + count + " tests"); if (reversed > 0) { System.out.println("reversed " + reversed); } } } public static void testBoth(int x, int y) { test(x, y); if (x != y) { test(y, x); } } public static void test(int x, int y) { count++; System.out.println("testing weave(" + x + ", " + y + ")"); int n2 = weave2(x, y); System.out.println("expected = " + n2); int n1 = 0; boolean fail = false; try { n1 = weave(x, y); } catch (RuntimeException e) { int line = e.getStackTrace()[1].getLineNumber(); System.out.println("threw " + e + " at line #" + line); fail = true; } if (!fail && n1 != n2) { System.out.println("actual = " + n1); String s1 = pad("" + n1); String s2 = pad("" + n2); if (reversePairs(s1).equals(s2)) { System.out.println("reversed"); reversed++; } fail = true; } if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } public static String pad(String s) { if (s.length() % 2 == 0) return s; else return "0" + s; } public static String reversePairs(String s) { String result = ""; for (int i = 0; i < s.length(); i += 2) { result = "" + s.charAt(i) + s.charAt(i + 1) + result; } return result; } }