Lab 2 – Recursion
Part 1 – Recursive methods¶
Task 1 – Print an array¶
Print the elements of A from position start to the end, recursively.
static void print(int[] A, int start) {
// ToDo
}Solution
static void print(int[] A, int start) {
if (start < A.length) {
System.out.print(A[start] + " ");
print(A, start + 1);
}
}Task 2 – Print an array in reverse order¶
print_Reverse(A, 0) prints 4 3 2 1 for A = {1, 2, 3, 4}, and print_Reverse(A, 2)
prints 4 3. Hint: move one line of Task 1 (the backward phase).
static void print_Reverse(int[] A, int start) {
// ToDo
}Solution
static void print_Reverse(int[] A, int start) {
if (start < A.length) {
print_Reverse(A, start + 1); // print the rest first
System.out.print(A[start] + " ");
}
}Task 3 – Convert a number to base b¶
Print n in base b (2 ≤ b ≤ 16): convert(13, 2) prints 1101. The last digit is
n % b; the other digits are those of n / b.
static void convert(int n, int b) {
// ToDo
}Solution
static void convert(int n, int b) {
if (n >= b)
convert(n / b, b); // the higher digits first
System.out.print("0123456789ABCDEF".charAt(n % b));
}Task 4 – Palindrome¶
A string is a palindrome if it reads the same in both directions ("level", "racecar").
static boolean palindrome(String s) {
// ToDo: compare the first and the last character, then the middle part
}Solution
static boolean palindrome(String s) {
if (s.length() <= 1)
return true;
if (s.charAt(0) != s.charAt(s.length() - 1))
return false;
return palindrome(s.substring(1, s.length() - 1));
}Task 5 – Reverse a string¶
static String reverse(String s) {
// ToDo
}Solution
static String reverse(String s) {
if (s.isEmpty())
return s;
return reverse(s.substring(1)) + s.charAt(0);
}Task 6 – The minimum of an array¶
static int min(int[] A, int start) {
// ToDo: the minimum of A[start..A.length-1]
}Solution
static int min(int[] A, int start) {
if (start == A.length - 1)
return A[start];
return Math.min(A[start], min(A, start + 1));
}Task 7 – Recursive binary search¶
Return the index of key in the sorted array A[start..end], or -1.
static int binarySearch(int[] A, int start, int end, int key) {
// ToDo
}Solution
static int binarySearch(int[] A, int start, int end, int key) {
if (start > end)
return -1; // empty range: not found
int mid = (start + end) / 2;
if (A[mid] == key)
return mid;
if (key < A[mid])
return binarySearch(A, start, mid - 1, key);
return binarySearch(A, mid + 1, end, key);
}Test your methods¶
int[] A = {1, 2, 3, 4};
print(A, 0); System.out.println();
print_Reverse(A, 0); System.out.println();
print_Reverse(A, 2); System.out.println();
convert(13, 2); System.out.println();
convert(255, 16); System.out.println();
System.out.println(palindrome("racecar") + " " + palindrome("level")
+ " " + palindrome("java"));
System.out.println(reverse("recursion"));
System.out.println(min(new int[]{12, 3, 24, 1, 6}, 0));
int[] S = {10, 12, 13, 16, 18, 22, 25, 27, 32, 37, 41, 65, 72, 92, 96};
System.out.println(binarySearch(S, 0, S.length - 1, 18) + " "
+ binarySearch(S, 0, S.length - 1, 50));Expected output:
1 2 3 4
4 3 2 1
4 3
1101
FF
true true false
noisrucer
1
4 -1Part 2 – Use the JDK¶
Challenge 1 – All binary strings of length n¶
Write bits(String prefix, int n, List<String> out), which adds to out every string of
n bits that starts with prefix: choose "0" or "1", then recurse with n - 1.
Solution
static void bits(String prefix, int n, List<String> out) {
if (n == 0) {
out.add(prefix);
return;
}
bits(prefix + "0", n - 1, out);
bits(prefix + "1", n - 1, out);
}List<String> all = new ArrayList<>();
bits("", 3, all);
System.out.println(all);
System.out.println(all.size() + " strings");Expected output:
[000, 001, 010, 011, 100, 101, 110, 111]
8 stringsChallenge 2 – Fibonacci in 99 calls instead of 40 billion¶
The naive fib(50) makes about calls. Remember every computed value in
a HashMap<Integer, Long>: before computing fib(n), check whether it is already in the
map. Count the calls.
Solution
static Map<Integer, Long> memo = new HashMap<>();
static int calls = 0;
static long fib(int n) {
calls++;
if (n <= 1)
return n;
if (memo.containsKey(n))
return memo.get(n); // computed before
long r = fib(n - 1) + fib(n - 2);
memo.put(n, r);
return r;
}System.out.println("fib(50) = " + fib(50) + " with " + calls + " calls");Expected output:
fib(50) = 12586269025 with 99 callsChallenge 3 – All the permutations of a word¶
Write permutations(String done, String rest, Set<String> out): for each character of
rest, move it to the end of done and recurse. Put the results in a TreeSet, so that
they come out sorted and duplicates ("aab" has two as) are removed automatically.
Solution
static void permutations(String done, String rest, Set<String> out) {
if (rest.isEmpty()) {
out.add(done);
return;
}
for (int i = 0; i < rest.length(); i++) // choose the next character
permutations(done + rest.charAt(i),
rest.substring(0, i) + rest.substring(i + 1), out);
}Set<String> p = new TreeSet<>();
permutations("", "aab", p);
System.out.println(p);
p.clear();
permutations("", "abc", p);
System.out.println(p);Expected output:
[aab, aba, baa]
[abc, acb, bac, bca, cab, cba]