** In Java with detailed comments ** ** In Java with detailed comments ** Assign
ID: 3707362 • Letter: #
Question
** In Java with detailed comments **
** In Java with detailed comments **
Assignment 11 Using a hash set to do a Monte Carlo analysis of the birthday paradox. The paradox states that the odds of 2 people in a group sharing a birthday is surprisingly high A Monte Carlo analysis is using random numbers to simulate actual probable outcomes Test your code for various numbers of people Here is pseudo code of the algorithm: Set number of collisions to zero Loop (10 to100 by 10) Loop Generate a birthday. (use 1-365) See if it is already in the set. If it is count as a collision and end the loop Add to the set. Print out the number of collisions as a probability P For example, if you ran 50 people and got 25 collisions P0.5 The probability of 100 is around 1.0. P can never exceed 1.0. If you exceed 1.0 you are counting collisions in a group more than once Example Output: Configuration:Explanation / Answer
Code
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class MonteCarloBirthday {
public static void main(String[] args) {
Random random = new Random();
int test_cases = 100000;
for (int people = 10; people < 100; people += 10) {
int collisionCount = 0; //collision counter
float prob = 0; //probability number
for (int eachCases = 0; eachCases < test_cases; eachCases++) {
Set<Integer> birthdaysSet = new HashSet<>(365);
birthdaysSet.add(random.nextInt(365) + 1);
for (int i = 0; i < people; i++) {
int randomBirthday = random.nextInt(365) + 1;
if (birthdaysSet.contains(randomBirthday)) {
collisionCount++;
break;
}
birthdaysSet.add(randomBirthday);
}
prob = (float) collisionCount / test_cases;
}
System.out.println("After " + test_cases + " tests there were "
+ collisionCount + " occurrences of shared "
+ " birthdays in a set of " + people + " people.");
System.out.println("Probability : " + prob);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.