Recursion FRQ
public class PopcornHack1 {
// 5! = 5 * 4! = 5 * (5 – 1)!
// 4! = 4 * 3! = 4 * (4 – 1)!
// ...
// 1! = 1
/**
* simple recursive method for finding factorial
*
* @param target factorial target
* @return factorial value
*/
public static int factorial(int target) {
if (target == 0) { // base case: if target is 0, return 1
return 1;
} else {
return target * factorial(--target); // recurse the product of target with the factorial of the target - 1
}
}
// unit tester
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
public class PopcornHack2 {
// Pro-tip: Think of why the index is stored as a parameter
// What are parameters usually used as?
/**
* adds the sum of the array from a given index to the end
*
* @param arr the given array to be added
* @param index starting index
* @return total sum
*/
public static int sumArray(int[] arr, int index) {
if (index == arr.length) { // prevent out-of-bound errors
return 0;
}
return arr[index] + sumArray(arr, ++index); // return recursive function of sum of array with index + 1
}
// unit tester
public static void main(String[] args) {
int[] arr = {5, 3, 6};
System.out.println(sumArray(arr, 1));
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class PopcornHack3 {
// Pro-tip: Set max to the first element
public static int[] sumArray(int[] arr, int index, int max) {
if (index >= arr.length - 1) {
return arr;
}
int minIndex = index;
for (int i = index + 1; i < arr.length; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
int temp = arr[index];
arr[index] = arr[minIndex];
arr[minIndex] = temp;
return sumArray(arr, index + 1, max);
}
}
public class PopcornHack4 {
// Pro tip: Remember what we learned from the 1D Array Popcorn Hack
public static int[][] sumArray(int[][] arr, int x_index, int y_index) {
int rows = arr.length;
int cols = arr[0].length;
// Base case: if the entire 2D array has been traversed, return the array
if (x_index >= rows || (x_index == rows - 1 && y_index >= cols)) {
return arr;
}
// Find the minimum element in the remaining part of the array
int minX = x_index, minY = y_index;
for (int i = x_index; i < rows; i++) {
for (int j = (i == x_index ? y_index : 0); j < cols; j++) {
if (arr[i][j] < arr[minX][minY]) {
minX = i;
minY = j;
}
}
}
// Swap the current element with the minimum element found
int temp = arr[x_index][y_index];
arr[x_index][y_index] = arr[minX][minY];
arr[minX][minY] = temp;
// Move to the next element
if (y_index + 1 < cols) {
return sumArray(arr, x_index, y_index + 1); // Move to the next column
} else {
return sumArray(arr, x_index + 1, 0); // Move to the next row
}
}
}