Skip to content

Added "baffling-birthdays" exercise #977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ jobs:
shell: powershell
# Delete the exercises that require Boost to avoid issues with Windows setup.
run: |
rm exercises/practice/baffling-birthdays -r
rm exercises/practice/gigasecond -r
rm exercises/practice/meetup -r
cmake .
Expand Down
15 changes: 15 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1278,6 +1278,21 @@
"comparisons"
],
"difficulty": 6
},
{
"slug": "baffling-birthdays",
"name": "Baffling Birthdays",
"uuid": "1886bed2-3985-4323-a689-22b1a5c75e38",
"practices": [
"randomness",
"datetimes"
],
"prerequisites": [
"datetimes",
"randomness",
"numbers"
],
"difficulty": 6
}
],
"foregone": [
Expand Down
23 changes: 23 additions & 0 deletions exercises/practice/baffling-birthdays/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Instructions

Your task is to estimate the birthday paradox's probabilities.

To do this, you need to:

- Generate random birthdates.
- Check if a collection of randomly generated birthdates contains at least two with the same birthday.
- Estimate the probability that at least two people in a group share the same birthday for different group sizes.

~~~~exercism/note
A birthdate includes the full date of birth (year, month, and day), whereas a birthday refers only to the month and day, which repeat each year.
Two birthdates with the same month and day correspond to the same birthday.
~~~~

~~~~exercism/caution
The birthday paradox assumes that:

- There are 365 possible birthdays (no leap years).
- Each birthday is equally likely (uniform distribution).

Your implementation must follow these assumptions.
~~~~
25 changes: 25 additions & 0 deletions exercises/practice/baffling-birthdays/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Introduction

Fresh out of college, you're throwing a huge party to celebrate with friends and family.
Over 70 people have shown up, including your mildly eccentric Uncle Ted.

In one of his usual antics, he bets you £100 that at least two people in the room share the same birthday.
That sounds ridiculous — there are many more possible birthdays than there are guests, so you confidently accept.

To your astonishment, after collecting the birthdays of just 32 guests, you've already found two guests that share the same birthday.
Accepting your loss, you hand Uncle Ted his £100, but something feels off.

The next day, curiosity gets the better of you.
A quick web search leads you to the [birthday paradox][birthday-problem], which reveals that with just 23 people, the probability of a shared birthday exceeds 50%.

Ah. So _that's_ why Uncle Ted was so confident.

Determined to turn the tables, you start looking up other paradoxes; next time, _you'll_ be the one making the bets.

~~~~exercism/note
The birthday paradox is a [veridical paradox][veridical-paradox]: even though it feels wrong, it is actually true.

[veridical-paradox]: https://en.wikipedia.org/wiki/Paradox#Quine's_classification
~~~~

[birthday-problem]: https://en.wikipedia.org/wiki/Birthday_problem
21 changes: 21 additions & 0 deletions exercises/practice/baffling-birthdays/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"authors": [
"marcelweikum"
],
"files": {
"solution": [
"baffling_birthdays.cpp",
"baffling_birthdays.h"
],
"test": [
"baffling_birthdays_test.cpp"
],
"example": [
".meta/example.cpp",
".meta/example.h"
]
},
"blurb": "Estimate the birthday paradox's probabilities.",
"source": "Erik Schierboom",
"source_url": "https://github.com/exercism/problem-specifications/pull/2539"
}
55 changes: 55 additions & 0 deletions exercises/practice/baffling-birthdays/.meta/example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <random>
#include <unordered_set>

#include "baffling_birthdays.h"

namespace baffling_birthdays {

Date parse_date(const std::string& iso) {
try {
return boost::gregorian::from_simple_string(iso);
} catch (...) {
return Date(boost::gregorian::not_a_date_time);
}
}

bool shared_birthday(const std::vector<Date>& dates) {
std::unordered_set<unsigned> seen_md;
seen_md.reserve(dates.size());
for (auto const& d : dates) {
if (d.is_not_a_date()) continue;
unsigned key = d.month().as_number() * 100 + d.day();
if (seen_md.count(key)) return true;
seen_md.insert(key);
}
return false;
}

std::vector<Date> random_birthdates(std::size_t group_size) {
static std::mt19937_64 gen(
static_cast<unsigned long>(std::random_device{}()));
std::uniform_int_distribution<int> month_dist(1, 12);
const int days_in_month[12] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
std::vector<Date> dates;
dates.reserve(group_size);
for (std::size_t i = 0; i < group_size; ++i) {
int m = month_dist(gen);
std::uniform_int_distribution<int> day_dist(1, days_in_month[m - 1]);
int d = day_dist(gen);
dates.push_back(Date(2001, m, d));
}
return dates;
}

double estimated_probability_of_shared_birthday(std::size_t group_size) {
if (group_size <= 1) return 0.0;
if (group_size > 365) return 100.0;
double unique_prob = 1.0;
for (std::size_t i = 0; i < group_size; ++i) {
unique_prob *= (365.0 - static_cast<double>(i)) / 365.0;
}
return (1.0 - unique_prob) * 100.0;
}

} // namespace baffling_birthdays
36 changes: 36 additions & 0 deletions exercises/practice/baffling-birthdays/.meta/example.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#pragma once

#include <boost/date_time/gregorian/gregorian.hpp>
#include <string>
#include <vector>

namespace baffling_birthdays {

using Date = boost::gregorian::date;

Date parse_date(const std::string& iso);

bool shared_birthday(const std::vector<Date>& dates);
std::vector<Date> random_birthdates(std::size_t group_size);

double estimated_probability_of_shared_birthday(std::size_t group_size);

inline bool shared_birthday(const std::vector<std::string>& birthdates) {
std::vector<Date> dates;
dates.reserve(birthdates.size());
for (auto const& s : birthdates) {
dates.push_back(parse_date(s));
}
return shared_birthday(dates);
}

inline std::vector<std::string> random_birthdates_str(std::size_t group_size) {
auto dates = random_birthdates(group_size);
std::vector<std::string> out;
out.reserve(group_size);
for (auto const& d : dates)
out.push_back(boost::gregorian::to_iso_extended_string(d));
return out;
}

} // namespace baffling_birthdays
61 changes: 61 additions & 0 deletions exercises/practice/baffling-birthdays/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[716dcc2b-8fe4-4fc9-8c48-cbe70d8e6b67]
description = "shared birthday -> one birthdate"

[f7b3eb26-bcfc-4c1e-a2de-af07afc33f45]
description = "shared birthday -> two birthdates with same year, month, and day"

[7193409a-6e16-4bcb-b4cc-9ffe55f79b25]
description = "shared birthday -> two birthdates with same year and month, but different day"

[d04db648-121b-4b72-93e8-d7d2dced4495]
description = "shared birthday -> two birthdates with same month and day, but different year"

[3c8bd0f0-14c6-4d4c-975a-4c636bfdc233]
description = "shared birthday -> two birthdates with same year, but different month and day"

[df5daba6-0879-4480-883c-e855c99cdaa3]
description = "shared birthday -> two birthdates with different year, month, and day"

[0c17b220-cbb9-4bd7-872f-373044c7b406]
description = "shared birthday -> multiple birthdates without shared birthday"

[966d6b0b-5c0a-4b8c-bc2d-64939ada49f8]
description = "shared birthday -> multiple birthdates with one shared birthday"

[b7937d28-403b-4500-acce-4d9fe3a9620d]
description = "shared birthday -> multiple birthdates with more than one shared birthday"

[70b38cea-d234-4697-b146-7d130cd4ee12]
description = "random birthdates -> generate requested number of birthdates"

[d9d5b7d3-5fea-4752-b9c1-3fcd176d1b03]
description = "random birthdates -> years are not leap years"

[d1074327-f68c-4c8a-b0ff-e3730d0f0521]
description = "random birthdates -> months are random"

[7df706b3-c3f5-471d-9563-23a4d0577940]
description = "random birthdates -> days are random"

[89a462a4-4265-4912-9506-fb027913f221]
description = "estimated probability of at least one shared birthday -> for one person"

[ec31c787-0ebb-4548-970c-5dcb4eadfb5f]
description = "estimated probability of at least one shared birthday -> among ten people"

[b548afac-a451-46a3-9bb0-cb1f60c48e2f]
description = "estimated probability of at least one shared birthday -> among twenty-three people"

[e43e6b9d-d77b-4f6c-a960-0fc0129a0bc5]
description = "estimated probability of at least one shared birthday -> among seventy people"
78 changes: 78 additions & 0 deletions exercises/practice/baffling-birthdays/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Get the exercise name from the current directory
get_filename_component(exercise ${CMAKE_CURRENT_SOURCE_DIR} NAME)

# Basic CMake project
cmake_minimum_required(VERSION 3.5.1)

# Name the project after the exercise
project(${exercise} CXX)

# Locate Boost date_time library
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.58 REQUIRED COMPONENTS date_time)

# Get a source filename from the exercise name by replacing -'s with _'s
string(REPLACE "-" "_" file ${exercise})

# Implementation could be only a header
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}.cpp)
set(exercise_cpp ${file}.cpp)
else()
set(exercise_cpp "")
endif()

# Use the common Catch library?
if(EXERCISM_COMMON_CATCH)
# For Exercism track development only
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h $<TARGET_OBJECTS:catchlib>)
elseif(EXERCISM_TEST_SUITE)
# The Exercism test suite is being run, the Docker image already
# includes a pre-built version of Catch.
find_package(Catch2 REQUIRED)
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h)
target_link_libraries(${exercise} PRIVATE Catch2::Catch2WithMain)
# When Catch is installed system wide we need to include a different
# header, we need this define to use the correct one.
target_compile_definitions(${exercise} PRIVATE EXERCISM_TEST_SUITE)
else()
# Build executable from sources and headers
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h test/tests-main.cpp)
endif()

set_target_properties(${exercise} PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED OFF
CXX_EXTENSIONS OFF
)

set(CMAKE_BUILD_TYPE Debug)

if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(GNU|Clang)")
set_target_properties(${exercise} PROPERTIES
COMPILE_FLAGS "-Wall -Wextra -Wpedantic -Werror"
)
endif()

# We need boost libraries
target_link_libraries(${exercise}
PRIVATE
Boost::date_time
)

# Configure to run all the tests?
if(${EXERCISM_RUN_ALL_TESTS})
target_compile_definitions(${exercise} PRIVATE EXERCISM_RUN_ALL_TESTS)
endif()

# Tell MSVC not to warn us about unchecked iterators in debug builds
# Treat warnings as errors
# Treat type conversion warnings C4244 and C4267 as level 4 warnings, i.e. ignore them in level 3
if(${MSVC})
set_target_properties(${exercise} PROPERTIES
COMPILE_DEFINITIONS_DEBUG _SCL_SECURE_NO_WARNINGS
COMPILE_FLAGS "/WX /w44244 /w44267")
endif()

# Run the tests on every build
add_custom_target(test_${exercise} ALL DEPENDS ${exercise} COMMAND ${exercise})
7 changes: 7 additions & 0 deletions exercises/practice/baffling-birthdays/baffling_birthdays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include "baffling_birthdays.h"

namespace baffling_birthdays {

// TODO: add your solution here

} // namespace baffling_birthdays
7 changes: 7 additions & 0 deletions exercises/practice/baffling-birthdays/baffling_birthdays.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#pragma once

namespace baffling_birthdays {

// TODO: add your solution here

} // namespace baffling_birthdays
Loading