|
| 1 | +#![expect(clippy::cast_possible_wrap, clippy::cast_possible_truncation, clippy::cast_sign_loss)] |
| 2 | + |
| 3 | +use std::iter::Sum; |
| 4 | +use std::str::FromStr; |
| 5 | + |
| 6 | +use pathfinding::matrix::Matrix; |
| 7 | + |
| 8 | +use crate::coords2d::Coords2D; |
| 9 | +use crate::parsing::parse_matrix; |
| 10 | + |
| 11 | +pub type Coords = Coords2D<i32>; |
| 12 | + |
| 13 | +pub trait Grid2D<T> { |
| 14 | + fn map_by_coords<F, U>(&self, f: F) -> MatrixGrid2D<U> |
| 15 | + where |
| 16 | + F: Fn(Coords) -> U; |
| 17 | + |
| 18 | + fn count<F>(&self, f: F) -> usize |
| 19 | + where |
| 20 | + F: Fn(Coords, &T) -> bool; |
| 21 | + |
| 22 | + fn get(&self, coords: Coords) -> Option<&T>; |
| 23 | + |
| 24 | + fn get_or_else(&self, coords: Coords, default: T) -> T |
| 25 | + where |
| 26 | + T: Clone, |
| 27 | + { |
| 28 | + self.get(coords).cloned().unwrap_or(default) |
| 29 | + } |
| 30 | + |
| 31 | + fn sum(&self) -> T |
| 32 | + where |
| 33 | + T: Sum + Clone; |
| 34 | +} |
| 35 | + |
| 36 | +pub struct MatrixGrid2D<T> { |
| 37 | + data: Matrix<T>, |
| 38 | +} |
| 39 | + |
| 40 | +impl From<(usize, usize)> for Coords { |
| 41 | + fn from(value: (usize, usize)) -> Self { |
| 42 | + let (x, y) = value; |
| 43 | + Coords::new(x as i32, y as i32) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl From<Coords> for (usize, usize) { |
| 48 | + fn from(coords: Coords) -> Self { |
| 49 | + (coords.x as usize, coords.y as usize) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl<T> Grid2D<T> for MatrixGrid2D<T> { |
| 54 | + fn map_by_coords<F, U>(&self, f: F) -> MatrixGrid2D<U> |
| 55 | + where |
| 56 | + F: Fn(Coords) -> U, |
| 57 | + { |
| 58 | + let new_data = self |
| 59 | + .data |
| 60 | + .keys() |
| 61 | + .map(|coords| f(Coords::from(coords))) |
| 62 | + .collect(); |
| 63 | + MatrixGrid2D { |
| 64 | + data: Matrix::from_vec(self.data.rows, self.data.columns, new_data).unwrap(), |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + fn count<F>(&self, f: F) -> usize |
| 69 | + where |
| 70 | + F: Fn(Coords, &T) -> bool, |
| 71 | + { |
| 72 | + self.data |
| 73 | + .keys() |
| 74 | + .filter(|coords| f(Coords::from(*coords), &self.data[*coords])) |
| 75 | + .count() |
| 76 | + } |
| 77 | + |
| 78 | + fn get(&self, coords: Coords) -> Option<&T> { |
| 79 | + self.data.get(coords.into()) |
| 80 | + } |
| 81 | + |
| 82 | + fn sum(&self) -> T |
| 83 | + where |
| 84 | + T: Sum + Clone, |
| 85 | + { |
| 86 | + self.data.values().cloned().sum() |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +impl FromStr for MatrixGrid2D<char> { |
| 91 | + type Err = String; |
| 92 | + |
| 93 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 94 | + parse_matrix(s, Ok).map(|data| MatrixGrid2D { data }) |
| 95 | + } |
| 96 | +} |
0 commit comments