-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.rs
69 lines (56 loc) · 1.73 KB
/
18.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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);