Skip to content

Commit 46a86a6

Browse files
committed
9
1 parent 30927cc commit 46a86a6

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

cpp/9.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include "common.h"
2+
3+
namespace {
4+
using Pos = std::complex<long>;
5+
6+
template <size_t N> long p1(const auto &input) {
7+
auto Hasher = [](const Pos &k) -> std::size_t {
8+
return std::hash<long>()(k.real()) ^ std::hash<long>()(k.imag());
9+
};
10+
auto offset = [](const Pos &p) {
11+
return Pos{(std::abs(p.real()) >= 2 ? p.real() / 2L : p.real()),
12+
(std::abs(p.imag()) >= 2 ? p.imag() / 2L : p.imag())};
13+
};
14+
std::unordered_set<Pos, decltype(Hasher)> v{Pos{0, 0}};
15+
std::array<Pos, N> rope{};
16+
std::unordered_map<char, Pos> dir{
17+
{'R', Pos{1, 0}}, {'L', Pos{-1, 0}}, {'U', Pos{0, 1}}, {'D', Pos{0, -1}}};
18+
for (auto [d, l, prev] = std::tuple{' ', 0L, Pos{0, 0}};
19+
const auto &s : input) {
20+
std::istringstream ss{s};
21+
ss >> d >> l;
22+
while (l--) {
23+
rope[0] += dir[d];
24+
for (const auto i : std::ranges::views::iota(1UL, N)) {
25+
const auto diff = rope[i - 1] - rope[i];
26+
if (std::abs(diff) >= 2)
27+
rope[i] += offset(diff);
28+
}
29+
v.emplace(rope[N - 1]);
30+
}
31+
}
32+
return v.size();
33+
}
34+
} // namespace
35+
36+
int main() {
37+
const auto &input = gb::advent2021::readIn();
38+
gb::advent2021::writeOut(std::to_string(p1<2>(input)));
39+
gb::advent2021::writeOut(std::to_string(p1<10>(input)));
40+
}

cpp/common.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <charconv>
55
#include <climits>
66
#include <cmath>
7+
#include <complex>
78
#include <cstdint>
89
#include <cstdio>
910
#include <cstring>

cpp/meson.build

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ executable('8',
3434
'8.cpp',
3535
dependencies: [])
3636

37-
# executable('9',
38-
# '9.cpp',
39-
# dependencies: [])
37+
executable('9',
38+
'9.cpp',
39+
dependencies: [])
4040

4141
# executable('10',
4242
# '10.cpp',

0 commit comments

Comments
 (0)