From 5f92ea475dadc173b2172834227f9392fd7d5a7c Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Fri, 10 Jan 2025 19:34:39 +0100 Subject: aoc 2016, day 1 --- 2016/src/day01.cpp | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 2016/src/day01.cpp (limited to '2016/src') diff --git a/2016/src/day01.cpp b/2016/src/day01.cpp new file mode 100644 index 0000000..f5d74a5 --- /dev/null +++ b/2016/src/day01.cpp @@ -0,0 +1,122 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +vector +split(string_view line, string_view delimiter) +{ + size_t pos_start = 0; + size_t pos_end = 0; + + vector res; + + while ( (pos_end = line.find(delimiter, pos_start)) != string::npos ) { + auto token = line.substr(pos_start, pos_end - pos_start); + pos_start = pos_end + delimiter.length(); + + res.emplace_back(token); + } + + if ( pos_start != line.size() ) { + res.emplace_back(line.substr(pos_start)); + } + return res; +} + +vector> +read_file(string_view filename) +{ + fstream input{ filename }; + string content{ istreambuf_iterator{ input }, istreambuf_iterator{} }; + + vector> result; + for ( const auto& part: split(content, ", ") ) { + result.emplace_back(part[0], stol(part.substr(1))); + } + return result; +} + +void +part1(const vector>& input) +{ + array, 4> dirs = { + make_tuple(1L, 0L), + make_tuple(0L, 1L), + make_tuple(-1L, 0L), + make_tuple(0L, -1L) + }; + + size_t dir = 0; + long pos_x = 0; + long pos_y = 0; + + for ( const auto& [change, length]: input ) { + if ( change == 'L' ) { + dir = (dir + 1) % 4; + } + else { + dir = (dir + 3) % 4; + } + + auto [delta_x, delta_y] = dirs.at(dir); + + pos_x += length * delta_x; + pos_y += length * delta_y; + } + + cout << abs(pos_x) + abs(pos_y) << endl; +} + +void +part2(const vector>& input) +{ + array, 4> dirs = { + make_tuple(1L, 0L), + make_tuple(0L, 1L), + make_tuple(-1L, 0L), + make_tuple(0L, -1L) + }; + + size_t dir = 0; + long pos_x = 0; + long pos_y = 0; + + set> visited; + + for ( auto [change, length]: input ) { + if ( change == 'L' ) { + dir = (dir + 1) % 4; + } + else { + dir = (dir + 3) % 4; + } + + auto [delta_x, delta_y] = dirs.at(dir); + + while ( length-- > 0 ) { + pos_x += delta_x; + pos_y += delta_y; + + if ( visited.contains({ pos_x, pos_y }) ) { + cout << abs(pos_x) + abs(pos_y) << endl; + return; + } + + visited.emplace(pos_x, pos_y); + } + } +} + +int +main() +{ + auto input = read_file("data/day01.txt"); + part1(input); + part2(input); +} -- cgit v1.3