solution: day1

This commit is contained in:
2023-01-24 21:38:58 +01:00
parent 0000001031
commit 000000208b
2 changed files with 98 additions and 0 deletions

97
src/bin/01.rs Normal file
View File

@@ -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<Direction>, 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<isize> {
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<isize> {
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));
}
}

1
src/examples/01.txt Normal file
View File

@@ -0,0 +1 @@
R8, R4, R4, R8