miércoles, 18 abril 2007
Java recursive functions explained // Using recursion to sum an array of numbers
Java is a very powerful object oriented language. If you search for recursion in wikipedia you will find this definition "Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition." This means, that the function will call itself again and again until it gets the correct answer.
There are many pages where you can find great explanations to recursion theory. Most of them use the example of the Towers of Hanoi:
What I'm going to show you is an easy way to sum arrays of numbers. This example lets you see how easy can recursion be and how useful it is.
public class recursive { public recursive() { /** We create the array of numbers we want to sum It can be any subclass of java.lang.Number*/ Double[] test = {100d, 0.05d, 88d, 99d, 0.05d, 88d, 99d, 0.05d, 88d, 99d}; /* We call our function */ System.out.println(sum(test)); } /* This is the initial function, it calculates the starting fields and results *automatically*/ public Number sum(Number[] numbers){ return sum(numbers[numbers.length - 1], numbers, numbers.length - 2); } /* This is our RECURSIVE FUNCTION */ public Number sum(Number initialValue, Number[] numbers, int location){ /* If we've reached the end of the array we return the final RESULT */ if(location < 0){ return initialValue; } /* Or else we are recursive */ else{ /*First we cast the java.lang.Number to its subclass so we can do the *sum */ if(numbers instanceof BigInteger[]){ return sum( ((BigInteger)initialValue).add((BigInteger)numbers[location]), numbers, (location - 1) ); } else if(numbers instanceof BigDecimal[]){ return sum( ((BigDecimal)initialValue).add((BigDecimal)numbers[location]), numbers, (location - 1) ); } else if(numbers instanceof Byte[]){ return sum( ((Byte)initialValue) + (Byte)numbers[location], numbers, (location - 1) ); } else if(numbers instanceof Double[]){ return sum( ((Double)initialValue) + ((Double)numbers[location]), numbers, (location - 1) ); } else if(numbers instanceof Integer[]){ return sum( ((Integer)initialValue)+ ((Integer)numbers[location]), numbers, (location - 1) ); } else if(numbers instanceof Long[]){ return sum( ((Long)initialValue)+ ((Long)numbers[location]), numbers, (location - 1) ); } else if(numbers instanceof Short[]){ return sum( ((Short)initialValue)+ ((Short)numbers[location]), numbers, (location - 1) ); } else{ return sum( ((Float)initialValue)+ ((Float)numbers[location]), numbers, (location - 1) ); } } } /* THis is our main method */ public static void main(String[] args) { new recursive(); } }
Technorati Tags: recursion recursive functions cast java j2se class cast Number Integer Float BigDecimal Double
Posted by at 10:10 AM in Java
