Day 10 part 2

This commit is contained in:
2023-12-26 17:03:46 +01:00
parent a6a9584a51
commit 01ba0f6662
2 changed files with 81 additions and 15 deletions
+26 -3
View File
@@ -1,7 +1,7 @@
//! A large number of logical games, by virtue of existing on paper, use 2-dimensional structures.
//! This module implement packed matrices, without the overhead of supporting multiple dimensions.
use std::ops::{Index, IndexMut};
use std::{ops::{Index, IndexMut}, fmt::Display};
use thiserror::Error;
@@ -57,6 +57,10 @@ impl <T> Matrix<T> {
(0..h).flat_map(move |x| (0..w).map(move |y| (x,y)))
}
pub fn elems(&self) -> impl Iterator<Item=&T> {
self.vec.iter()
}
/// Lists all the neighbors of the given location, truncating at the edge.
pub fn neighbors(&self, pos: (usize, usize)) -> Vec<(usize,usize)> {
let (x,y) = pos;
@@ -92,6 +96,25 @@ impl <T> Matrix<T> {
}
impl <T: Clone> Matrix<T> {
pub fn constant(item: T, shape: (usize, usize)) -> Self {
let data = vec![item; shape.0 * shape.1];
Matrix::new(data, shape).unwrap()
}
}
impl <T: Display> Display for Matrix<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for l in self.lines() {
for e in l {
write!(f, "{}", e)?;
}
writeln!(f)?;
}
Ok(())
}
}
impl <T> Index<usize> for Matrix<T> {
type Output = [T];
@@ -109,7 +132,7 @@ impl <T> IndexMut<usize> for Matrix<T> {
macro_rules! umat {
[$e:expr; $shape:expr] => {
$crate::util::matrix::Matrix::new(vec![$e; $shape.0 * $shape.1], $shape).unwrap()
$crate::matrix::Matrix::new(vec![$e; $shape.0 * $shape.1], $shape).unwrap()
};
}
pub(crate) use umat;
@@ -134,7 +157,7 @@ pub(crate) use mat;
#[cfg(test)]
mod test {
use crate::util::matrix::ShapeError;
use crate::matrix::ShapeError;
use super::Matrix;