[Rust/2023/18] Add solution

This commit is contained in:
Felix Bargfeldt 2023-12-18 07:52:52 +01:00
parent eb815d4905
commit 791a2423e7
Signed by: Defelo
GPG key ID: 2A05272471204DD3
7 changed files with 99 additions and 2 deletions

File diff suppressed because one or more lines are too long

69
Rust/2023/18.rs Normal file
View file

@ -0,0 +1,69 @@
#![feature(test)]
use aoc::grid::Direction;
use regex::Regex;
#[derive(Debug)]
struct Input {
part1: Vec<Instruction>,
part2: Vec<Instruction>,
}
#[derive(Debug)]
struct Instruction {
direction: Direction,
steps: isize,
}
fn setup(input: &str) -> Input {
let regex = Regex::new(r"^([UDLR]) (\d+) \(#(.{5})([0123])\)$").unwrap();
let (part1, part2) = input
.lines()
.map(|line| {
let cap = regex.captures(line).unwrap();
let p1 = Instruction {
direction: Direction::from(cap[1].chars().next().unwrap()),
steps: cap[2].parse().unwrap(),
};
let p2 = Instruction {
direction: match &cap[4] {
"0" => Direction::East,
"1" => Direction::South,
"2" => Direction::West,
"3" => Direction::North,
_ => unreachable!(),
},
steps: isize::from_str_radix(&cap[3], 16).unwrap(),
};
(p1, p2)
})
.unzip();
Input { part1, part2 }
}
fn solve(instructions: &[Instruction]) -> usize {
let (_, a, b) = instructions
.iter()
.fold((0, 0, 0), |(x, a, b), i| match i.direction {
Direction::North => (x, a - i.steps * x, b + i.steps),
Direction::East => (x + i.steps, a, b + i.steps),
Direction::South => (x, a + i.steps * x, b + i.steps),
Direction::West => (x - i.steps, a, b + i.steps),
});
a.unsigned_abs() + b.unsigned_abs() / 2 + 1
}
fn part1(input: &Input) -> usize {
solve(&input.part1)
}
fn part2(input: &Input) -> usize {
solve(&input.part2)
}
aoc::main!(2023, 18, ex: 1);

View file

@ -275,3 +275,6 @@ path = "2023/16.rs"
[[bin]]
name = "2023_17"
path = "2023/17.rs"
[[bin]]
name = "2023_18"
path = "2023/18.rs"

View file

@ -26,6 +26,15 @@ impl Direction {
}
}
pub fn step_signed_n(self, (x, y): (isize, isize), n: isize) -> (isize, isize) {
match self {
Direction::North => (x, y - n),
Direction::East => (x + n, y),
Direction::South => (x, y + n),
Direction::West => (x - n, y),
}
}
pub fn invert(self) -> Self {
match self {
Direction::North => Direction::South,

14
examples/2023/18/1 Normal file
View file

@ -0,0 +1,14 @@
R 6 (#70c710)
D 5 (#0dc571)
L 2 (#5713f0)
D 2 (#d2c081)
R 2 (#59c680)
D 2 (#411b91)
L 5 (#8ceee2)
U 2 (#caa173)
L 1 (#1b58a2)
U 2 (#caa171)
R 2 (#7807d2)
U 3 (#a77fa3)
L 2 (#015232)
U 2 (#7a21e3)

1
examples/2023/18/1.1 Normal file
View file

@ -0,0 +1 @@
62

1
examples/2023/18/1.2 Normal file
View file

@ -0,0 +1 @@
952408144115