Search code examples
javaloopsrandomdice

Roll 5 dice and see if 3 are the same


Full question: Simulates repeated trials to estimate the probability of rolling five dice and obtaining at least three numbers that are the same.

I know how to check for the probability using repeated trials and stuff. I just do not know how to see if three dice out of five will be the same. Important to note: we have not learned arrays yet in my class, so I cannot use that. We have learned objects, decisions, and are currently learning loops. Any help with how to check if three are the same would be appreciated. Here is what I have right now:

Random rand = new Random();

    final int TRIALS = 100_000;
    int same = 0;//check if they are the same??

    for(int i=0; i<TRIALS; i++){
        int a = rand.nextInt(6)+1;
        int b = rand.nextInt(6)+1;
        int c = rand.nextInt(6)+1;
        int d = rand.nextInt(6)+1;
        int e = rand.nextInt(6)+1;

    }

Solution

  • I guess this should work for you:

            Random rand = new Random();
    
        final int TRIALS = 100;
        int same = 0;//check if they are the same??
        int aux = 0;
        for(int i=0; i<TRIALS; i++){
            aux = 0;
            int a = rand.nextInt(6)+1;
            int b = rand.nextInt(6)+1;
            int c = rand.nextInt(6)+1;
            int d = rand.nextInt(6)+1;
            int e = rand.nextInt(6)+1;
            if(a == b || a == c || a == d || a == e)
                aux++;
            if(b == c || b == d || b == e)
                aux++;
            if(c == d || c == e)
                aux++;
            if(d == e)
                aux++;
            if(aux > 2)
                same++;
        }
        System.out.println("The posibilities are: " + same + "/" + TRIALS);
    }
    

    Trying not to use anything that is out of what you know right now.

    You can also try this, is the same but you'll have the exact prob:

        final int TRIALS = 100;
        int same = 0;//check if they are the same??
        int aux = 0;
        for(int i=0; i<TRIALS; i++){
            aux = 0;
            int a = rand.nextInt(6)+1;
            int b = rand.nextInt(6)+1;
            int c = rand.nextInt(6)+1;
            int d = rand.nextInt(6)+1;
            int e = rand.nextInt(6)+1;
            if(a == b || a == c || a == d || a == e)
                aux++;
            if(b == c || b == d || b == e)
                aux++;
            if(c == d || c == e)
                aux++;
            if(d == e)
                aux++;
            if(aux > 2)
                same++;
        }
        double prob = same/TRIALS;
        System.out.println("The posibilities are: " + prob);
    }