Search code examples
javarecursiondata-structurestail-recursion

Total possible outcomes for coin flip


For a given coin which is tossed 'n' times, find the 'count' of total possible combination of outcomes using recursion. I have successfully printed the outcomes using this code:

public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        int n=3;
        String answer="";
       
        toss(n,answer);
    }
    public static void toss(int n, String answer){
        
        if(n==0)
        {
            System.out.println(answer);
            return;
        }
        toss(n-1,answer+"H");
        toss(n-1,answer+"T");
        
        
    }
}

where n is the number of tosses and answer is the string kept to store the combination of outcomes

I HAVE TO FIND THE COUNT OF THE COMBINATIONS FOR WHICH I USED THIS CODE BUT DID NOT WORK:

static int toss(int n, String answer, int count){

                if(n==0)
                return count+1;

                toss(n-1,answer+"H",count+1);
                toss(n-1,answer+"T",count+1);
    }

*How to find the count of the total outcomes from the tosses?

For ex; for n =2 outcomes will be: "HH", "TT", "HT", "TH" count : 4 (How to find this? My code gives count as 0).*


Solution

  • The problem is that you don't return anything when n != 0. What you can do is just return 1 if n == 0 and return the sum of the two recursive calls else. This gives you:

    static int toss(int n, String answer){
                    if(n == 0) {
                            System.out.println(answer);
                            return 1;
                    }
                    return toss(n - 1, answer + "H") + toss(n - 1, answer + "T");
        }