Day 01 - No Time for a Taxicab
Language: Rust
Problem https://adventofcode.com/2016/day/1
Part 1:
Instructions like R2 or L5: turn, then walk that many blocks. Starting at the origin
facing North, find the Manhattan distance to the final position.
I track direction as an index into a directions array and update x and y by the full
step count at once:
let directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]; // N, E, S, W
dir = match turn {
"R" => (dir + 1) % 4,
"L" => (dir + 3) % 4,
_ => panic!("Invalid turn"),
};
let (dx, dy) = directions[dir];
x += dx * steps;
y += dy * steps;
Answer is x.abs() + y.abs().
Part 2:
Find the first location visited twice. Since each instruction can cover multiple blocks, I
walk one step at a time and check every intermediate position against a HashSet:
for _ in 0..steps {
x += dx;
y += dy;
if !visited.insert((x, y)) {
return (x.abs() + y.abs()).to_string();
}
}
HashSet::insert returns false if the value was already present, so the check and insert
happen in one call.
Solution: https://github.com/Elyrial/AdventOfCode/blob/main/src/solutions/year2016/day01.rs
No C writeup yet.