summaryrefslogtreecommitdiff
path: root/src/bin/day10.rs
blob: 4d722b0b2e71817d15c434188943396b5bf062c7 (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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use std::collections::HashMap;

static DAY: u8 = 10;

fn main() {
    let input = advent::read_lines(DAY);
    println!("{DAY}a: {}", steps_to_farthest(&input));
    println!("{DAY}b: {}", 0);
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Direction {
    North,
    South,
    East,
    West,
}

impl Direction {
    fn from(c: char) -> [Direction; 2] {
        match c {
            '|' => [Direction::South, Direction::North],
            '-' => [Direction::West, Direction::East],
            'L' => [Direction::North, Direction::East],
            'J' => [Direction::North, Direction::West],
            '7' => [Direction::South, Direction::West],
            'F' => [Direction::South, Direction::East],
            _ => panic!("unexpected pipe"),
        }
    }

    fn opposite(&self) -> Direction {
        match *self {
            Direction::North => Direction::South,
            Direction::South => Direction::North,
            Direction::West => Direction::East,
            Direction::East => Direction::West,
        }
    }
}

#[derive(PartialEq, Eq, Hash, Clone, Copy)]
struct Position {
    x: isize,
    y: isize,
}

struct Map {
    start: Position,
    pipes: HashMap<Position, [Direction; 2]>,
}

impl Map {
    fn new(input: &[String]) -> Map {
        let mut start = Position { x: 0, y: 0 };
        let mut pipes = HashMap::new();
        for (y, line) in input.iter().enumerate() {
            for (x, c) in line.chars().enumerate() {
                let pos = Position { x: x as isize, y: y as isize };
                match c {
                    'S' => { start = pos },
                    '.' => continue,
                    pipe => { pipes.insert(pos, Direction::from(pipe)); },
                }
            }
        }
        Map { start, pipes }
    }

    fn pos_connectable(&self, pos: &Position, from_direction: Direction) -> bool {
        if *pos == self.start {
            /* pipe at start is unknown; assume that it can connect to anything */
            true
        } else if let Some(directions) = self.pipes.get(pos) {
            match from_direction {
                Direction::North => { directions.contains(&Direction::South) },
                Direction::South => { directions.contains(&Direction::North) },
                Direction::East => { directions.contains(&Direction::West) },
                Direction::West => { directions.contains(&Direction::East) },
            }
        } else {
            false
        }
    }

    fn remove_disconnected_pipes(&mut self) {
        let mut disconnected_pipes = Vec::new();
        loop {
            disconnected_pipes.clear();
            for (pos, directions) in &self.pipes {
                for direction in directions {
                    match direction {
                        Direction::North => if !self.pos_connectable(&Position { x: pos.x, y: pos.y - 1 }, *direction) { disconnected_pipes.push(*pos); },
                        Direction::South => if !self.pos_connectable(&Position { x: pos.x, y: pos.y + 1 }, *direction) { disconnected_pipes.push(*pos); },
                        Direction::West => if !self.pos_connectable(&Position { x: pos.x - 1, y: pos.y }, *direction) { disconnected_pipes.push(*pos); },
                        Direction::East => if !self.pos_connectable(&Position { x: pos.x + 1, y: pos.y }, *direction) { disconnected_pipes.push(*pos); },
                    }
                }
            }
            for pos in &disconnected_pipes {
                self.pipes.remove(pos);
            }
            if disconnected_pipes.is_empty() {
                break;
            }
        }
    }

    fn other_direction(&self, pos: &Position, direction: Direction) -> Direction {
        /* get the direction from the other end of the pipe */
        let directions = self.pipes.get(pos).unwrap();
        if directions[0] == direction {
            directions[1]
        } else {
            directions[0]
        }
    }

    fn count_steps(&self) -> u32 {
        let mut steps = 0;

        let mut pos = self.start;
        let mut direction = Direction::North;

        /* check for possible connection from starting position */
        if self.pos_connectable(&Position { x: pos.x, y: pos.y - 1 }, Direction::North) { direction = Direction::North; }
        else if self.pos_connectable(&Position { x: pos.x, y: pos.y + 1 }, Direction::South) { direction = Direction::South; }
        else if self.pos_connectable(&Position { x: pos.x - 1, y: pos.y }, Direction::West) { direction = Direction::West; }
        else if self.pos_connectable(&Position { x: pos.x + 1, y: pos.y }, Direction::East) { direction = Direction::East; }

        loop {
            let next_pos = match direction {
                Direction::North => Position { x: pos.x, y: pos.y - 1 },
                Direction::South => Position { x: pos.x, y: pos.y + 1 },
                Direction::West => Position { x: pos.x - 1, y: pos.y },
                Direction::East => Position { x: pos.x + 1, y: pos.y },
            };
            steps += 1;

            if next_pos == self.start {
                break;
            }

            direction = self.other_direction(&next_pos, direction.opposite());
            pos = next_pos;
        }

        steps
    }

    fn _print_map(&self) {
        let max_x = self.pipes.keys().map(|pos| pos.x).max().unwrap();
        let max_y = self.pipes.keys().map(|pos| pos.y).max().unwrap();

        for y in 0 ..= max_y {
            for x in 0 ..= max_x {
                let pos = Position { x, y };
                if pos == self.start {
                    print!("S");
                    continue;
                }
                if let Some(direction) = self.pipes.get(&pos) {
                    match direction {
                        [Direction::South, Direction::North] => { print!("|"); },
                        [Direction::West, Direction::East] => { print!("-"); },
                        [Direction::North, Direction::East] => { print!("L"); },
                        [Direction::North, Direction::West] => { print!("J"); },
                        [Direction::South, Direction::West] => { print!("7"); },
                        [Direction::South, Direction::East] => { print!("F"); },
                        _ => panic!("unexpected directions"),
                    }
                } else {
                    print!(".");
                }
            }
            println!();
        }
    }
}

fn steps_to_farthest(input: &[String]) -> u32 {
    let mut map = Map::new(input);
    map.remove_disconnected_pipes();
    map.count_steps() / 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        let input = [
            "-L|F7",
            "7S-7|",
            "L|7||",
            "-L-J|",
            "L|-JF",
        ].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
        assert_eq!(steps_to_farthest(&input), 4);

        let input = [
            "7-F7-",
            ".FJ|7",
            "SJLL7",
            "|F--J",
            "LJ.LJ",
        ].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
        assert_eq!(steps_to_farthest(&input), 8);
    }
}