aboutsummaryrefslogtreecommitdiff
path: root/2020/src/day02.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2020/src/day02.cpp')
-rw-r--r--2020/src/day02.cpp58
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>
7using namespace std;
8
9auto
10read_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
27void
28part1(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
40void
41part2(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
52int
53main()
54{
55 auto input = read_file("data/day02.txt");
56 part1(input);
57 part2(input);
58}