CS1101X: Programming Methodology Recitation 9 Recursion II
CS1101X Recitation #92 Task 1: Mystery (1/6) Study the code below and if you like, trace the recursive method mystery(). What is the smaller version of the task on which the recursive call works? How does the original problem relate to the smaller problem? What does the method compute?
CS1101X Recitation #93 Task 1: Mystery (2/6) public static void main(String[] args) { // code to read values into array - omitted System.out.print("Answer = " + mystery(list, list.length); } // pre-cond: n > 0 public static int mystery(int[] a, int n) { if (n == 1) return a[0]; else { int m = mystery(a, n-1); return a[n-1] > m ? a[n-1]: m; }
CS1101X Recitation #94 Task 1: Mystery (3/6) Is the code a “going-up”, “going-down” or “split-half” recursion? Write the other two versions. You may also try other versions.
CS1101X Recitation #95 Task 1: Mystery (4/6) “Going-up” version
CS1101X Recitation #96 Task 1: Mystery (5/6) “Split-half” version
CS1101X Recitation #97 Task 1: Mystery (6/6) Other version
CS1101X Recitation #98 Task 2: Transpose Matrix (1/6) To transpose a square matrix, the columns become the rows and the rows become columns. For example, the 5 5 matrix on the left below is transposed into the matrix on the right.
CS1101X Recitation #99 Task 2: Transpose Matrix (2/6) Write a recursive method to transpose a square matrix. Hint: If the original problem is an n n matrix that extends from m[0][0] to m[n-1][n-1], then the smaller problem is the (n-1) (n-1) matrix that extends from m[0][0] to m[n-2][n-2].
CS1101X Recitation #910 Task 2: Transpose Matrix (3/6) import java.util.*; class Transpose { public static void main(String[] args) { int[][] matrix = createMatrix(); System.out.println("Before transpose:"); printMatrix(matrix); transpose(matrix, matrix.length); System.out.println(); System.out.println("After transpose:"); printMatrix(matrix); }... } Write the methods createMatrix, printMatrix, and transpose.
CS1101X Recitation #911 Task 2: Transpose Matrix (4/6) createMatrix
CS1101X Recitation #912 Task 2: Transpose Matrix (5/6) printMatrix
CS1101X Recitation #913 Task 2: Transpose Matrix (6/6) transpose
CS1101X Recitation #914 End of Recitation #9