-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday18.rs
117 lines (94 loc) · 2.69 KB
/
day18.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//! [Day 18: Lavaduct Lagoon](https://adventofcode.com/2023/day/18)
/// Use the Shoelace and Pick formulas to compute polygon area.
fn shoelace(points: &[(i64, i64)], contour_length: i64) -> i64 {
let n = points.len();
let mut area = 0;
for i in 0..n {
let x1 = points[i].0;
let y0 = points[(i + n - 1) % n].1;
let y2 = points[(i + 1) % n].1;
area += x1 * (y0 - y2);
}
area.abs() / 2 + contour_length / 2 + 1
}
struct Puzzle<'a> {
data: &'a str,
}
impl<'a> Puzzle<'a> {
const fn new(data: &'a str) -> Self {
Self { data }
}
/// Solve part one.
fn part1(&self) -> i64 {
let mut x = 0i64;
let mut y = 0i64;
let mut points = vec![];
let mut length = 0;
points.push((x, y));
for line in self.data.lines() {
let mut line = line.split_ascii_whitespace();
let direction = line.next().unwrap();
let steps: i64 = line.next().unwrap().parse().unwrap();
match direction {
"U" => y += steps,
"D" => y -= steps,
"R" => x += steps,
"L" => x -= steps,
_ => panic!(),
}
length += steps;
points.push((x, y));
}
shoelace(&points, length)
}
/// Solve part two.
fn part2(&self) -> i64 {
let mut x = 0i64;
let mut y = 0i64;
let mut points = vec![];
let mut length = 0;
points.push((x, y));
for line in self.data.lines() {
let color = line.split_ascii_whitespace().nth(2).unwrap();
let color = &color[2..8];
let color = i64::from_str_radix(color, 16).unwrap();
let direction = color % 16;
let steps = color / 16;
match direction {
0 => x += steps, // R
1 => y -= steps, // D
2 => x -= steps, // L
3 => y += steps, // U
_ => panic!(),
}
length += steps;
points.push((x, y));
}
shoelace(&points, length)
}
}
/// # Panics
#[must_use]
pub fn solve(data: &str) -> (i64, i64) {
let puzzle = Puzzle::new(data);
(puzzle.part1(), puzzle.part2())
}
pub fn main() {
let args = aoc::parse_args();
args.run(solve);
}
#[cfg(test)]
mod test {
use super::*;
const TEST_INPUT: &str = include_str!("test.txt");
#[test]
fn test01() {
let puzzle = Puzzle::new(TEST_INPUT);
assert_eq!(puzzle.part1(), 62);
}
#[test]
fn test02() {
let puzzle = Puzzle::new(TEST_INPUT);
assert_eq!(puzzle.part2(), 952408144115);
}
}