summaryrefslogtreecommitdiff
path: root/src/bin/day_13.rs
blob: 547c7a2816a913fcafec2edc307e0bd70c4aa4a2 (plain)
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
use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::{char as nom_char, line_ending, u32 as nom_u32},
    combinator::map,
    multi::{many0, separated_list1},
    sequence::tuple,
    IResult,
};
use std::{collections::BTreeSet, fmt, fs};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_13.txt")?;
    let mut page = parse_page(&input).unwrap().1;
    page.do_next_fold();
    dbg!(page.count_points());
    while page.do_next_fold() {}
    println!("{}", page);

    Ok(())
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Point {
    x: u32,
    y: u32,
}

#[derive(Debug)]
enum Fold {
    X(u32),
    Y(u32),
}

#[derive(Debug)]
struct Page {
    points: BTreeSet<Point>,
    folds: Vec<Fold>,
}

impl Page {
    fn do_next_fold(&mut self) -> bool {
        let fold = self.folds.pop();
        match fold {
            Some(Fold::X(x)) => {
                self.points = std::mem::take(&mut self.points)
                    .into_iter()
                    .filter(|point| point.x != x)
                    .map(|point| {
                        if point.x > x {
                            Point {
                                x: x - (point.x - x),
                                y: point.y,
                            }
                        } else {
                            point
                        }
                    })
                    .collect();
                true
            }
            Some(Fold::Y(y)) => {
                self.points = std::mem::take(&mut self.points)
                    .into_iter()
                    .filter(|point| point.y != y)
                    .map(|point| {
                        if point.y > y {
                            Point {
                                x: point.x,
                                y: y - (point.y - y),
                            }
                        } else {
                            point
                        }
                    })
                    .collect();
                true
            }
            None => false,
        }
    }

    fn count_points(&self) -> usize {
        self.points.len()
    }
}

impl fmt::Display for Page {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let width = self.points.iter().map(|p| p.x).max().unwrap_or(0);
        let height = self.points.iter().map(|p| p.y).max().unwrap_or(0);
        for y in 0..=height {
            for x in 0..=width {
                let p = Point { x, y };
                if self.points.contains(&p) {
                    write!(f, "#")?;
                } else {
                    write!(f, ".")?;
                }
            }
            writeln!(f)?;
        }
        Ok(())
    }
}

fn parse_page(input: &str) -> IResult<&str, Page> {
    let (input, points) = separated_list1(line_ending, parse_point)(input)?;
    let (input, _) = many0(line_ending)(input)?;
    let (input, mut folds) = separated_list1(line_ending, parse_fold)(input)?;
    folds.reverse();
    Ok((
        input,
        Page {
            points: points.into_iter().collect(),
            folds,
        },
    ))
}

fn parse_fold(input: &str) -> IResult<&str, Fold> {
    alt((
        map(tuple((tag("fold along x="), nom_u32)), |(_, val)| {
            Fold::X(val)
        }),
        map(tuple((tag("fold along y="), nom_u32)), |(_, val)| {
            Fold::Y(val)
        }),
    ))(input)
}

fn parse_point(input: &str) -> IResult<&str, Point> {
    map(tuple((nom_u32, nom_char(','), nom_u32)), |(x, _, y)| {
        Point { x, y }
    })(input)
}