-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_13.rs
117 lines (96 loc) Β· 2.77 KB
/
day_13.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
use hashbrown::HashSet;
use common::{solution, Answer};
use nd_vec::vector;
type Point = nd_vec::Vec2<usize>;
solution!("Transparent Origami", 13);
fn part_a(input: &str) -> Answer {
let mut paper = Paper::parse(input);
paper.fold(0);
paper.data.len().into()
}
fn part_b(input: &str) -> Answer {
let mut paper = Paper::parse(input);
(0..paper.folds.len()).for_each(|x| paper.fold(x));
paper.print().into()
}
#[derive(Debug)]
struct Paper {
data: HashSet<Point>,
folds: Vec<Fold>,
}
#[derive(Debug)]
struct Fold {
direction: Direction,
position: usize,
}
#[derive(Debug)]
enum Direction {
Horizontal,
Vertical,
}
impl Paper {
fn parse(raw: &str) -> Self {
let mut parts = raw.split("\n\n");
let data = parts.next().unwrap().lines().map(parse_point).collect();
let folds = parts.next().unwrap().lines().map(parse_fold).collect();
Self { data, folds }
}
// Cordantes go from 0 onwards
fn fold(&mut self, ins: usize) {
let ins = &self.folds[ins];
match ins.direction {
Direction::Horizontal => {
for i in self.data.clone().iter().filter(|x| x.x() > ins.position) {
self.data.remove(i);
self.data.insert(vector!(ins.position * 2 - i.x(), i.y()));
}
}
Direction::Vertical => {
for i in self.data.clone().iter().filter(|x| x.y() > ins.position) {
self.data.remove(i);
self.data.insert(vector!(i.x(), ins.position * 2 - i.y()));
}
}
}
}
fn bounds(&self) -> (usize, usize) {
let x = self.data.iter().map(|x| x.x()).max().unwrap();
let y = self.data.iter().map(|x| x.y()).max().unwrap();
(x, y)
}
fn print(&self) -> String {
let (mx, my) = self.bounds();
let mut out = "\n".to_owned();
for y in 0..=my {
for x in 0..=mx {
let point = vector!(x, y);
if self.data.contains(&point) {
out.push('#');
} else {
out.push(' ');
}
}
out.push('\n');
}
out
}
}
fn parse_point(raw: &str) -> Point {
let parts = raw.split_once(',').unwrap();
let x = parts.0.parse().unwrap();
let y = parts.1.parse().unwrap();
vector!(x, y)
}
fn parse_fold(raw: &str) -> Fold {
let parts = raw.rsplit_once(' ').unwrap().1.split_once('=').unwrap();
let position = parts.1.parse().unwrap();
let direction = match parts.0 {
"x" => Direction::Horizontal,
"y" => Direction::Vertical,
_ => unreachable!(),
};
Fold {
direction,
position,
}
}