diff options
Diffstat (limited to '2023/src/day06.cpp')
| -rw-r--r-- | 2023/src/day06.cpp | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/2023/src/day06.cpp b/2023/src/day06.cpp new file mode 100644 index 0000000..9a429c5 --- /dev/null +++ b/2023/src/day06.cpp | |||
| @@ -0,0 +1,74 @@ | |||
| 1 | #include <cstdint> | ||
| 2 | #include <fstream> | ||
| 3 | #include <iostream> | ||
| 4 | #include <numeric> | ||
| 5 | #include <sstream> | ||
| 6 | #include <vector> | ||
| 7 | using namespace std; | ||
| 8 | |||
| 9 | template<typename T = long> | ||
| 10 | vector<T> | ||
| 11 | read_ints(const string& line) | ||
| 12 | { | ||
| 13 | stringstream iss{ line }; | ||
| 14 | return vector<T>{ istream_iterator<T>{ iss }, istream_iterator<T>{} }; | ||
| 15 | } | ||
| 16 | |||
| 17 | long | ||
| 18 | solve(long time, long winningDistance) | ||
| 19 | { | ||
| 20 | long counter = 0; | ||
| 21 | for ( long pushTime = 0; pushTime < time; ++pushTime ) { | ||
| 22 | auto distance = (time * pushTime - pushTime * pushTime); | ||
| 23 | counter += long(distance > winningDistance); | ||
| 24 | } | ||
| 25 | return counter; | ||
| 26 | } | ||
| 27 | |||
| 28 | void | ||
| 29 | part1() | ||
| 30 | { | ||
| 31 | fstream input{ "data/day06.txt" }; | ||
| 32 | string line; | ||
| 33 | |||
| 34 | getline(input, line); | ||
| 35 | auto times = read_ints(line.substr(line.find(':') + 1)); | ||
| 36 | |||
| 37 | getline(input, line); | ||
| 38 | auto distances = read_ints(line.substr(line.find(':') + 1)); | ||
| 39 | |||
| 40 | long result = 1; | ||
| 41 | for ( size_t idx = 0; idx != times.size(); ++idx ) { | ||
| 42 | result *= solve(times[idx], distances[idx]); | ||
| 43 | } | ||
| 44 | cout << result << endl; | ||
| 45 | } | ||
| 46 | |||
| 47 | string | ||
| 48 | join(const string& line) | ||
| 49 | { | ||
| 50 | stringstream iss{ line }; | ||
| 51 | return accumulate(istream_iterator<string>{ iss }, istream_iterator<string>{}, string{}); | ||
| 52 | } | ||
| 53 | |||
| 54 | void | ||
| 55 | part2() | ||
| 56 | { | ||
| 57 | fstream input{ "data/day06.txt" }; | ||
| 58 | string line; | ||
| 59 | |||
| 60 | getline(input, line); | ||
| 61 | auto time = stol(join(line.substr(line.find(':') + 1))); | ||
| 62 | |||
| 63 | getline(input, line); | ||
| 64 | auto distance = stol(join(line.substr(line.find(':') + 1))); | ||
| 65 | |||
| 66 | cout << solve(time, distance) << endl; | ||
| 67 | } | ||
| 68 | |||
| 69 | int | ||
| 70 | main() | ||
| 71 | { | ||
| 72 | part1(); | ||
| 73 | part2(); | ||
| 74 | } | ||
