day 02
bathroom security
approach
the keypad is a grid of characters written straight into the source. each input line is a run of U, D, L, R moves; a move that would leave the grid, or land on a #, is ignored. after each line the key under the current position is appended to the code, and the next line carries on from there.
part 1 uses the plain 3×3 keypad starting on 5. part 2 runs the same function on a 5×5 grid where the diamond-shaped keypad is padded with #, again starting on 5.
the trick
padding the odd-shaped keypad with # cells turns its outline into ordinary walls, so both parts share one step.
rust
fn step(grid: &Vec<Vec<char>>, r: isize, c: isize, dr: isize, dc: isize) -> (isize, isize) {
let n = grid.len() as isize;
let m = grid[grid.len() - 1].len() as isize;
if ((r + dr) < 0) | ((c + dc) < 0) | ((r + dr) == n) | ((c + dc) == m) {
return (r, c);
} else {
let nr = (r + dr) as usize;
let nc = (c + dc) as usize;
if grid[nr][nc] == '#' {
return (r, c);
} else {
return (nr as isize, nc as isize);
}
}
}