aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--2020/src/day01.cpp21
-rw-r--r--2020/src/day02.cpp58
2 files changed, 70 insertions, 9 deletions
diff --git a/2020/src/day01.cpp b/2020/src/day01.cpp
index d2d8629..67f88c4 100644
--- a/2020/src/day01.cpp
+++ b/2020/src/day01.cpp
@@ -32,24 +32,27 @@ process(const vector<long>& values)
32void 32void
33combination(const vector<long>& values, size_t r) 33combination(const vector<long>& values, size_t r)
34{ 34{
35 vector<bool> v(values.size()); 35 vector<bool> marker(values.size());
36 fill(v.end() - long(r), v.end(), true); 36
37 vector<long> set(r); 37 fill(marker.end() - long(r), marker.end(), true);
38
39 vector<long> subset(r);
40
38 do { 41 do {
39 set.clear(); 42 subset.clear();
40 for ( size_t i = 0; i != values.size(); ++i ) { 43 for ( size_t i = 0; i != values.size(); ++i ) {
41 if ( v[i] ) { 44 if ( marker[i] ) {
42 set.emplace_back(values[i]); 45 subset.emplace_back(values[i]);
43 } 46 }
44 } 47 }
45 process(set); 48 process(subset);
46 } while ( std::next_permutation(v.begin(), v.end()) ); 49 } while ( std::next_permutation(marker.begin(), marker.end()) );
47} 50}
48 51
49int 52int
50main() 53main()
51{ 54{
52 auto values = read_file("data/day01-sample1.txt"); 55 auto values = read_file("data/day01.txt");
53 combination(values, 2); 56 combination(values, 2);
54 combination(values, 3); 57 combination(values, 3);
55} 58}
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}