Key to CSE142 Sample Final, Autumn 2017 1. Reference Mystery. The program produces the following output. 2 [12, 8, 5] 5 [2, 2, 5] 16 3 2. Original List Final List -------------------------------------------------------------- {2, 5, 6, 9} {2, 3, 5, 9} {1, 3, 3, 5, 8} {1, 2, 4, 7, 8} {4, 4, 5, 8, 2} {4, 4, 6, 9, 2} {3, 6, 9, 12, 15} {3, 4, 6, 9, 15} {2, 4, 6, 8, 10, 12} {2, 3, 5, 8, 12, 12} 3. Inheritance. The output produced is as follows. d a d d b 1 b 1 d 1 c 1 b 2 b 2 d 2 d 2 4. Token-Based File Processing. One possible solution appears below. public static void tallyScores(Scanner input) { while (input.hasNext()) { String name = input.next(); System.out.print(name + ":"); int points = 0; int count = 0; while (input.hasNextInt()) { int nextPoints = input.nextInt(); points += nextPoints; count++; System.out.print(" " + nextPoints); } System.out.println(); double average = (double) points / count; System.out.println("average = " + average); } } 5. Line-Based File Processing. One possible solution appears below. public static void underline(Scanner input) { while (input.hasNextLine()) { String text = input.nextLine(); if (!text.startsWith(".")) { System.out.println(text); } else { System.out.println(text.substring(1)); for (int i = 1; i <= text.length() - 1; i++) { System.out.print("-"); } System.out.println(); } } } 6. Arrays. One possible solution appears below. public static int numUnique(int[] list) { if (list.length == 0) { return 0; } else { int count = 1; for (int i = 1; i < list.length; i++) { if (list[i] != list[i - 1]) { count++; } } return count; } } 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 Raptor extends Critter { private boolean east; private int stompCount; public Raptor(boolean startEast) { east = startEast; stompCount = 0; } public boolean eat() { stompCount = 20; east = !east; return true; } public Direction getMove() { if (stompCount > 0) { stompCount--; if (stompCount % 2 == 1) { return Direction.NORTH; } else { return Direction.SOUTH; } } else { if (east) { return Direction.EAST; } else { return Direction.WEST; } } } } 9. Arrays. One possible solution appears below. public static int[] collapse(int[] list) { int size = list.length / 2; if (list.length % 2 == 1) { size++; } int[] result = new int[size]; for (int i = 0; i < list.length / 2; i++) { result[i] = list[i * 2] + list[i * 2 + 1]; } if (list.length % 2 == 1) { result[result.length - 1] = list[list.length - 1]; } return result; } 10. Programming. One possible solution appears below. public static void sumCount(int[] data, int[] sum, int[] count) { for (int i = 0; i < 4; i++) { sum[i] = 0; count[i] = 0; } for (int i = 0; i < data.length; i++) { int index = (i % 7 + 1) / 2; if (data[i] > 0) { count[index]++; sum[index] += data[i]; } } }