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
//! Searching algorithms.
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
use std::ops::Add;

/// This trait allows searching algorithms to navigate a space.
pub trait Navigable {
    /// Describes a single point in the searchable space.
    type Point;

    /// The distance score between points a and b.
    fn distance_score(&self, a: &Self::Point, b: &Self::Point) -> u64;

    /// Returns the points that can be reached directly from `point`, together with the distance.
    fn get_neighbours(&self, point: &Self::Point) -> Vec<(u64, Self::Point)>;

    /// Use [A*](https://en.wikipedia.org/wiki/A*_search_algorithm) to find the shortest path
    /// between two points within a `Navigable` space.
    fn find_shortest_path(&self, start: &Self::Point, end: &Self::Point) -> Option<Vec<Self::Point>>
    where
        Self::Point: Hash + PartialEq + Eq + Clone,
    {
        let mut open_set: BinaryHeap<SortablePoint<Self::Point>> = BinaryHeap::new();
        open_set.push(SortablePoint {
            point: start.clone(),
            f_score: self.distance_score(start, end),
        });

        let mut came_from: HashMap<Self::Point, Self::Point> = HashMap::new();

        let mut g_score: HashMap<Self::Point, u64> = HashMap::new();
        g_score.insert(start.clone(), 0);

        while let Some(current) = open_set.pop() {
            let current = &current.point;
            if current == end {
                let mut point = current;
                let mut path = vec![point.clone()];
                while let Some(p) = came_from.get(point) {
                    point = p;
                    path.push(p.clone());
                }
                path.reverse();
                return Some(path);
            }

            let current_distance = *g_score.get(current).unwrap_or(&u64::MAX);

            for (d, neighbour) in &self.get_neighbours(current) {
                let distance = current_distance + d;
                let neighbour_distance = *g_score.get(neighbour).unwrap_or(&u64::MAX);

                if distance < neighbour_distance {
                    came_from.insert(neighbour.clone(), current.clone());
                    g_score.insert(neighbour.clone(), distance);
                    open_set.push(SortablePoint {
                        point: neighbour.clone(),
                        f_score: distance.add(self.distance_score(neighbour, end)),
                    });
                }
            }
        }

        None
    }
}

/// In the A* implementation, a priority queue (i.e. BinaryHeap) is used. This wrapper around the
/// points allows sorting on the f_score. Note that a descending sort is used.
struct SortablePoint<P> {
    point: P,
    f_score: u64,
}

impl<P> Eq for SortablePoint<P> {}

impl<P> PartialEq<Self> for SortablePoint<P> {
    fn eq(&self, other: &Self) -> bool {
        other.f_score.eq(&self.f_score)
    }
}

impl<P> PartialOrd<Self> for SortablePoint<P> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        other.f_score.partial_cmp(&self.f_score)
    }
}

impl<P> Ord for SortablePoint<P> {
    fn cmp(&self, other: &Self) -> Ordering {
        other.f_score.cmp(&self.f_score)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use crate::math::taxi_cab_2d;

    use super::*;

    #[test]
    fn test_find_shortest_path_without_obstacles() {
        // ############
        // #S.........#
        // #..........#
        // #..........#
        // #..........#
        // #.........E#
        // ############

        let nav = TestNav::new(10, 5, &[]);
        let path = nav.find_shortest_path(&(1, 1), &(10, 5));
        assert_eq!(path.map(|p| p.len()), Some(14));
    }

    #[test]
    fn test_find_shortest_with_obstacles() {
        // ############
        // #S#.....#..#
        // #.###.#...##
        // #.....#.#..#
        // #..#######.#
        // #.....#...E#
        // ############

        let obstacles = vec![
            (2, 1),
            (2, 2),
            (3, 2),
            (3, 4),
            (4, 2),
            (4, 4),
            (5, 4),
            (6, 2),
            (6, 3),
            (6, 4),
            (6, 5),
            (7, 4),
            (8, 1),
            (8, 3),
            (8, 4),
            (9, 4),
            (10, 2),
        ];
        let nav = TestNav::new(10, 5, &obstacles);
        let path = nav.find_shortest_path(&(1, 1), &(10, 5));
        assert_eq!(
            path,
            Some(vec![
                (1, 1),
                (1, 2),
                (1, 3),
                (2, 3),
                (3, 3),
                (4, 3),
                (5, 3),
                (5, 2),
                (5, 1),
                (6, 1),
                (7, 1),
                (7, 2),
                (8, 2),
                (9, 2),
                (9, 3),
                (10, 3),
                (10, 4),
                (10, 5),
            ])
        );
    }

    #[test]
    fn test_find_shortest_path_impossible() {
        // ############
        // #S.........#
        // #..........#
        // ############
        // #..........#
        // #.........E#
        // ############

        let obstacles = vec![
            (1, 3),
            (2, 3),
            (3, 3),
            (4, 3),
            (5, 3),
            (6, 3),
            (7, 3),
            (8, 3),
            (9, 3),
            (10, 3),
        ];
        let nav = TestNav::new(10, 10, &obstacles);
        let path = nav.find_shortest_path(&(1, 1), &(10, 5));
        assert_eq!(path, None);
    }

    struct TestNav {
        width: u64,
        height: u64,
        obstacles: HashSet<(u64, u64)>,
    }

    impl TestNav {
        fn new(width: u64, height: u64, obstacles: &[(u64, u64)]) -> TestNav {
            let mut obstacles_as_set = HashSet::new();
            for obstacle in obstacles {
                obstacles_as_set.insert(*obstacle);
            }
            TestNav {
                width,
                height,
                obstacles: obstacles_as_set,
            }
        }
    }

    impl Navigable for TestNav {
        type Point = (u64, u64);

        fn distance_score(&self, a: &Self::Point, b: &Self::Point) -> u64 {
            taxi_cab_2d(*a, *b)
        }

        fn get_neighbours(&self, (x, y): &Self::Point) -> Vec<(u64, Self::Point)> {
            vec![(*x - 1, *y), (*x + 1, *y), (*x, *y - 1), (*x, *y + 1)]
                .iter()
                .filter(|(x, y)| *x > 0 && *x <= self.width && *y > 0 && *y <= self.height)
                .filter(|p| !self.obstacles.contains(p))
                .copied()
                .map(|p| (1, p))
                .collect()
        }
    }
}