1- // source: https://github.com/maneatingape/advent-of-code-rust/blob/109bf05f8cb5026d97af42b42ea3985afe600dfb /src/util/grid.rs
1+ // source: https://github.com/maneatingape/advent-of-code-rust/blob/177fc32fbfc3ce814b26b10263b2cc081e121b50 /src/util/grid.rs
22
33//! Fast 2 dimensional Grid backed by a single `vec`. This module is designed to work with [`Point`].
44//!
1919//! ```
2020//!
2121//! A convenience [`parse`] method creates a `Grid` directly from a 2 dimenionsal set of
22- //! ASCII characters, a common occurence in Advent of Code inputs. The [`default_copy `] function
22+ //! ASCII characters, a common occurence in Advent of Code inputs. The [`same_size_with `] function
2323//! creates a grid of the same size, that can be used for in BFS algorithms for tracking visited
2424//! location or for tracking cost in Djikstra.
2525//!
26- //! [`Point`]: crate::util ::point
26+ //! [`Point`]: crate::maneatingape ::point
2727//! [`parse`]: Grid::parse
28- //! [`default_copy `]: Grid::default_copy
28+ //! [`same_size_with `]: Grid::same_size_with
2929use crate :: maneatingape:: point:: * ;
3030use std:: ops:: { Index , IndexMut } ;
3131
@@ -37,6 +37,7 @@ pub struct Grid<T> {
3737}
3838
3939impl Grid < u8 > {
40+ #[ inline]
4041 pub fn parse ( input : & str ) -> Self {
4142 let raw: Vec < _ > = input. lines ( ) . map ( str:: as_bytes) . collect ( ) ;
4243 let width = raw[ 0 ] . len ( ) as i32 ;
@@ -49,9 +50,21 @@ impl Grid<u8> {
4950 bytes,
5051 }
5152 }
53+
54+ pub fn print ( & self ) {
55+ for y in 0 ..self . height {
56+ for x in 0 ..self . width {
57+ let point = Point :: new ( x, y) ;
58+ print ! ( "{}" , self [ point] as char ) ;
59+ }
60+ println ! ( ) ;
61+ }
62+ println ! ( ) ;
63+ }
5264}
5365
5466impl < T : Copy + PartialEq > Grid < T > {
67+ #[ inline]
5568 pub fn find ( & self , needle : T ) -> Option < Point > {
5669 let to_point = |index| {
5770 let x = ( index as i32 ) % self . width ;
@@ -73,11 +86,12 @@ impl<T: Copy> Grid<T> {
7386}
7487
7588impl < T > Grid < T > {
76- pub fn default_copy < U : Default + Copy > ( & self ) -> Grid < U > {
89+ #[ inline]
90+ pub fn same_size_with < U : Copy > ( & self , value : U ) -> Grid < U > {
7791 Grid {
7892 width : self . width ,
7993 height : self . height ,
80- bytes : vec ! [ U :: default ( ) ; ( self . width * self . height) as usize ] ,
94+ bytes : vec ! [ value ; ( self . width * self . height) as usize ] ,
8195 }
8296 }
8397
0 commit comments