forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBafflingBirthdays.java
More file actions
48 lines (44 loc) · 1.52 KB
/
Copy pathBafflingBirthdays.java
File metadata and controls
48 lines (44 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class BafflingBirthdays {
private static final int nonLeapYear = 2001;
private static final int daysInYear = 365;
boolean sharedBirthday(List<LocalDate> birthdates) {
Set<String> seen = new HashSet<>();
for (LocalDate birthdate : birthdates) {
if (!seen.add(birthdate.getMonth().toString() + birthdate.getDayOfMonth())) {
return true;
}
}
return false;
}
List<LocalDate> randomBirthdates(int groupSize) {
if (groupSize <= 0) {
return List.of();
}
List<LocalDate> birthdates = new ArrayList<>(groupSize);
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < groupSize; i++) {
int dayOfYear = random.nextInt(1, daysInYear + 1);
birthdates.add(LocalDate.ofYearDay(nonLeapYear, dayOfYear));
}
return birthdates;
}
double estimatedProbabilityOfSharedBirthday(int groupSize) {
if (groupSize <= 1) {
return 0.0;
}
if (groupSize > daysInYear) {
return 100.0;
}
double probabilityNoSharedBirthday = 1.0;
for (int k = 0; k < groupSize; k++) {
probabilityNoSharedBirthday *= (daysInYear - k) / (double) daysInYear;
}
return (1 - probabilityNoSharedBirthday) * 100.0;
}
}