Skip to content
advent of code 2016

day 01

no time for a taxicab

approach

the instructions are parsed into (turn, distance) pairs. the walker is a position (r, c) plus a direction vector (dr, dc) that starts pointing up; a turn rotates the vector and the position then moves along it.

part 1 jumps the whole distance in one go and returns the manhattan distance from the origin. part 2 walks one cell at a time instead, keeping every visited cell in a HashSet, and returns the distance of the first cell seen twice.

the trick

a quarter turn is just swapping the two components of the direction vector and negating one of them, so no compass lookup is needed.

rust
fn turn_left(dr: isize, dc: isize) -> (isize, isize) {
    return (-dc, dr);
}

// >  to  v  ->  0,1  to   1,0
// v  to  <  ->  1,0  to  0,-1
// <  to  ^  -> 0,-1  to  -1,0
// ^  to  >  -> -1,0  to   0,1
fn turn_right(dr: isize, dc: isize) -> (isize, isize) {
    return (dc, -dr);
}