summaryrefslogtreecommitdiff
path: root/src/bin/day_20.rs
blob: eb10864de82db60292226bd944fa19cf11e12bfa (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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use rpds::rbt_set;
use rpds::vector;
use rpds::vector::Vector;
use rpds::RedBlackTreeMap;
use rpds::RedBlackTreeSet;
use std::io;
use std::io::prelude::*;
use std::iter;
use std::iter::FromIterator;
use std::process;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "Day 20: Donut Maze")]
/// Finds the shortest path through a maze with portals.
///
/// See https://adventofcode.com/2019/day/20 for details.
struct Opt {}

fn main() {
    let stdin = io::stdin();
    let _opt = Opt::from_args();

    let maze = stdin
        .lock()
        .lines()
        .map(|x| exit_on_failed_assertion(x, "Error reading input"))
        .collect::<MazeBuilder>()
        .build();

    println!("{}", maze.shortest_route());
}

fn exit_on_failed_assertion<A, E: std::error::Error>(data: Result<A, E>, message: &str) -> A {
    match data {
        Ok(data) => data,
        Err(e) => {
            eprintln!("{}: {}", message, e);
            process::exit(1);
        }
    }
}

struct MazeBuilder {
    map: Vector<Vector<char>>,
    portals: Vector<([char; 2], Point)>,
}

impl FromIterator<String> for MazeBuilder {
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        MazeBuilder {
            map: iter
                .into_iter()
                .map(|line| line.chars().collect())
                .collect(),
            portals: Vector::new(),
        }
    }
}

impl MazeBuilder {
    fn build(self) -> Maze {
        Maze {
            walls: self
                .map
                .iter()
                .map(|line| line.iter().map(|ch| *ch != '.').collect())
                .collect(),
            portals: self.grouped_portals(),
            entrance: self
                .all_portals()
                .find(|(id, _)| *id == ['A', 'A'])
                .unwrap()
                .1,
            exit: self
                .all_portals()
                .find(|(id, _)| *id == ['Z', 'Z'])
                .unwrap()
                .1,
        }
    }

    fn grouped_portals(&self) -> Vector<(Point, Point)> {
        self.all_portals()
            .fold(
                (Vector::new(), RedBlackTreeMap::new()),
                |(matched, unmatched): (
                    Vector<(Point, Point)>,
                    RedBlackTreeMap<[char; 2], Point>,
                ),
                 (next_id, next_p)| match unmatched.get(&next_id) {
                    Some(pair) => (
                        matched.push_back((pair.clone(), next_p)),
                        unmatched.remove(&next_id),
                    ),
                    None => (matched, unmatched.insert(next_id, next_p)),
                },
            )
            .0
    }

    fn all_portals(&self) -> impl Iterator<Item = ([char; 2], Point)> + '_ {
        self.horizontal_trailing_portals()
            .chain(self.horizontal_leading_portals())
            .chain(self.vertical_trailing_portals())
            .chain(self.vertical_leading_portals())
    }

    fn horizontal_trailing_portals(&self) -> impl Iterator<Item = ([char; 2], Point)> + '_ {
        // .XX
        (0..self.map.len())
            .flat_map(move |y| (0..self.map[y].len() - 2).map(move |x| Point { x, y }))
            .filter(move |p| {
                self.map[p.y][p.x] == '.'
                    && self.map[p.y][p.x + 1].is_alphabetic()
                    && self.map[p.y][p.x + 2].is_alphabetic()
            })
            .map(move |p| ([self.map[p.y][p.x + 1], self.map[p.y][p.x + 2]], p))
    }

    fn horizontal_leading_portals(&self) -> impl Iterator<Item = ([char; 2], Point)> + '_ {
        // XX.
        (0..self.map.len())
            .flat_map(move |y| (0..self.map[y].len() - 2).map(move |x| Point { x, y }))
            .filter(move |p| {
                self.map[p.y][p.x + 2] == '.'
                    && self.map[p.y][p.x + 1].is_alphabetic()
                    && self.map[p.y][p.x].is_alphabetic()
            })
            .map(move |p| {
                (
                    [self.map[p.y][p.x], self.map[p.y][p.x + 1]],
                    Point { x: p.x + 2, y: p.y },
                )
            })
    }

    fn vertical_trailing_portals(&self) -> impl Iterator<Item = ([char; 2], Point)> + '_ {
        // .XX
        (0..self.map[0].len())
            .flat_map(move |x| (0..self.map.len() - 2).map(move |y| Point { x, y }))
            .filter(move |p| {
                self.map[p.y][p.x] == '.'
                    && self.map[p.y + 1][p.x].is_alphabetic()
                    && self.map[p.y + 2][p.x].is_alphabetic()
            })
            .map(move |p| ([self.map[p.y + 1][p.x], self.map[p.y + 2][p.x]], p))
    }

    fn vertical_leading_portals(&self) -> impl Iterator<Item = ([char; 2], Point)> + '_ {
        // XX.
        (0..self.map[0].len())
            .flat_map(move |x| (0..self.map.len() - 2).map(move |y| Point { x, y }))
            .filter(move |p| {
                self.map[p.y + 2][p.x] == '.'
                    && self.map[p.y + 1][p.x].is_alphabetic()
                    && self.map[p.y][p.x].is_alphabetic()
            })
            .map(move |p| {
                (
                    [self.map[p.y][p.x], self.map[p.y + 1][p.x]],
                    Point { x: p.x, y: p.y + 2 },
                )
            })
    }
}

#[derive(Debug)]
struct Maze {
    walls: Vector<Vector<bool>>,
    portals: Vector<(Point, Point)>,
    entrance: Point, // AA
    exit: Point,     // ZZ
}

#[derive(Debug, Clone)]
struct Point {
    x: usize,
    y: usize,
}

impl Maze {
    fn shortest_route(&self) -> usize {
        unimplemented!()
    }
}