summaryrefslogtreecommitdiffstats
path: root/src/day_17.rs
blob: 728e1d8c2c77b3ccad4ba8b38285eda5bd813007 (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use std::{
    cmp::Reverse,
    collections::{hash_map::Entry, BinaryHeap, HashMap},
};

use anyhow::Context;

use crate::{Problem, Solution};

pub struct Day17;

impl Problem for Day17 {
    const DAY: u8 = 17;

    const INPUT: &'static str = include_str!("../input/day_17.txt");
}

impl Solution for Day17 {
    type Answer1 = usize;

    type Answer2 = usize;

    fn part_1(input: &str) -> anyhow::Result<Self::Answer1> {
        let grid = parse_grid(input).context("Failed to parse grid")?;

        astar::<1, 3>(&grid, (0, 0), (grid.len() - 1, grid[0].len() - 1))
            .context("Failed to find path")

        // 755 ==
    }

    fn part_2(input: &str) -> anyhow::Result<Self::Answer2> {
        let grid = parse_grid(input).context("Failed to parse grid")?;

        astar::<4, 10>(&grid, (0, 0), (grid.len() - 1, grid[0].len() - 1))
            .context("Failed to find path")
        // 879 <
        // 881 ==
    }
}

fn parse_grid(input: &str) -> Option<Grid> {
    input
        .lines()
        .map(|v| {
            v.chars()
                .map(|c| c.to_digit(10).map(|n| n as usize))
                .try_collect::<Vec<_>>()
        })
        .try_collect::<Grid>()
}

#[cfg(test)]
fn rebuild_path(edges: &[Edge], start: Position, end: Position) -> Vec<Position> {
    let mut path = vec![];
    let mut position = start;
    for edge in edges {
        path.push(position);
        position = edge.traverse(position).unwrap();
    }
    path.push(end);
    path
}

fn astar<const S: usize, const M: usize>(
    grid: &Grid,
    start: Position,
    goal: Position,
) -> Option<usize> {
    let mut queue = BinaryHeap::from([Reverse(Node::<S, M>::start(start))]);
    let mut cache = HashMap::from([((start, None), usize::MAX)]);

    #[cfg(test)]
    let printer = &mut crate::Printer::from(std::io::stdout().lock());

    while let Some(Reverse(node)) = queue.pop() {
        for (edges, position, cost) in node.successors(grid) {
            let mut next = node.clone();
            next.position = position;
            next.path.extend(edges);
            next.cost += cost;
            next.estimated = next.cost + next.dist(goal);

            #[cfg(test)]
            {
                let node = &next;
                let path = rebuild_path(&node.path, start, node.position);
                printer
                    .with(format_args!("pos: {:?}", node.position))
                    .with(format_args!("score: {}", node.cost))
                    .with(format_args!("trail: {:?}", node.trail()))
                    .with_grid(grid, &path)
                    .clear()
                    .write()
                    .unwrap();
            }

            // pause();
            if next.position == goal {
                #[cfg(test)]
                printer
                    .with(format_args!("score: {}", node.cost))
                    .with_grid(grid, &rebuild_path(&next.path, start, next.position))
                    .clear()
                    .write()
                    .unwrap();
                return Some(next.cost);
            }

            match cache.entry((next.position, next.trail())) {
                Entry::Vacant(e) => {
                    e.insert(next.cost);
                }
                Entry::Occupied(mut e) => {
                    if next.cost < *e.get() {
                        e.insert(next.cost);
                    } else {
                        continue;
                    }
                }
            }

            queue.push(Reverse(next))
        }
    }

    None
}

type Grid = Vec<Vec<usize>>;
type Position = (usize, usize);

#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Node<const STEP: usize, const MAX: usize> {
    estimated: usize,
    cost: usize,
    position: Position,
    path: Vec<Edge>,
}

impl<const S: usize, const M: usize> Node<S, M> {
    fn start(position: Position) -> Self {
        Node {
            position,
            estimated: usize::MAX,
            ..Default::default()
        }
    }

    fn trail(&self) -> Option<[Edge; M]> {
        self.path.last_chunk().copied()
    }

    fn successors(&self, grid: &Grid) -> Vec<(Vec<Edge>, Position, usize)> {
        let (iter, last_seq) = match self.path.last() {
            Some(last) => (
                last.edges(),
                Some((
                    last,
                    self.path.iter().rev().take_while(|e| *e == last).count(),
                )),
            ),
            None => (Edge::ALL.as_slice(), None),
        };

        iter.iter()
            .flat_map(|edge| {
                match last_seq {
                    Some((last, seq)) if last == edge => 1..=(M - seq),
                    _ => S..=M,
                }
                .map(move |step| (edge, step))
            })
            .filter_map(|(edge, step)| self.traverse(*edge, step, grid))
            .collect()
    }

    fn traverse(
        &self,
        edge: Edge,
        step: usize,
        grid: &Grid,
    ) -> Option<(Vec<Edge>, Position, usize)> {
        let mut cost = 0;
        let mut position = self.position;

        for _ in 0..step {
            position = edge.traverse(position)?;
            cost += grid.get(position.0)?.get(position.1)?;
        }

        Some((vec![edge; step], position, cost))
    }

    fn dist(&self, p2: Position) -> usize {
        (self.position.0.abs_diff(p2.0) + self.position.1.abs_diff(p2.1)) * S
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Edge {
    North,
    East,
    South,
    West,
}

impl Edge {
    const ALL: [Edge; 4] = [Edge::North, Edge::East, Edge::South, Edge::West];

    fn edges(&self) -> &[Edge] {
        match self {
            Edge::North => &[Edge::North, Edge::East, Edge::West],
            Edge::East => &[Edge::North, Edge::East, Edge::South],
            Edge::South => &[Edge::East, Self::South, Edge::West],
            Edge::West => &[Edge::North, Edge::South, Edge::West],
        }
    }

    fn traverse(&self, (row, col): Position) -> Option<Position> {
        Some(match self {
            Edge::North => (row.checked_sub(1)?, col),
            Edge::East => (row, col.checked_add(1)?),
            Edge::South => (row.checked_add(1)?, col),
            Edge::West => (row, col.checked_sub(1)?),
        })
    }
}

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

    const INPUT: &str = indoc::indoc! {r#"
        2413432311323
        3215453535623
        3255245654254
        3446585845452
        4546657867536
        1438598798454
        4457876987766
        3637877979653
        4654967986887
        4564679986453
        1224686865563
        2546548887735
        4322674655533
    "#};

    const INPUT2: &str = indoc::indoc! {r#"
        111111111111
        999999999991
        999999999991
        999999999991
        999999999991
    "#};

    #[test]
    fn test_part_1() -> anyhow::Result<()> {
        Ok(assert_eq!(102, Day17::part_1(INPUT)?))
    }

    #[test]
    fn test_part_2_1() -> anyhow::Result<()> {
        Ok(assert_eq!(94, Day17::part_2(INPUT)?))
    }

    #[test]
    fn test_part_2_2() -> anyhow::Result<()> {
        Ok(assert_eq!(71, Day17::part_2(INPUT2)?))
    }
}