-
Notifications
You must be signed in to change notification settings - Fork 0
/
day18.rs
122 lines (100 loc) · 2.87 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
118
119
120
121
122
//! [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 {
data: String,
}
impl Puzzle {
fn new() -> Puzzle {
Puzzle {
data: String::new(),
}
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
self.data = 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)
}
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 62);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 952408144115);
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}