Skip to main content

grid_map/loc/square/
distance.rs

1use crate::Loc;
2
3impl Loc {
4    //! Distance
5
6    /// Gets the manhattan distance to the `other` location
7    pub fn manhattan(self, other: Loc) -> usize {
8        let dx: usize = self.x.abs_diff(other.x) as usize;
9        let dy: usize = self.y.abs_diff(other.y) as usize;
10        dx + dy
11    }
12}
13
14#[cfg(test)]
15mod tests {
16    use crate::Loc;
17
18    #[test]
19    fn manhattan() {
20        let test_cases: &[(Loc, Loc, usize)] = &[
21            (Loc::new(3, 4), Loc::new(3, 4), 0), // same
22            (Loc::new(0, 0), Loc::new(5, 0), 5), // axis
23            (Loc::new(0, 0), Loc::new(3, 4), 7), // diagonal
24        ];
25
26        for &(a, b, expected) in test_cases {
27            assert_eq!(a.manhattan(b), expected);
28            assert_eq!(b.manhattan(a), expected); // symmetric
29        }
30    }
31}