-7

This program is supposed to go through the number of 2 to 50 people and get the probability out of 100,000 trials whether 2 people will have the same birthday or not.

import java.util.Random;

public class birthday {
    public static void main(String[] args) {
        int N = 2;
        while (N != 51) {
            double probability = one_probability(N); 
            System.out.println(N + "  " + probability);
            N++;
        }
    }

    public static boolean one_group(int N) {
        int A[] = new int[N]; 
        Random random = new Random();
        boolean have_match = false; 
        for (int i = 0; i < N; i++) {  //assigns each person a birthday
            int k = random.nextInt(365);
            A[i] = k;
        }
        for (int i = 0; i < N; i++) {  //testing to see if birthdays match up
            for (int j = i+1; j < N; j++) {
                if (A[i] == A[j]) { have_match = true; break; }
            }
        }
        return have_match;
    }

    public static double one_probability(int N) { 
        int x = 0;
        for (int i = 0; i < 100000; i++) {  //repeating 100,000 times to get average probability
            boolean have_match = one_group(N);
            if (have_match == true) { x++; }
        }
        double probability = x / 100000;  //getting the average probability
        return probability;
    }
}

Here's the result (it goes from 2-50), it keeps giving me zeros so I know something is wrong. Please help :) Output

Michael A.
  • 11
  • 7

2 Answers2

0

Try with

int probability = x / 1000; // 1/100 of the value to get an probability in percent (integer)

or

float probably =  x / 100000F; //F for a `float` 
double probability = x / 100000.0; //a decimal without a F is a `double`

Without that, this can't work :

float probably = x / 100000;

First, the division of two integer will be stored in memory like an integer then store in a float/double. That storage truncate the value. This is the operator logic to return the biggest type in an operation so :

int * int -> int
int * float -> float
int * double -> double
short * short -> int //that's a trick, int is the minimal value an operation can return
AxelH
  • 13,322
  • 2
  • 21
  • 50
-1
int probability=x/100000; always return 0.

convert it to double probability=x/100000.0; the value of probability will always less than or equal one. because x will never be greater than 100000. And also change the return type of one_probability method to double.