1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#![no_std]
mod test;
#[derive(Clone, Copy)]
pub struct Data(u32, u16);
impl Data {
pub fn new(x: u32) -> Option<Self> {
let bits = (0..6)
.map(|i| 1_u16 << (x >> (4 * i) & 0xF))
.fold(0, core::ops::BitOr::bitor);
match bits.count_ones() {
6 => Some(Self(x, bits)),
_ => None,
}
}
pub const fn get(self) -> u32 {
self.0
}
pub const fn compare(self, other: Self) -> Result {
let b = self.0 ^ !other.0;
let b = b & b >> 1;
Result(((b & b >> 2 & 0x11_1111).count_ones() * 8 + (self.1 & other.1).count_ones()) as u8)
}
}
#[derive(Copy, Clone, PartialEq)]
pub struct Result(u8);
impl Eq for Result {}
impl core::fmt::Display for Result {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{} bulls, {} cows", self.get().0, self.get().1)
}
}
impl Result {
pub const VALUES: [Self; 27] = [
Self(0),
Self(1),
Self(2),
Self(3),
Self(4),
Self(5),
Self(6),
Self(9),
Self(10),
Self(11),
Self(12),
Self(13),
Self(14),
Self(18),
Self(19),
Self(20),
Self(21),
Self(22),
Self(27),
Self(28),
Self(29),
Self(30),
Self(36),
Self(37),
Self(38),
Self(45),
Self(54),
];
pub fn new(bulls: u8, cows: u8) -> Option<Self> {
if bulls.saturating_add(cows) <= 6 && (bulls != 5 || cows != 1) {
Some(Self(bulls * 9 + cows))
} else {
None
}
}
pub const fn get(self) -> (u8, u8) {
(self.0 >> 3, (self.0 & 7) - (self.0 >> 3))
}
}
pub struct ResultArray<T>([T; 55]);
impl<T> Default for ResultArray<T>
where
T: Default + Copy,
{
fn default() -> Self {
Self([T::default(); 55])
}
}
impl<T> core::ops::Index<Result> for ResultArray<T> {
type Output = T;
fn index(&self, r: Result) -> &Self::Output {
unsafe { self.0.get_unchecked(r.0 as usize) }
}
}
impl<T> core::ops::IndexMut<Result> for ResultArray<T> {
fn index_mut(&mut self, r: Result) -> &mut Self::Output {
unsafe { self.0.get_unchecked_mut(r.0 as usize) }
}
}