java: Birthday probability program - java

I'm trying to create a program that finds the probability of two random students in a room to have the same birthday. Number of students and number of simulations is inputted. Whenever I run it though, with 23 students, I consistently get 0.69, which is inconsistent with the actual answer of about 0.50. I think it probbaly has something to do with the fact that, if there are 3 students with the same birthday, it will count it as 3 matches. But I'm not sure how to fix this problem and I've already tried multiple times. Can I get some help?
import java.util.Scanner;
public class bday{
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
System.out.println("How many students?");
int num = inp.nextInt();
System.out.println("How many times?");
int times = inp.nextInt();
double x[] = new double[num];
int match = 0;
for(int i=0;i<times;i++){
for(int j=0;j<num;j++){
x[j] = (int)(Math.random()*365)+1;
}
for(int j=0;j<num;j++){
for(int k=j+1;k<num;k++){
if(x[j]==x[k]){
match++;
}
}
}
}
double prob = (double)match/times;
System.out.println("The probability for two students to share a birthday is "+prob+".");
}}

You messed up the logic. The logic should be like this:
whenever there is a occurrence of same birthday, you add one to the total matches and then break then start another time. After you finished all the times, divide the total matches by how many times.
here is the code:
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner inp = new Scanner(System. in );
System.out.println("How many students?");
int num = inp.nextInt();
System.out.println("How many times?");
int times = inp.nextInt();
int x[] = new int[num];
int matches = 0;
boolean out = false;
for (int i = 0; i < times; i++) {
for (int j = 0; j < num; j++) {
x[j] = (int)(Math.random() * 365) + 1;
}
for (int j = 0; j < num; j++) {
for (int k = j + 1; k < num; k++) {
if (x[j] == x[k]) {
matches++;
out = true;
break;
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / times;
System.out.println("The probability for two students to share a birthday is " + prob + ".");
}
}
The test result: 0.50557 for 100000, 0.507591 for 1000000. Should be close to your answer.

Related

find probability of n people in a class of x share the same birthday using monte carlo simulation in java

As the problem states, i must use monte carlo(randomness) to solve the question given. I am running the simulation 1,000,000 times.
import java.util.*;
public class MonteCarlo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter size of the class: ");
int classSize = sc.nextInt();
System.out.println("Please enter the amount of people who share the same birthday: ");
int birthPpl = sc.nextInt();
System.out.println("calculate the probability that "+birthPpl+" people share the same Birthday in a class size of "+classSize);
sc.close();
int birthdays [] = new int[classSize];
int simulations = 0;
int success=0;
for(int i=0; i<1000000; i++){
simulations++;
if(Collision(birthdays)>=birthPpl){
success++;
}
}
System.out.println(success+" "+simulations);
System.out.println("Answer: "+ (success*100)/simulations + "%");
}
public static int Collision(int birthday[]){
Random rand = new Random();
for(int i=1; i<birthday.length; i++){
birthday[i]= rand.nextInt(365);
}
int count = 0;
for(int i=0; i<birthday.length; i++){
for(int j= i+1; j<birthday.length; j++){
if(birthday[i]==birthday[j]){
count++;
}
}
}
return count;
}
}
As per a couple of psuedo code solutions i have seen online i have tried looping through the size of the class x and inserting in a random birthday. then comparing birthdays , reducing the birthdays i look through by 1 each time. I then check the number of collisions against the amount sof ppl who should a birthday , if it is greater or equal to it than i increase the count. i have been given sample imput 20 and 2 which should give 41 % but my program gives eithe 7 or 8 %
What's the problem, and how can it be fixed?
You could also make use the Random and HashMap classes. Map.merge will take the key, a birthday in this case, then a default value of 1, and continues to add 1 to the existing value which is returned and compared to x. Then success is appropriately updated. The Random class provides a variety of methods to return random numbers and is usually preferred over Math.random.
double success = 0;
int tests = 1_000_000;
// instantiate a Random class for selecting the next birthday
Random r = new Random();
// a map to hold the frequency count of same birthdays
Map<Integer,Integer> birthdays = new HashMap<>();
int n = 23;
int x = 2;
for(int i=0; i< tests; i++) {
for (int j = 0; j < n; j++) {
if (birthdays.merge(r.nextInt(365), 1, Integer::sum) >= x) {
success++;
break;
}
}
// clear the map for the next run
birthdays.clear();
}
Using System.out.printf facilitates formatting the output.
System.out.printf("probability = %4.1f%%%n", (success/tests) * 100);
prints something like the following:
probability = 50.7%
import java.util.Scanner;
public class Birthday {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // class size
int x = sc.nextInt(); // people who share the same birthday
double tests = 1_000_000;
double success = 0;
// fills array of birthdays and breaks out when x amount of people share
// a birthday. then we find the % of successes.
for (int i = 0; i < tests; i++) {
int[] year = new int[365];
for (int j = 0; j < n; j++) {
int birthday = (int) (Math.random() * 365);
year[birthday]++;
if (year[birthday] >= x) {
success++;
break;
}
}
}
System.out.println(Math.round(success * 100 / tests));
}
}

create a program that prompts the user to enter a number between 1 and 15 and print the sum as shown: 1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10

I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}

How To Add Indices Together Within An Array?

I am working on an assignment and I'm not sure how to add the indices together to get a sum that can be displayed. Mind you I'm only a high school student so my code is sloppier and less efficient than what any of you would likely create, but any help is appreciated. Here's what I have right now that's producing an index out of bounds exception:
System.out.println("Please enter the amount of workers you have");
Scanner userInput = new Scanner (System.in);
int workerAmount = userInput.nextInt();
int payroll[][]= new int [workerAmount][6];
for(int a = 0; a < payroll.length; a++){
for(int b = 0; b < payroll[a].length; b++)
{
System.out.println("How many hours did this worker work?");
Scanner use = new Scanner (System.in);
int user = use.nextInt();
payroll[a][b] = user;
}
}
for(int i = 0; i < payroll.length; i++){
for(int a = 0; a < payroll[i].length; a++){
System.out.println(payroll[i][a]);
int sum = (payroll[i + a][a]);
}
}
to sum all the values, try this:
int sum = 0;
for(int i = 0; i < payroll.length; i++){
for(int a = 0; a < payroll[i].length; a++){
sum += payroll[i][a];
}
}
System.out.println("the sum is: " + sum);
The code above simply iterates through all the arrays of arrays and adds the value of each element onto the sum variable which then gets printed to the console.

Nested for loop sum of integers

public class NestedCountLoop
{
public static void main(String[] args)
{
int sum = 0;
for (int i = 1; sum < 5050; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
So I have a little homework assignment for my intro programming class to use a nested loop to accept positive integer input and add all of the integers within the interval from 1 to that input. My mind is playing games with me and I'm having trouble getting going. I know I need a scanner and whatnot, and it has to print every result from 1 to n such as "The sum of 1 to 100 is 5050." Any advice is helpful
Information on scanner at from http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner sc = new Scanner(System.in);
for (int i = o; i < 100; i++){
int upperLimit = sc.nextInt();
for (int w = 0; w < upperLimit; w++){
sum = sum + i;
}
System.out.println("Sum is " + sum);
}
public class NestedCountLoop
{
public static void main(String[] args)
{
int to = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 1; sum < to; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
How about this one? It takes an input from the command line (arg0), and adds every number to your number (not inclusive).
So you have to compile your java file with javac, then you can run:
javac NestedCountLoop.java
java NestedCountLoop.class 100
On the other hand, the a previous solution mentioned the javadoc for your scanner, if you really need to use it. :)
System.out.println("Enter your maximum number: ");
// get the input
Scanner input = new Scanner(System.in);
int max = input.nextInt();
int sum = 0;
// iterate through an array to sum up the numbers
for (int i = 1; i < max; i++) {
sum = sum + i; // sum += i;
}
// print out the sum after you counted everything
System.out.println(sum);
import java.util.Scanner;
public class sumoftenIntegerInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
for(int i=1; i<=10; i++){
System.out.println("Enter integer input " + i + ":");
int a = input.nextInt();
sum = sum + a ;
}
System.out.println("Total is:" + sum );
}
}

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories