CSE 142 Final Key - Summer 2017 1. Reference Mystery 2 [12, 8, 5] 5 [2, 2, 5] 16 3 2. Array Simulation Original List Final List -------------------------------------------------------------- {2, 5, 8} {2, 5, 10} {3, 4, 7, 5} {3, 4, 10, 5} {2, 4, 6, 2, 6} {2, 4, 8, 2, 14} {4, 5, 8, 9, 3} {4, 5, 12, 9, 15} {1, 2, 8, 5, 10, 5, 4} {1, 2, 9, 5, 19, 5, 23} 3. Inheritance c b b b c 1 c 1 c 1 d 1 c 2 b 2 a 2 b 2 4. Token-Based File Processing. One possible solution appears below. public static void switchData(Scanner input) { String label = input.next(); System.out.print(label); while (input.hasNextInt()) { int n1 = input.nextInt(); if (input.hasNextInt()) { int n2 = input.nextInt(); System.out.print(" " + n2); } System.out.print(" " + n1); } System.out.println(); } 5. Line-Based File Processing. One possible solution appears below. public static void formatList(Scanner input) { while (input.hasNextLine()) { String text = input.nextLine(); if (!text.startsWith(".")) { System.out.println(text); } else { while (text.startsWith(".")) { System.out.print(" "); text = text.substring(1); } System.out.println("* " + text); } } } 6. Arrays. One possible solution appears below. public static int minGap(int[] list) { if (list.length < 2) return 0; else { int min = list[1] - list[0]; for (int i = 2; i < list.length; i++) { int gap = list[i] - list[i - 1]; if (gap < min) min = gap; } return min; } } 7. ArrayLists. One possible solution appears below. public static void rearrange(ArrayList list) { for (int i = 1; i <= list.size() / 2; i++) { int n = list.get(i); list.remove(i); list.add(n); } } 8. Critters. One possible solution appears below. public class Eagle extends Critter { private int count; private int max; public Eagle() { count = 0; max = 1; } public Action getMove(CritterInfo info) { count++; if (count == 2 * max) { count = 0; max++; } if (info.getFront() == Neighbor.EMPTY) { return Action.HOP; } else if (info.getFront() == Neighbor.WALL) { return Action.RIGHT; } else { return Action.INFECT; } } public Color getColor() { if (count < max) { return Color.RED; } else { return Color.BLUE; } } public String toString() { return "<>"; } } 9. Arrays. One possible solution appears below. public static int[] reverseSublist(int[] list, int from, int to) { int[] result = new int[to - from]; for (int i = 0; i < result.length; i++) { result[i] = list[to - i - 1]; } return result; } 10. Programming. One possible solution appears below. public static String encode(String s, int n) { String result = ""; for (int j = 0; j < n; j++) { for (int i = 0; i < s.length() - j; i += n) { result += s.charAt(i + j); } } return result; }