Showing posts with label Recursion. Show all posts
Showing posts with label Recursion. Show all posts

Tuesday, September 22, 2009

Tokenizing String Recursively

This is an update to the blog entry "String tokenizer by hand". In this article, I am demonstrating an example of tokenizing a given string in a recursive manner. The code is as below:

import java.util.ArrayList;

public class StringTokenizer {

private static ArrayList tokenizedStr = new ArrayList();
private static StringBuffer str = new StringBuffer();

public static ArrayList tokenizer(String input){
int strLength = input.length();
return tokenizer(input, 0, strLength);
}

public static ArrayList tokenizer(String input, int currentIndex, int strLength){
if (currentIndex < strLength) {
char curr = input.charAt(currentIndex);
if (curr != ' ') {
str.append(curr);
} else {
if (str.length() != 0) {
tokenizedStr.add(str);
}
str = new StringBuffer();
}
if ((currentIndex == strLength-1 ) && (curr != ' ')) {
tokenizedStr.add(str);
}
currentIndex++;
tokenizer(input, currentIndex, strLength);
}
return tokenizedStr;
}

public static void main(String[] args) {
System.out.println(tokenizer(" Hello World This is Nicholas Key. How are you? "));
}

}

Tuesday, September 1, 2009

Fibonacci Sequence

Here's an interesting usage of "memoization". According to Wikipedia, "In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.".

There is actually a drawback if we are using plain and simple recursion to compute the Fibonacci sequence using long datatype (because we are only limited to hold the first 48 Fibonacci numbers). Memoization helps to speed up the computation time by saving already computed values into memory (and we can use BigInteger datatype). An example implementation is as below:

import java.math.BigInteger;
import java.util.ArrayList;

public class Fibonacci {

/** Variables for memoization **/
private static ArrayList fibMemoized = new ArrayList();
static {
fibMemoized.add(BigInteger.ZERO);
fibMemoized.add(BigInteger.ONE);
}

/** Memoized method to retrieve stored computed values **/
public static BigInteger fibonacci(int n) {
if (n >= fibMemoized.size()) {
fibMemoized.add(n, fibonacci(n-1).add(fibonacci(n-2)));
}
return fibMemoized.get(n);
}

/** Old school recursion **/
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}

/** Driver **/
public static void main(String[] args) {
int N = 45;
System.out.println(fibonacci(N));
System.out.println(fib(N));
}

}
You may try copying the codes and run it locally to observe the difference in performance. The typical recursive method runs slower because it computes the Fibonnaci numbers from scratch many times. Unlike the memoized method, the ArrayList is used to store the previously computed values. While memoized method is more superior in terms of speed, we are actually sacrificing space in order to achieve greater speed.

Friday, July 3, 2009

Greatest Common Divisor (Recursion)

Here's a sample solution to solve the GCD recursively.

public long GCD(long numberA, long numberB) {
if (numberB==0)
return numberA;
else
return GCD(numberB, numberA % numberB);
}
Update: The code is also available in Python in this entry

Friday, June 5, 2009

Solving Palindrome Using Recursion

This is a follow-up article about solving palindrome using recursion. While we solved this problem previously using iteration (link to previous article), I am demonstrating the way of solving it in a recursive manner.

public static void isPalindromeRecursive(String text){
text = text.toLowerCase().replaceAll("[\\W\\_*]", "");
if (helperFunction(text, 0, text.length()-1)) {
System.out.println("Is a Palindrome");
} else {
System.out.println("Is not a Palindrome");
}
}

private static boolean helperFunction(String input, int leftIndex, int rightIndex){
if (leftIndex < rightIndex) {
if (!(input.charAt(leftIndex) == input.charAt(rightIndex))) {
return false;
}
leftIndex++;
rightIndex--;
helperFunction(input, leftIndex, rightIndex);
}
return true;
}