optimization_tools/sudoku/
cell_index.rs1use super::*;
2use deterministic_rand::{ Rng, distributions::{ Distribution, Standard } };
3#[ derive( Default, Debug, Clone, Copy, PartialEq, Eq ) ]
6pub struct CellFlatIndex( usize );
7
8impl CellFlatIndex
9{
10 #[ inline ]
11 pub fn unwrap( self ) -> usize
12 {
13 self.0
14 }
15}
16
17impl From< usize > for CellFlatIndex
18{
19 #[ inline ]
20 fn from( src : usize ) -> Self
21 {
22 let a = src.into();
23 debug_assert!( a < 81 );
24 Self ( a )
25 }
26}
27
28impl From< CellIndex > for CellFlatIndex
29{
30 #[ inline ]
31 fn from( src : CellIndex ) -> Self
32 {
33 Self( src.0 as usize + src.1 as usize * 9 )
34 }
35}
36
37impl From< CellFlatIndex > for usize
38{
39 #[ inline ]
40 fn from( src : CellFlatIndex ) -> Self
41 {
42 src.0
43 }
44}
45
46#[ derive( Default, Debug, Clone, Copy, PartialEq, Eq ) ]
47pub struct CellIndex( u8, u8 );
48
49impl CellIndex
50{
51 pub fn random_in_block( block : BlockIndex, hrng : Hrng ) -> Self
53 {
54 let rng_ref = hrng.rng_ref();
55 let mut rng = rng_ref.lock().unwrap();
56
57 let intervals = block.cells_intervals();
58
59 ( rng.gen_range( intervals.0 ) as u8, rng.gen_range( intervals.1 ) as u8 ).into()
60 }
61
62 #[ inline ]
63 pub fn col( &self ) -> u8
64 {
65 self.0
66 }
67 #[ inline ]
68 pub fn row( &self ) -> u8
69 {
70 self.1
71 }
72}
73
74impl Distribution< CellIndex > for Standard
75{
76 fn sample< R : Rng + ?Sized >( &self, rng : &mut R) -> CellIndex
77 {
78 ( rng.gen_range( 0..=8 ), rng.gen_range( 0..=8 ) ).into()
79 }
80}
81
82impl< T > From< ( T, T ) > for CellIndex
83where
84 T : Into< u8 >,
85{
86 fn from( src : ( T, T ) ) -> Self
87 {
88 let a = src.0.into();
89 let b = src.1.into();
90 debug_assert!( a <= 8 );
91 debug_assert!( b <= 8 );
92 Self ( a, b )
93 }
94}
95
96impl From< CellFlatIndex > for CellIndex
97{
98 #[ inline ]
99 fn from( src : CellFlatIndex ) -> Self
100 {
101 Self( src.0 as u8 % 9, src.0 as u8 / 9 )
102 }
103}
104
105impl From< CellIndex > for usize
106{
107 #[ inline ]
108 fn from( src : CellIndex ) -> Self
109 {
110 let index : CellFlatIndex = src.into();
111 index.into()
112 }
113}