diff options
| author | Thomas Schmucker <ts@its1.de> | 2024-01-04 00:32:07 +0100 |
|---|---|---|
| committer | Thomas Schmucker <ts@its1.de> | 2024-01-04 00:32:07 +0100 |
| commit | 52ac586dcd7c78184d5884b0587f6b2c6fae98c4 (patch) | |
| tree | b3fcdeaf2e747d32acd49933257a2d641c322ea1 /2020/src/day02.cpp | |
| parent | 56e890cec0a28c0a485212ccebfaf774235a79a2 (diff) | |
| download | advent-of-code-52ac586dcd7c78184d5884b0587f6b2c6fae98c4.tar.gz advent-of-code-52ac586dcd7c78184d5884b0587f6b2c6fae98c4.tar.bz2 advent-of-code-52ac586dcd7c78184d5884b0587f6b2c6fae98c4.zip | |
solutions fpor day 1 & day 2, advent of code 2020
Diffstat (limited to '2020/src/day02.cpp')
| -rw-r--r-- | 2020/src/day02.cpp | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/2020/src/day02.cpp b/2020/src/day02.cpp new file mode 100644 index 0000000..d7e28f1 --- /dev/null +++ b/2020/src/day02.cpp | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | #include <fstream> | ||
| 2 | #include <functional> | ||
| 3 | #include <iostream> | ||
| 4 | #include <numeric> | ||
| 5 | #include <string> | ||
| 6 | #include <vector> | ||
| 7 | using namespace std; | ||
| 8 | |||
| 9 | auto | ||
| 10 | read_file(string_view filename) | ||
| 11 | { | ||
| 12 | fstream input{ filename }; | ||
| 13 | vector<tuple<long, long, char, string>> data; | ||
| 14 | |||
| 15 | for ( string line; getline(input, line); ) { | ||
| 16 | long min = 0; | ||
| 17 | long max = 0; | ||
| 18 | char chr = 0; | ||
| 19 | char password[100]; | ||
| 20 | sscanf(line.data(), "%ld-%ld %c: %99s", &min, &max, &chr, password); // NOLINT | ||
| 21 | data.emplace_back(min, max, chr, password); | ||
| 22 | } | ||
| 23 | |||
| 24 | return data; | ||
| 25 | } | ||
| 26 | |||
| 27 | void | ||
| 28 | part1(vector<tuple<long, long, char, string>>& data) | ||
| 29 | { | ||
| 30 | long sum = 0; | ||
| 31 | for ( const auto& [min, max, chr, password]: data ) { | ||
| 32 | const auto amount = count(password.begin(), password.end(), chr); | ||
| 33 | if ( min <= amount && amount <= max ) { | ||
| 34 | ++sum; | ||
| 35 | } | ||
| 36 | } | ||
| 37 | cout << sum << endl; | ||
| 38 | } | ||
| 39 | |||
| 40 | void | ||
| 41 | part2(vector<tuple<long, long, char, string>>& data) | ||
| 42 | { | ||
| 43 | long sum = 0; | ||
| 44 | for ( const auto& [min, max, chr, password]: data ) { | ||
| 45 | if ( (password[size_t(min - 1)] == chr) ^ (password[size_t(max - 1)] == chr) ) { | ||
| 46 | ++sum; | ||
| 47 | } | ||
| 48 | } | ||
| 49 | cout << sum << endl; | ||
| 50 | } | ||
| 51 | |||
| 52 | int | ||
| 53 | main() | ||
| 54 | { | ||
| 55 | auto input = read_file("data/day02.txt"); | ||
| 56 | part1(input); | ||
| 57 | part2(input); | ||
| 58 | } | ||
