miércoles, 18 abril 2007

Java recursive functions explained // Using recursion to sum an array of numbers

« Displaying a jTable inside another jTable // JTable cellRenderer | Main | Numbers to Strings with custom symbols // DecimalFormat - DecimalFormatSymbols »

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:

Posted by admin at 10:10 AM in Java

 

[Trackback URL for this entry]

Comment: Peter Veentjer at jue, 19 abr 7:45 AM

The problem with recursive calls in Java is that Java doesn't do much 'tail call optimization'. The consequence is that for each call you need another stackframe, and this will lead to problems (stack overflow and performance).

Functional programming languages like Haskell or Erlang do provide tail call optimization and in these languages a recursive call is just as expensive as an iteration.

Comment: Marc Nuri at jue, 19 abr 8:13 AM

What you say is completely true. Although recursion is an elegant method for iteration, it can lead to stack overflow in many ocasions.
You can read more about this issue at IBM: Diagnosing java code...

Comment: Power Kites at mar, 19 jul 1:13 PM

Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration.

Comment: Flags Banners at vie, 22 jul 8:26 AM

Thanks for that information. I am glad that you shared this helpful info with us. Thank you for bringing more information to this topic for me.

Comment: Austin Luxury Homes at mar, 26 jul 6:20 PM

I think this page is very nice to read. I like the discussion about saying his/her own opinion.

Comment: bull outdoor kitchen at dom, 31 jul 9:26 AM

I have found your site through Yahoo. I am glad that you shared this helpful info with us. Good to see this page. Thanks for sharing.

Comment: stickers islam at dom, 4 sep 11:03 AM

Good site that can be referred by all and also to all that helps in various ways. Nice site that helps gather the knowledge.

Comment: garageporte priser at mar, 13 sep 8:33 AM

This is a good article with lots of useful information. I like all your post.

Comment: Work Life coaching at vie, 30 sep 12:20 PM

it was nice to find a website that becomes a container and also the gathering place of people who have similar interests.

Comment: pc repairs Birmingham at sáb, 8 oct 10:07 AM

This is truly amazing. I would like to see some more updates on this issue here. I appreciate this effort.

Comment: tiles floor cleaning at dom, 9 oct 8:48 AM

I could tell how great you are in your field of interest. You could relate in each detail very well.

Comment: Water Damage at mar, 11 oct 10:03 AM

I recently found many useful information in your website especially this blog page. Thanks for sharing

Your comment:

(not displayed)
 

SCode

Please enter the code as seen in the image above to post your comment.

 
 

Live Comment Preview:

 
Google
 
« April »
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
2930