summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_8.rs
blob: b96b43a912abe64ce80c6391c149149ab0419e93 (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
use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::{alpha1, char as nom_char, line_ending},
    combinator::{map, value},
    multi::{many1, separated_list1},
    sequence::{pair, preceded, separated_pair, terminated},
    IResult,
};
use std::{collections::BTreeMap, fs, ops::Range};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_8.txt")?;
    let directions = Directions::parser(&input).unwrap().1;
    dbg!(directions.steps_from_a_to_z());
    dbg!(directions.ghost_steps_from_a_to_z());

    Ok(())
}

#[derive(Debug)]
struct Directions {
    turns: Vec<Turn>,
    packed_map: Vec<PackedFork>,
    packed_ghost_starts: Range<u16>,
    packed_ghost_destinations: Range<u16>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Turn {
    Left,
    Right,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Location(String);

#[derive(Debug)]
struct Fork {
    left: Location,
    right: Location,
}

#[derive(Debug)]
struct PackedFork {
    left: u16,
    right: u16,
}

impl Directions {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_pair(
                many1(Turn::parser),
                pair(line_ending, line_ending),
                separated_list1(
                    line_ending,
                    separated_pair(Location::parser, tag(" = "), Fork::parser),
                ),
            ),
            |(turns, map)| {
                let map: BTreeMap<Location, Fork> = map.into_iter().collect();
                let mut locations: Vec<Location> = map.keys().cloned().collect();
                locations.sort_by_key(|l| l.0.chars().rev().collect::<String>());

                Directions {
                    turns,
                    packed_map: locations
                        .iter()
                        .map(|l| {
                            let unpacked_fork = map.get(l).unwrap();
                            PackedFork {
                                left: locations
                                    .iter()
                                    .position(|f| *f == unpacked_fork.left)
                                    .unwrap() as u16,
                                right: locations
                                    .iter()
                                    .position(|f| *f == unpacked_fork.right)
                                    .unwrap() as u16,
                            }
                        })
                        .collect(),
                    packed_ghost_starts: 0
                        ..locations.iter().position(|l| !l.ghost_start()).unwrap() as u16,
                    packed_ghost_destinations: locations.iter().position(|l| l.ghost_end()).unwrap()
                        as u16
                        ..locations.len() as u16,
                }
            },
        )(input)
    }

    fn steps_from_a_to_z(&self) -> usize {
        let mut step_count = 0;
        let mut current_location: u16 = 0;

        for dir in self.turns.iter().cycle() {
            let current_fork: &PackedFork = &self.packed_map[current_location as usize];
            current_location = match dir {
                Turn::Left => current_fork.left,
                Turn::Right => current_fork.right,
            };
            step_count += 1;

            if current_location == self.packed_map.len() as u16 - 1 {
                return step_count;
            }
        }
        unreachable!()
    }

    fn ghost_steps_from_a_to_z(&self) -> usize {
        let mut step_count = 0;
        let mut current_locations: Vec<u16> = self.packed_ghost_starts.clone().collect();

        for dir in self.turns.iter().cycle() {
            for current_location in &mut current_locations {
                let current_fork: &PackedFork = &self.packed_map[*current_location as usize];
                *current_location = match dir {
                    Turn::Left => current_fork.left,
                    Turn::Right => current_fork.right,
                };
            }
            step_count += 1;

            if current_locations
                .iter()
                .all(|l| self.packed_ghost_destinations.contains(l))
            {
                return step_count;
            }
        }
        unreachable!()
    }
}

impl Turn {
    fn parser(input: &str) -> IResult<&str, Self> {
        alt((
            value(Turn::Left, nom_char('L')),
            value(Turn::Right, nom_char('R')),
        ))(input)
    }
}

impl Location {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(alpha1, |l: &str| Location(l.to_string()))(input)
    }

    fn ghost_start(&self) -> bool {
        self.0.ends_with("A")
    }

    fn ghost_end(&self) -> bool {
        self.0.ends_with("Z")
    }
}

impl Fork {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            preceded(
                tag("("),
                terminated(
                    separated_pair(Location::parser, tag(", "), Location::parser),
                    tag(")"),
                ),
            ),
            |(left, right)| Fork { left, right },
        )(input)
    }
}