aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/day15.cpp48
1 files changed, 46 insertions, 2 deletions
diff --git a/src/day15.cpp b/src/day15.cpp
index 905110f..607f5f2 100644
--- a/src/day15.cpp
+++ b/src/day15.cpp
@@ -1,5 +1,7 @@
1#include <algorithm>
1#include <fstream> 2#include <fstream>
2#include <iostream> 3#include <iostream>
4#include <list>
3#include <sstream> 5#include <sstream>
4#include <string> 6#include <string>
5#include <vector> 7#include <vector>
@@ -46,8 +48,8 @@ calculate_hash(string_view str)
46void 48void
47part1() 49part1()
48{ 50{
49 const auto line = read_file("data/day15.txt"); 51 const auto line = read_file("data/day15.txt");
50 const auto parts = split(line, ','); 52 const auto parts = split(line, ',');
51 unsigned long value = 0; 53 unsigned long value = 0;
52 for ( const auto& part: parts ) { 54 for ( const auto& part: parts ) {
53 value += calculate_hash(part); 55 value += calculate_hash(part);
@@ -55,8 +57,50 @@ part1()
55 cout << value << endl; 57 cout << value << endl;
56} 58}
57 59
60void
61part2()
62{
63 vector<list<tuple<string, long>>> boxes(256);
64
65 const auto line = read_file("data/day15.txt");
66 const auto parts = split(line, ',');
67 for ( const auto& part: parts ) {
68 const auto pos = part.find_first_of("=-");
69 const auto lens = part.substr(0, pos);
70 auto& box = boxes[calculate_hash(lens)];
71
72 if ( part[pos] == '=' ) {
73 const auto value = stol(part.substr(pos + 1));
74
75 auto iter = find_if(box.begin(), box.end(), [&lens](const auto& element) { return get<0>(element) == lens; });
76 if ( iter == box.end() ) {
77 box.emplace_back(lens, value);
78 }
79 else {
80 *iter = { lens, value };
81 }
82 }
83 else {
84 box.remove_if([&lens](const auto& element) { return get<0>(element) == lens; });
85 }
86 }
87
88 long value = 0;
89 for ( size_t idx = 0; idx != boxes.size(); ++idx ) {
90 const auto& box = boxes[idx];
91
92 long lens_number = 1;
93 for ( const auto& lens: box ) {
94 value += static_cast<long>(idx + 1) * lens_number * get<1>(lens);
95 ++lens_number;
96 }
97 }
98 cout << value << endl;
99}
100
58int 101int
59main() 102main()
60{ 103{
61 part1(); 104 part1();
105 part2();
62} 106}