aboutsummaryrefslogtreecommitdiff
path: root/2018/src/day02.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2018/src/day02.cpp')
-rw-r--r--2018/src/day02.cpp87
1 files changed, 87 insertions, 0 deletions
diff --git a/2018/src/day02.cpp b/2018/src/day02.cpp
new file mode 100644
index 0000000..5dc6c7f
--- /dev/null
+++ b/2018/src/day02.cpp
@@ -0,0 +1,87 @@
1#include <filesystem>
2#include <fstream>
3#include <iostream>
4#include <map>
5#include <set>
6#include <string>
7#include <vector>
8
9using namespace std;
10
11namespace {
12
13vector<string>
14read_lines(const filesystem::path& filename)
15{
16 ifstream file{ filename };
17 vector<string> lines;
18
19 for ( string line; getline(file, line); ) {
20 lines.emplace_back(line);
21 }
22
23 return lines;
24}
25
26void
27part1(const vector<string>& lines)
28{
29 int twos = 0;
30 int threes = 0;
31 for ( const auto& line: lines ) {
32 map<char, int> foo;
33 for ( const auto chr: line ) {
34 foo[chr]++;
35 }
36
37 set<int> counts;
38 for ( const auto& [chr, count]: foo ) {
39 counts.insert(count);
40 }
41
42 if ( counts.contains(2) ) {
43 ++twos;
44 }
45 if ( counts.contains(3) ) {
46 ++threes;
47 }
48 }
49 cout << "Part 1: " << twos * threes << '\n';
50}
51
52void
53part2(const vector<string>& lines)
54{
55 for ( size_t i = 0; i != lines.size(); ++i ) {
56 for ( size_t j = i + 1; j != lines.size(); ++j ) {
57 const auto& lhs = lines.at(i);
58 const auto& rhs = lines.at(j);
59
60 if ( lhs.length() != rhs.length() ) {
61 throw runtime_error("invalid data");
62 }
63
64 string result;
65 for ( size_t k = 0; k != lhs.length(); ++k ) {
66 if ( lhs[k] == rhs[k] ) {
67 result += lhs[k];
68 }
69 }
70
71 if ( result.length() + 1 == lhs.length() ) {
72 cout << "Part 2: " << result << '\n';
73 return;
74 }
75 }
76 }
77}
78
79} // namespace
80
81int
82main()
83{
84 auto lines = read_lines("data/day02.txt");
85 part1(lines);
86 part2(lines);
87}