aboutsummaryrefslogtreecommitdiff
path: root/2017/src/day03.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2017/src/day03.cpp')
-rw-r--r--2017/src/day03.cpp94
1 files changed, 94 insertions, 0 deletions
diff --git a/2017/src/day03.cpp b/2017/src/day03.cpp
new file mode 100644
index 0000000..417cef3
--- /dev/null
+++ b/2017/src/day03.cpp
@@ -0,0 +1,94 @@
1#include <algorithm>
2#include <array>
3#include <cmath>
4#include <iostream>
5#include <map>
6
7using namespace std;
8
9namespace {
10
11void
12part1(int value)
13{
14 auto ring = static_cast<int>(ceil((sqrt(value) - 1) / 2));
15 auto side_len = (2 * ring) + 1;
16 auto max_value = side_len * side_len;
17
18 array<int, 4> centers = {
19 max_value - ring - (2 * ring * 0),
20 max_value - ring - (2 * ring * 1),
21 max_value - ring - (2 * ring * 2),
22 max_value - ring - (2 * ring * 3)
23 };
24
25 auto* itr = ranges::min_element(centers, {}, [value](int rhs) { return abs(value - rhs); });
26
27 auto dist_to_center = abs(value - *itr);
28
29 cout << "Part1: " << ring + dist_to_center << '\n';
30}
31
32void
33part2(int value)
34{
35 static const array<tuple<int, int>, 4> dirs{
36 make_tuple(1, 0), // right
37 make_tuple(0, -1), // up
38 make_tuple(-1, 0), // left
39 make_tuple(0, 1), // down
40 };
41
42 static const array<int, 3> offsets = { -1, 0, 1 };
43
44 map<tuple<int, int>, int> grid; // (x,y) => value
45
46 int x = 0;
47 int y = 0;
48 int steps = 1;
49
50 grid[{ x, y }] = 1;
51
52 while ( true ) {
53 for ( const auto [dx, dy]: dirs ) {
54 for ( int _ = 0; _ != steps; ++_ ) {
55 x += dx;
56 y += dy;
57
58 int sum = 0;
59 for ( const auto off_x: offsets ) {
60 for ( const auto off_y: offsets ) {
61 if ( off_x == 0 && off_y == 0 ) {
62 continue;
63 }
64
65 const auto pos = make_tuple(x + off_x, y + off_y);
66 if ( grid.contains(pos) ) {
67 sum += grid.at(pos);
68 }
69 }
70 }
71
72 if ( sum > value ) {
73 cout << "Part2: " << sum << '\n';
74 return;
75 }
76
77 grid[{ x, y }] = sum;
78 }
79 if ( dx == 0 ) {
80 ++steps;
81 }
82 }
83 }
84}
85
86} // namespace
87
88int
89main()
90{
91 static const auto puzzle = 265149;
92 part1(puzzle);
93 part2(puzzle);
94}