1
- use std:: fmt:: { Display , Formatter } ;
1
+ use std:: collections:: HashMap ;
2
+ use std:: fmt:: { Debug , Display , Formatter } ;
3
+ use std:: hash:: Hash ;
2
4
use std:: ops:: { Add , AddAssign , Sub , SubAssign } ;
3
5
use std:: str:: FromStr ;
4
6
use std:: sync:: OnceLock ;
5
7
8
+ use strum:: IntoEnumIterator ;
9
+
6
10
use crate :: captures:: CapturesHelper ;
7
11
use 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 ;
8
15
use crate :: regex:: Regex ;
9
16
10
17
/// A point in 2D space.
@@ -20,6 +27,26 @@ impl<T> Pt<T> {
20
27
}
21
28
}
22
29
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
+
23
50
impl < T , U , V > From < ( U , V ) > for Pt < T >
24
51
where
25
52
U : Into < T > ,
@@ -135,3 +162,24 @@ where
135
162
{
136
163
( a. x - b. x ) . abs ( ) + ( a. y - b. y ) . abs ( )
137
164
}
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