1- use std:: fmt:: { Display , Formatter } ;
1+ use std:: collections:: HashMap ;
2+ use std:: fmt:: { Debug , Display , Formatter } ;
3+ use std:: hash:: Hash ;
24use std:: ops:: { Add , AddAssign , Sub , SubAssign } ;
35use std:: str:: FromStr ;
46use std:: sync:: OnceLock ;
57
8+ use strum:: IntoEnumIterator ;
9+
610use crate :: captures:: CapturesHelper ;
711use crate :: num:: { zero, Signed , Zero } ;
12+ use crate :: positioning:: direction:: eight_points:: Direction8 ;
13+ use crate :: positioning:: direction:: four_points:: Direction4 ;
14+ use crate :: positioning:: direction:: MovementDirection ;
815use crate :: regex:: Regex ;
916
1017/// A point in 2D space.
@@ -20,6 +27,26 @@ impl<T> Pt<T> {
2027 }
2128}
2229
30+ impl < T > Pt < T >
31+ where
32+ Self : Add < Output = Self > + Copy ,
33+ Direction4 : MovementDirection < T > ,
34+ {
35+ pub fn four_neighbours ( self ) -> impl Iterator < Item = Self > {
36+ Direction4 :: iter ( ) . map ( move |dir| self + dir. displacement ( ) )
37+ }
38+ }
39+
40+ impl < T > Pt < T >
41+ where
42+ Self : Add < Output = Self > + Copy ,
43+ Direction8 : MovementDirection < T > ,
44+ {
45+ pub fn eight_neighbours ( self ) -> impl Iterator < Item = Self > {
46+ Direction8 :: iter ( ) . map ( move |dir| self + dir. displacement ( ) )
47+ }
48+ }
49+
2350impl < T , U , V > From < ( U , V ) > for Pt < T >
2451where
2552 U : Into < T > ,
@@ -135,3 +162,24 @@ where
135162{
136163 ( a. x - b. x ) . abs ( ) + ( a. y - b. y ) . abs ( )
137164}
165+
166+ /// Given a two-dimensional matrix of elements, returns a map of
167+ /// [`Pt`] associated with the element at that position in the matrix.
168+ pub fn matrix_to_map < M , R , T , PT > ( matrix : M ) -> HashMap < Pt < PT > , T >
169+ where
170+ M : IntoIterator < Item = R > ,
171+ R : IntoIterator < Item = T > ,
172+ PT : TryFrom < usize > ,
173+ <PT as TryFrom < usize > >:: Error : Debug ,
174+ Pt < PT > : Hash + Eq ,
175+ {
176+ matrix
177+ . into_iter ( )
178+ . enumerate ( )
179+ . flat_map ( |( y, row) | {
180+ row. into_iter ( )
181+ . enumerate ( )
182+ . map ( move |( x, t) | ( Pt :: new ( x. try_into ( ) . unwrap ( ) , y. try_into ( ) . unwrap ( ) ) , t) )
183+ } )
184+ . collect ( )
185+ }
0 commit comments