summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_17.rs
blob: 99d828b7641d392eab0c871bfc0d8f82c78f97b0 (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
use nalgebra::{DMatrix, Point2, Unit, Vector2};
use nom::{
    character::complete::{line_ending, satisfy},
    combinator::{map, map_res},
    multi::{many1, separated_list1},
    IResult,
};
use std::{collections::HashSet, fs};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_17.txt")?;
    let parsed = HeatlossMap::parser(&input).unwrap().1;
    dbg!(&parsed.find_shortest_heatloss_path());

    Ok(())
}

#[derive(Debug)]
struct HeatlossMap(DMatrix<u32>);

#[derive(Debug, Hash, PartialEq, Eq, Clone)]
struct Position {
    pos: Point2<isize>,
    facing: Unit<Vector2<isize>>,
    duration_with_facing: usize,
}

impl HeatlossMap {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_list1(
                line_ending,
                many1(map_res(satisfy(|c| c.is_digit(10)), |d| {
                    d.to_string().parse::<u32>()
                })),
            ),
            |digits_vec| {
                HeatlossMap(DMatrix::from_iterator(
                    digits_vec.len(),
                    digits_vec[0].len(),
                    digits_vec.into_iter().flat_map(|row| row.into_iter()),
                ))
            },
        )(input)
    }

    fn find_shortest_heatloss_path(&self) -> u32 {
        let start = Position {
            pos: Point2::new(0, 0),
            facing: Vector2::x_axis(),
            duration_with_facing: 0,
        };
        let end_pos = self.end();

        let mut frontier = vec![(0, start.clone())];
        let mut visited = HashSet::new();
        visited.insert(start);

        let mut distance_to_end = None;
        while distance_to_end.is_none() && frontier.len() > 0 {
            // shortest distance is now at the end
            frontier
                .sort_unstable_by(|(distance_a, _), (distance_b, _)| distance_b.cmp(distance_a));
            let (front_distance, front_position) = frontier.pop().unwrap();

            let mut next_points: Vec<Position> = Vec::new();
            {
                let facing = rotate_left(&front_position.facing);
                let pos = front_position.pos + *facing;
                next_points.push(Position {
                    pos,
                    facing,
                    duration_with_facing: 1,
                });
            }
            {
                let facing = rotate_right(&front_position.facing);
                let pos = front_position.pos + *facing;
                next_points.push(Position {
                    pos,
                    facing,
                    duration_with_facing: 1,
                });
            }
            if front_position.duration_with_facing < 3 {
                let pos = front_position.pos + *front_position.facing;
                next_points.push(Position {
                    pos,
                    facing: front_position.facing.clone(),
                    duration_with_facing: front_position.duration_with_facing + 1,
                });
            }

            for next_point in next_points {
                if let Some(step_distance) = self.get(&next_point.pos) {
                    if !visited.contains(&next_point) {
                        visited.insert(next_point.clone());

                        let distance = front_distance + step_distance;

                        if next_point.pos == end_pos {
                            distance_to_end = Some(distance);
                        }
                        frontier.push((distance, next_point));
                    }
                }
            }
        }

        distance_to_end.unwrap()
    }

    fn end(&self) -> Point2<isize> {
        Point2::new(self.0.ncols() as isize - 1, self.0.nrows() as isize - 1)
    }

    fn get(&self, pos: &Point2<isize>) -> Option<u32> {
        let x: Option<usize> = pos.x.try_into().ok();
        let y: Option<usize> = pos.y.try_into().ok();

        match (x, y) {
            (Some(x), Some(y)) => self.0.get((x, y)).copied(),
            _ => None,
        }
    }
}

fn rotate_left(facing: &Unit<Vector2<isize>>) -> Unit<Vector2<isize>> {
    Unit::new_unchecked(Vector2::new(-facing.y, facing.x))
}

fn rotate_right(facing: &Unit<Vector2<isize>>) -> Unit<Vector2<isize>> {
    Unit::new_unchecked(Vector2::new(facing.y, -facing.x))
}