Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epidemian
GitHub Repository: epidemian/advent-of-code-2021
Path: blob/main/src/day13.rs
97 views
1
use std::collections::HashSet;
2
3
pub fn run() {
4
let (dots_part, folds_part) = include_str!("inputs/day13").split_once("\n\n").unwrap();
5
let mut dots: Dots = parse_dots(dots_part);
6
let folds: Vec<Fold> = parse_folds(folds_part);
7
8
for (i, fold) in folds.iter().enumerate() {
9
dots = fold_paper(&dots, fold);
10
if i == 0 {
11
println!("{}", dots.len());
12
}
13
}
14
15
print_dots(&dots);
16
}
17
18
type Dots = HashSet<(i32, i32)>;
19
type Fold = (char, i32);
20
21
fn parse_dots(s: &str) -> Dots {
22
s.lines()
23
.map(|l| {
24
let (x, y) = l.split_once(",").unwrap();
25
(x.parse().unwrap(), y.parse().unwrap())
26
})
27
.collect()
28
}
29
30
fn parse_folds(s: &str) -> Vec<Fold> {
31
s.lines()
32
.map(|l| {
33
let (lhs, rhs) = l.split_once("=").unwrap();
34
(lhs.chars().last().unwrap(), rhs.parse().unwrap())
35
})
36
.collect()
37
}
38
39
fn fold_paper(dots: &Dots, fold: &Fold) -> Dots {
40
dots
41
.iter()
42
.map(|&(x, y)| match fold {
43
&('x', fx) => (if x < fx { x } else { fx - (x - fx) }, y),
44
&('y', fy) => (x, if y < fy { y } else { fy - (y - fy) }),
45
_ => unreachable!(),
46
})
47
.collect()
48
}
49
50
fn print_dots(dots: &Dots) {
51
let max_x = *dots.iter().map(|(x, _)| x).max().unwrap();
52
let max_y = *dots.iter().map(|(_, y)| y).max().unwrap();
53
54
for y in 0..=max_y {
55
for x in 0..=max_x {
56
print!("{}", if dots.contains(&(x, y)) { "#" } else { " " })
57
}
58
println!()
59
}
60
}
61
62