diff --git a/src/bin/01.rs b/src/bin/01.rs new file mode 100644 index 0000000000..8124586 --- /dev/null +++ b/src/bin/01.rs @@ -0,0 +1,97 @@ +use hashbrown::HashSet; + +enum Rotation { + Left, + Right, +} + +fn rotate(direction: (isize, isize), rotation: &Rotation) -> (isize, isize) { + match rotation { + Rotation::Right => (-direction.1, direction.0), + Rotation::Left => (direction.1, -direction.0), + } +} + +enum Direction { + Move(isize), + Rotate(Rotation), +} + +fn expand_directions(dv: &mut Vec, d: &str) { + let (r, m) = d.split_at(1); + + let dir = match r { + "L" => Rotation::Left, + "R" => Rotation::Right, + _ => unreachable!(), + }; + + dv.push(Direction::Rotate(dir)); + dv.push(Direction::Move(m.parse().unwrap())); +} + +pub fn part_one(input: &str) -> Option { + let mut directions = Vec::new(); + + for d in input.split(", ") { + expand_directions(&mut directions, d); + } + + let (mut x, mut y) = (0, 0); + let (mut dx, mut dy) = (1, 0); + + for d in directions { + match d { + Direction::Rotate(r) => (dx, dy) = rotate((dx, dy), &r), + Direction::Move(n) => (x, y) = (x + dx * n, y + dy * n), + } + } + + Some(x.abs() + y.abs()) +} +pub fn part_two(input: &str) -> Option { + let mut directions = Vec::new(); + + for d in input.split(", ") { + expand_directions(&mut directions, d); + } + + let (mut x, mut y) = (0, 0); + let (mut dx, mut dy) = (1, 0); + let mut visited = HashSet::new(); + + for d in directions { + match d { + Direction::Rotate(r) => (dx, dy) = rotate((dx, dy), &r), + Direction::Move(n) => { + for _ in 1..=n { + (x, y) = (x + dx, y + dy); + if !visited.insert((x, y)) { + return Some(x.abs() + y.abs()); + } + } + } + } + } + + None +} +fn main() { + let input = &aoc::read_file("inputs", 1); + aoc::solve!(1, part_one, input); + aoc::solve!(2, part_two, input); +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_part_one() { + let input = aoc::read_file("examples", 1); + assert_eq!(part_one(&input), Some(8)); + } + #[test] + fn test_part_two() { + let input = aoc::read_file("examples", 1); + assert_eq!(part_two(&input), Some(4)); + } +} diff --git a/src/examples/01.txt b/src/examples/01.txt new file mode 100644 index 0000000000..1d6615f --- /dev/null +++ b/src/examples/01.txt @@ -0,0 +1 @@ +R8, R4, R4, R8