lundi 27 juin 2016

How many base cases can we have for a recursive function?

I have rand2() method that returns 0 or 1 randomly.
I am trying to create a method rand3 which will use rand2() and return 0,1,2 with an equal probability.
I came up with a recursive solution that considers 4 combinations of 0,1.
All in all I wrote this function, with more than 1 base case, in a hope that it will work,
but it seems like recusive functions can't have more than one base case.
What am I missing?

public static int rand3(){
        String str = "";
        str+= rand2();
        str+= rand2();
        System.out.println(str);

        if(str=="00")
            return 0;
        else if(str=="11")
            return 1;
        else if( str=="01")
            return 2;          
        else
            return rand3();


    }




Aucun commentaire:

Enregistrer un commentaire