-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-13.rs
143 lines (124 loc) · 3.51 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::{fmt::Display, str::FromStr};
const INPUT: &str = include_str!("day-13.input");
struct Dots {
map: Vec<bool>,
pitch: usize,
width: usize,
height: usize,
}
impl Dots {
fn fold(&mut self, fold: Fold) {
match fold {
Fold::AlongX(x) => {
assert!(x <= self.width / 2);
for i in 1..=x {
if x + i >= self.width {
continue;
}
let xl = x - i;
let xr = x + i;
for y in 0..self.height {
self.map[y * self.pitch + xl] |= self.map[y * self.pitch + xr];
}
}
self.width = x;
}
Fold::AlongY(y) => {
assert!(y <= self.height / 2);
for i in 1..=y {
if y + i >= self.height {
continue;
}
let yu = y - i;
let yd = y + i;
for x in 0..self.width {
self.map[yu * self.pitch + x] |= self.map[yd * self.pitch + x];
}
}
self.height = y;
}
}
}
fn count_dots(&self) -> usize {
let mut dots = 0;
for y in 0..self.height {
for x in 0..self.width {
dots += self.map[y * self.pitch + x] as usize;
}
}
dots
}
}
impl FromStr for Dots {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let it = s.lines().map(|line| {
let (x, y) = line.split_once(',').unwrap();
(x.parse::<usize>().unwrap(), y.parse::<usize>().unwrap())
});
let mut width = 0;
let mut height = 0;
for (x, y) in it.clone() {
width = width.max(x + 1);
height = height.max(y + 1);
}
let mut map = vec![false; width * height];
for (x, y) in it {
map[y * width + x] = true;
}
Ok(Self {
map,
pitch: width,
width,
height,
})
}
}
impl Display for Dots {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for y in 0..self.height {
for x in 0..self.width {
write!(
f,
"{}",
if self.map[y * self.pitch + x] {
'#'
} else {
' '
}
)?;
}
writeln!(f)?;
}
Ok(())
}
}
#[derive(Clone, Copy)]
enum Fold {
AlongX(usize),
AlongY(usize),
}
impl FromStr for Fold {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (along, n) = s.split_once('=').unwrap();
let n = n.trim().parse().unwrap();
Ok(match along {
"fold along x" => Fold::AlongX(n),
"fold along y" => Fold::AlongY(n),
_ => panic!("unrecongized fold `{}`", s),
})
}
}
fn main() {
let (dots, folds) = INPUT.trim().split_once("\n\n").unwrap();
let mut dots = dots.parse::<Dots>().unwrap();
let folds: Vec<Fold> = folds.lines().map(|s| s.parse().unwrap()).collect();
dots.fold(folds[0]);
println!("part 1: {}", dots.count_dots());
for &fold in folds.iter().skip(1) {
dots.fold(fold);
}
println!("part 2:");
println!("{}", dots);
}