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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#![warn(missing_docs)]
mod field;
mod brute_force;
mod detect_uniques;
mod parse_error;
mod project_lines;
mod project_numbers;
use self::field::Field;
use brute_force::brute_force;
use detect_uniques::detect_uniques;
pub use self::parse_error::ParseError;
use project_lines::project_lines;
use project_numbers::project_numbers;
use std::fmt::{self, Display};
use std::io::BufRead;
use std::iter;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Sudoku {
fields: Vec<Vec<Field>>
}
impl Sudoku {
pub fn from_str(s: &str) -> Result<Sudoku, ParseError> {
Sudoku::from_reader(s.as_bytes())
}
pub fn from_reader<T: BufRead>(reader: T) -> Result<Sudoku, ParseError> {
let column = vec![Field::new(); 9];
let mut rows = vec![column; 9];
let mut line_nr = 0;
for line in reader.lines().take(9) {
line_nr += 1;
let line = line.ok().unwrap_or("".to_string());
let numbers: Vec<char> = line.trim_right().chars().collect();
if numbers.len() != 9 {
return Err(ParseError::InvalidLineLength(line_nr));
}
for x in 0..9 {;
match numbers[x].to_digit(10) {
Some(i) if i != 0 => rows[x][line_nr as usize - 1].set_number(i as u8),
None if numbers[x] == '_' => (),
_ => return Err(ParseError::InvalidNumber(line_nr, numbers[x]))
}
}
}
if line_nr < 9 {
Err(ParseError::NotEnoughRows)
} else {
Ok(Sudoku { fields: rows })
}
}
pub fn solve(&mut self) {
self.fast_solve();
if !self.is_solved() {
self.brute_force_solve();
}
}
pub fn fast_solve(&mut self) {
let mut progress = true;
while progress {
progress = project_numbers(self)
|| detect_uniques(self)
|| project_lines(self);
}
}
pub fn brute_force_solve(&mut self) {
brute_force(self);
}
pub fn is_solved(&self) -> bool {
self.fields.iter().all(|column| column.iter().all(|field|
field.number_found())
)
}
fn get_corner(x: u8, y: u8) -> (u8, u8) {
assert!(x < 9 && y < 9);
((x / 3) * 3, (y / 3) * 3)
}
fn get(&self, x: u8, y: u8) -> &Field {
&self.fields[x as usize][y as usize]
}
fn get_mut(&mut self, x: u8, y: u8) -> &mut Field {
&mut self.fields[x as usize][y as usize]
}
fn is_valid(&self, x: u8, y: u8) -> bool {
let number = self.get(x, y).get_number();
for i in 0..9 {
if i != x
&& self.get(i, y).number_found()
&& self.get(i, y).get_number() == number {
return false;
}
}
for i in 0..9 {
if i != y
&& self.get(x, i).number_found()
&& self.get(x, i).get_number() == number {
return false;
}
}
let (corner_x, corner_y) = Sudoku::get_corner(x, y);
for off_x in 0..3 {
for off_y in 0..3 {
if corner_x + off_x != x || corner_y + off_y != y {
if self.get(corner_x + off_x, corner_y + off_y).number_found()
&& self.get(corner_x + off_x, corner_y + off_y).get_number() == number {
return false;
}
}
}
}
true
}
}
impl Display for Sudoku {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..9 {
if y == 3 || y == 6 {
try!(write!(f, "{}\n", iter::repeat("-").take(12).collect::<String>()));
}
for x in 0..9 {
if x == 3 || x == 6 {
try!(write!(f, "|"));
}
if self.get(x, y).number_found() {
try!(write!(f, "{}", self.get(x, y).get_number()))
} else {
try!(write!(f, " "))
}
}
try!(write!(f, "\n"));
}
Ok(())
}
}
#[test]
fn solve_1() {
let sudoku_str =
"___2___63
3____54_1
__1__398_
_______9_
___538___
_3_______
_263__5__
5_37____8
47___1___";
let mut sudoku = Sudoku::from_str(sudoku_str).unwrap();
sudoku.solve();
println!("{}", sudoku);
}
#[test]
#[should_panic]
fn wrong_format_1() {
let sudoku_str =
"___2___63
3____54_1
__1__398_
_______9_
___538___
_3_______
_263__5__
5_37____8";
let mut sudoku = Sudoku::from_str(sudoku_str).unwrap();
}