recursive function code example

Example 1: bash vlookup function

# Example usage:
awk 'FNR==NR{a[$1]=$2; next}; {if($9 in a) {print $0, "\t"a[$9];} else {print $0, "\tNA"}}' input_file_1 input_file_2
# This command does a VLOOKUP-type operation between two files using
#	awk. With the numbers above, column 1 from input_file_1 is used 
#	an a key in an array with column 2 of input_file_1 as the match for 
#	the key. Column 9 of input_file_2 is then compared to the keys from
#	input_file_1 and any matches return the associated match from 
#	input_file_1 (here, column 2).

Example 2: recursive function javascript

function pow(x, n) {
  if (n == 1) {
    return x;
  } else {
    return x * pow(x, n - 1);
  }
}

alert( pow(3, 3) ); // 27

Example 3: recursion

# modified code tranclated to python from (Drab Duck)

def fact(num):
  if num <= 1:
      return 1
  else:
    return num*fact(num-1)

Example 4: recursive

private static long factorial(int n){  
	if (n == 1)
    	return 1;    
    else
		return n * factorial(n-1);
        }

Example 5: Recursion

/**
 * Return all subsequences of word (as defined above) separated by commas,
 * with partialSubsequence prepended to each one.
 */
private static String subsequencesAfter(String partialSubsequence, String word) {
    if (word.isEmpty()) {
        // base case
        return partialSubsequence;
    } else {
        // recursive step
        return subsequencesAfter(partialSubsequence, word.substring(1))
             + ","
             + subsequencesAfter(partialSubsequence + word.charAt(0), word.substring(1));
    }
}

Tags:

Java Example