sudoku.rs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. // pub mod group;
  2. use crate::bits::*;
  3. use crate::group::*;
  4. use strum::IntoEnumIterator;
  5. use std::string::String;
  6. extern crate rand_chacha;
  7. use rand::seq::SliceRandom;
  8. use rand_chacha::rand_core::SeedableRng;
  9. use rand_chacha::ChaCha20Rng;
  10. // For custom error
  11. use std::error;
  12. use std::fmt;
  13. #[derive(Debug, Clone)]
  14. struct GameLoadError {
  15. message: String,
  16. }
  17. impl fmt::Display for GameLoadError {
  18. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  19. write!(f, "Game load error: {}", self.message)
  20. }
  21. }
  22. impl error::Error for GameLoadError {}
  23. // const DEBUG_OUTPUT: bool = false;
  24. // Vec doesn't implement Copy ...
  25. #[derive(Debug, Clone, Eq, PartialEq)]
  26. pub struct AnyBoard {
  27. pub size: u8,
  28. pub width: u8,
  29. pub max_index: usize,
  30. pub board: Vec<u8>,
  31. }
  32. impl AnyBoard {
  33. pub fn new(board_size: u8) -> Self {
  34. if (board_size < 3) || (board_size > 5) {
  35. panic!("Board size must be 3-5.");
  36. }
  37. let n = board_size as usize;
  38. let s = AnyBoard {
  39. size: board_size,
  40. width: board_size * board_size,
  41. max_index: n * n * n * n,
  42. board: vec![0; n * n * n * n],
  43. };
  44. s
  45. }
  46. /// Clear out the board
  47. pub fn clear(&mut self) {
  48. self.board.fill(0);
  49. }
  50. pub fn copy(&mut self, copy_from: &Self) {
  51. debug_assert!(
  52. self.size == copy_from.size,
  53. "Can't copy size {} into size {}",
  54. copy_from.size,
  55. self.size
  56. );
  57. for i in 0..self.max_index {
  58. self.board[i] = copy_from.board[i];
  59. }
  60. }
  61. /// Calculate index position of (x,y)
  62. #[inline]
  63. pub fn pos(&self, x: u8, y: u8) -> usize {
  64. debug_assert!(
  65. x < self.width && y < self.width,
  66. "Expected ({}, {}) < {}",
  67. x,
  68. y,
  69. self.width
  70. );
  71. x as usize + y as usize * self.width as usize
  72. }
  73. /// Return (x,y) position for given index.
  74. #[inline]
  75. pub fn xy(&self, idx: usize) -> (u8, u8) {
  76. (
  77. (idx % self.width as usize) as u8,
  78. (idx / self.width as usize) as u8,
  79. )
  80. }
  81. /// Set a position in the board with a value
  82. pub fn set(&mut self, x: u8, y: u8, value: u8) {
  83. debug_assert!(
  84. x < self.width && y < self.width,
  85. "Expected ({}, {}) < {}",
  86. x,
  87. y,
  88. self.width
  89. );
  90. debug_assert!(
  91. value <= self.width,
  92. "Expected value for ({},{}) = {} < {}",
  93. x,
  94. y,
  95. value,
  96. self.width
  97. );
  98. let index = self.pos(x, y);
  99. assert!(index <= self.board.capacity());
  100. self.board[index] = value;
  101. }
  102. /// Get value at position (x,y)
  103. pub fn get(&self, x: u8, y: u8) -> u8 {
  104. debug_assert!(
  105. x < self.width && y < self.width,
  106. "Expected ({}, {}) < {}",
  107. x,
  108. y,
  109. self.width
  110. );
  111. let index = self.pos(x, y);
  112. assert!(index <= self.board.capacity());
  113. self.board[index]
  114. }
  115. /// Load from ksudoku file
  116. /// - uses load_from_tld
  117. pub fn load_ksudoku(&mut self, s: &str) -> Result<(), Box<dyn error::Error>> {
  118. self.load_from_tld('b', '_', s)
  119. }
  120. pub fn save_ksudoku(&self) -> String {
  121. self.save_to_tld('b', '_')
  122. }
  123. /// Load puzzle from string (top,left) going down.
  124. pub fn load_from_tld(
  125. &mut self,
  126. start_ch: char,
  127. blank: char,
  128. s: &str,
  129. ) -> Result<(), Box<dyn error::Error>> {
  130. self.clear();
  131. let mut x: u8 = 0;
  132. let mut y: u8 = 0;
  133. if s.len() != self.max_index {
  134. // self.size * self.size*self.size*self.size {
  135. return Err(Box::new(GameLoadError {
  136. message: format!(
  137. "String ({}) exceeds expected length {}.",
  138. s.len(),
  139. self.width
  140. ),
  141. }));
  142. }
  143. for ch in s.chars() {
  144. if ch != blank {
  145. let value = (ch as u8 - start_ch as u8) + 1;
  146. if value == 0 || value > self.width {
  147. return Err(Box::new(GameLoadError {
  148. message: format!(
  149. "String symbol ({}) represents value {}, expecting 1 to {}.",
  150. ch, value, self.width
  151. ),
  152. }));
  153. }
  154. self.set(x, y, value);
  155. }
  156. y += 1;
  157. if y >= self.width {
  158. y = 0;
  159. x += 1;
  160. }
  161. }
  162. Ok(())
  163. }
  164. /// Save puzzle to a string (top,left) going down.
  165. pub fn save_to_tld(&self, start_ch: char, blank: char) -> String {
  166. let mut result = String::new();
  167. result.reserve(self.max_index);
  168. let start_ch = (start_ch as u8 - 1) as char;
  169. let mut x: u8 = 0;
  170. let mut y: u8 = 0;
  171. for _i in 0..self.max_index {
  172. let value = self.get(x, y);
  173. if value == 0 {
  174. result.push(blank);
  175. } else {
  176. result.push((start_ch as u8 + value) as char);
  177. }
  178. y += 1;
  179. if y >= self.width {
  180. y = 0;
  181. x += 1;
  182. }
  183. }
  184. result
  185. }
  186. /// Load puzzle from string (top,left) going right.
  187. pub fn load_from_tlr(
  188. &mut self,
  189. start_ch: char,
  190. blank: char,
  191. s: &str,
  192. ) -> Result<(), Box<dyn error::Error>> {
  193. self.clear();
  194. if s.len() != self.max_index {
  195. // self.size * self.size*self.size*self.size {
  196. return Err(Box::new(GameLoadError {
  197. message: format!(
  198. "String exceeds ({}) expected length {}.",
  199. s.len(),
  200. self.width
  201. ),
  202. }));
  203. }
  204. let mut i: usize = 0;
  205. for ch in s.chars() {
  206. if ch != blank {
  207. let value = (ch as u8 - start_ch as u8) + 1;
  208. if value == 0 || value > self.width {
  209. return Err(Box::new(GameLoadError {
  210. message: format!(
  211. "String symbol ({}) represents value {}, expecting 1 to {}.",
  212. ch, value, self.width
  213. ),
  214. }));
  215. }
  216. self.board[i] = value;
  217. i += 1;
  218. }
  219. }
  220. Ok(())
  221. }
  222. /// Save puzzle to a string (top,left) going right.
  223. pub fn save_to_tlr(&self, start_ch: char, blank: char) -> String {
  224. let mut result = String::new();
  225. result.reserve(self.max_index);
  226. let start_ch = (start_ch as u8 - 1) as char;
  227. for i in 0..self.max_index {
  228. let value = self.board[i];
  229. if value == 0 {
  230. result.push(blank);
  231. } else {
  232. result.push((start_ch as u8 + value) as char);
  233. }
  234. }
  235. result
  236. }
  237. /// Display board using unicode box characters.
  238. pub fn display(&self) {
  239. let line = "═".repeat(self.size as usize);
  240. let alpha_display = self.width >= 10;
  241. // println!("╔{}╦{}╦{}╗", line, line, line);
  242. // Top
  243. for i in 0..self.size {
  244. if i == 0 {
  245. print!("╔{}", line);
  246. } else {
  247. print!("╦{}", line);
  248. }
  249. }
  250. println!("╗");
  251. for y in 0..self.width {
  252. print!("║");
  253. for x in 0..self.width {
  254. let value = self.get(x, y);
  255. if value == 0 {
  256. print!(" ");
  257. } else {
  258. if alpha_display {
  259. print!("{}", (value - 1 + 'A' as u8) as char);
  260. } else {
  261. print!("{}", value);
  262. }
  263. }
  264. if x % self.size == self.size - 1 {
  265. print!("║");
  266. }
  267. }
  268. println!("");
  269. if y % self.size == self.size - 1 {
  270. if y + 1 == self.width {
  271. // Bottom
  272. for i in 0..self.size {
  273. if i == 0 {
  274. print!("╚{}", line);
  275. } else {
  276. print!("╩{}", line);
  277. }
  278. }
  279. println!("╝");
  280. // println("╚═══╩═══╩═══╝");
  281. } else {
  282. // Middle
  283. for i in 0..self.size {
  284. if i == 0 {
  285. print!("╠{}", line);
  286. } else {
  287. print!("╬{}", line);
  288. }
  289. }
  290. println!("╣");
  291. // println("╠═══╬═══╬═══╣");
  292. }
  293. }
  294. }
  295. }
  296. /// Output board as strings.
  297. /// - Uses 1-9 (for 9x9), and A-? for others.
  298. /// - Used by tests to confirm the board is what we think it should be.
  299. pub fn to_strings(&self) -> Vec<String> {
  300. let mut result = Vec::<String>::new();
  301. let alpha_display = self.width >= 10;
  302. for y in 0..self.width {
  303. let mut line = String::new();
  304. line.reserve(self.width as usize);
  305. for x in 0..self.width {
  306. let value = self.get(x, y);
  307. if value == 0 {
  308. line.push(' ');
  309. } else {
  310. if alpha_display {
  311. line.push((value - 1 + 'A' as u8) as char);
  312. } else {
  313. line.push((value + '0' as u8) as char);
  314. }
  315. }
  316. }
  317. result.push(line);
  318. }
  319. result
  320. }
  321. /// Is the puzzle completed?
  322. /// Have all of the locations been filled with a value?
  323. /// - This does not validate that it is a correct puzzle.
  324. /// It doesn't check for duplicate digits (for example).
  325. pub fn complete(&self) -> bool {
  326. for i in 0..self.max_index {
  327. if self.board[i] == 0 {
  328. return false;
  329. }
  330. }
  331. true
  332. }
  333. /// Solve by brute force
  334. /// - Returns up to max # of solutions.
  335. /// - Returns total solutions found, and vector of boards (up to max).
  336. /// - Uses brute_force (recursive function) to solve.
  337. pub fn brute_force_solver(&self, max: u16) -> (u16, Vec<AnyBoard>) {
  338. let mut workset = self.clone();
  339. let mut total_solutions: u16 = 0;
  340. let mut solutions: Vec<AnyBoard> = Vec::new();
  341. let groups = AnyGroup::new(workset.size);
  342. solutions.reserve(max as usize);
  343. workset.brute_force(&mut total_solutions, &mut solutions, &groups);
  344. (total_solutions, solutions)
  345. }
  346. /// Recursive brute force solver.
  347. fn brute_force(
  348. &mut self,
  349. total_solutions: &mut u16,
  350. solutions: &mut Vec<AnyBoard>,
  351. groups: &AnyGroup,
  352. ) -> bool {
  353. for idx in 0..self.max_index {
  354. if self.board[idx] == 0 {
  355. // Blank found
  356. let (x, y) = self.xy(idx);
  357. // println!("Blank ({},{})", x, y);
  358. 'outer: for value in 1..=self.width {
  359. // Check if it fits in the puzzle via group.
  360. for clear in groups.row(y) {
  361. if self.board[*clear] == value {
  362. continue 'outer;
  363. }
  364. }
  365. for clear in groups.column(x) {
  366. if self.board[*clear] == value {
  367. continue 'outer;
  368. }
  369. }
  370. for clear in groups.cell(groups.which_cell(x, y)) {
  371. if self.board[*clear] == value {
  372. continue 'outer;
  373. }
  374. }
  375. // Ok, this is possible move.
  376. self.board[idx] = value;
  377. // println!("Try ({},{}) = {}", x, y, value);
  378. // self.display();
  379. if self.complete() {
  380. if *total_solutions < solutions.capacity() as u16 {
  381. solutions.push(self.clone());
  382. }
  383. *total_solutions += 1;
  384. break;
  385. } else {
  386. if self.brute_force(total_solutions, solutions, groups) {
  387. return true;
  388. }
  389. }
  390. }
  391. // We failed to place a value -- return failure.
  392. // println!("rewind");
  393. self.board[idx] = 0;
  394. return false;
  395. }
  396. }
  397. false
  398. }
  399. }
  400. // Need to use u32, so 5*5=25, 25 bits can be accessed.
  401. // u16 is fine for 3*3=9.
  402. #[derive(Debug, Clone)]
  403. pub struct AnyPossible {
  404. pub size: u8,
  405. pub width: u8,
  406. pub max_index: usize,
  407. pub possible: Vec<GenBits<u32>>,
  408. }
  409. impl AnyPossible {
  410. pub fn new(board_size: u8) -> Self {
  411. let mut initial = GenBits::<u32>(0);
  412. let width = board_size * board_size;
  413. initial.set_bits(0..width);
  414. Self {
  415. size: board_size,
  416. width: width,
  417. max_index: width as usize * width as usize,
  418. possible: vec![initial; width as usize * width as usize],
  419. }
  420. }
  421. pub fn clear(&mut self) {
  422. let mut initial = GenBits::<u32>(0);
  423. // let width = self.size * self.size;
  424. initial.set_bits(0..self.width);
  425. self.possible.fill(initial);
  426. // self.possible = vec![initial; self.max_index];
  427. // width as usize * width as usize];
  428. }
  429. pub fn copy(&mut self, copy_from: &Self) {
  430. debug_assert!(
  431. self.size == copy_from.size,
  432. "Can't copy size {} into size {}",
  433. copy_from.size,
  434. self.size
  435. );
  436. for i in 0..self.max_index {
  437. self.possible[i] = copy_from.possible[i];
  438. }
  439. }
  440. // NOTE: values range from 1..width. Bits range from 0..width-1
  441. #[inline]
  442. pub fn set(&mut self, index: usize, value: usize, state: bool) {
  443. debug_assert!(
  444. index < self.max_index,
  445. "Index {} >= {}",
  446. index,
  447. self.max_index
  448. );
  449. self.possible[index].set(value - 1, state);
  450. }
  451. #[inline]
  452. pub fn get(&self, index: usize, value: usize) -> bool {
  453. debug_assert!(
  454. index < self.max_index,
  455. "Index {} >= {}",
  456. index,
  457. self.max_index
  458. );
  459. self.possible[index].get(value - 1)
  460. }
  461. #[inline]
  462. pub fn pos(&self, x: u8, y: u8) -> usize {
  463. debug_assert!(
  464. x < self.width && y < self.width,
  465. "Expected ({},{}) < {}",
  466. x,
  467. y,
  468. self.width
  469. );
  470. x as usize + y as usize * self.width as usize
  471. }
  472. /// Return (x,y) position for given index.
  473. #[inline]
  474. pub fn xy(&self, idx: usize) -> (u8, u8) {
  475. debug_assert!(idx < self.max_index, "Index {} >= {}", idx, self.max_index);
  476. (
  477. (idx % self.width as usize) as u8,
  478. (idx / self.width as usize) as u8,
  479. )
  480. }
  481. /// Format all possible, finding max length.
  482. /// - Return vec<string> of each item formatted.
  483. /// - Return max length.
  484. pub fn pos_max(&self) -> (Vec<String>, usize) {
  485. let mut pos = Vec::<String>::new();
  486. pos.reserve(self.max_index);
  487. let mut max: usize = 0;
  488. for idx in 0..self.max_index {
  489. let s = self.possible[idx].display();
  490. if max < s.len() {
  491. max = s.len();
  492. }
  493. pos.push(s);
  494. }
  495. (pos, max)
  496. }
  497. /// Display Possible
  498. /// - Collect all of the possibles, with max length.
  499. /// - Display formatted (using max length).
  500. pub fn display(&self) {
  501. let pos_info = self.pos_max();
  502. for y in 0..self.width {
  503. for x in 0..self.width {
  504. let idx = self.pos(x, y);
  505. print!("({},{}):{:3$} ", x + 1, y + 1, pos_info.0[idx], pos_info.1);
  506. }
  507. println!("");
  508. }
  509. }
  510. }
  511. /*
  512. An idea I have for AnySolver is to store the AnyPossible as
  513. sections. row/column/cell.
  514. I think this would better allow me to judge how hard the puzzle
  515. is. If it can be solved by looking at just one section --
  516. that would be one level. If it takes 2, another level. All 3,
  517. yet another. I think that's how I mentally judge the puzzles.
  518. "Not all hard puzzles are hard."
  519. */
  520. #[derive(Debug, Clone)]
  521. pub struct AnySolver {
  522. pub board: AnyBoard,
  523. pub possible: AnyPossible,
  524. pub group: AnyGroup,
  525. }
  526. impl AnySolver {
  527. /// Construct new solver from given board size. (3,4,5)
  528. pub fn new(board_size: u8) -> Self {
  529. let mut s = Self {
  530. board: AnyBoard::new(board_size),
  531. possible: AnyPossible::new(board_size),
  532. group: AnyGroup::new(board_size),
  533. };
  534. s.reset_possible();
  535. s
  536. }
  537. /// Construct new solver from given board.
  538. pub fn new_from(initial_board: &AnyBoard) -> Self {
  539. let mut s = AnySolver {
  540. board: initial_board.clone(),
  541. possible: AnyPossible::new(initial_board.size),
  542. group: AnyGroup::new(initial_board.size),
  543. };
  544. s.reset_possible();
  545. s
  546. }
  547. /// Clear out board and possible.
  548. /// - group is ok, unless they change the board size.
  549. pub fn clear(&mut self) {
  550. let board_size: u8 = self.board.size;
  551. self.board = AnyBoard::new(board_size);
  552. self.possible = AnyPossible::new(board_size);
  553. self.reset_possible();
  554. }
  555. /// Process a move
  556. /// - Remove value from rows, columns, and cells.
  557. /// - Clear possibles from (x,y) position, it's filled.
  558. pub fn process_move(&mut self, x: u8, y: u8, value: u8) {
  559. debug_assert!(
  560. x <= self.board.width && y <= self.board.width,
  561. "Expected ({}, {}) <= {}",
  562. x,
  563. y,
  564. self.board.width
  565. );
  566. debug_assert!(
  567. value <= self.board.width,
  568. "Expected value {} < {}",
  569. value,
  570. self.board.width
  571. );
  572. let mut g = self.group.row(y);
  573. let val: usize = value as usize;
  574. for g in g {
  575. self.possible.set(*g, val, false);
  576. }
  577. g = self.group.column(x);
  578. for g in g {
  579. self.possible.set(*g, val, false);
  580. }
  581. g = self.group.cell(self.group.which_cell(x, y));
  582. for g in g {
  583. self.possible.set(*g, val, false);
  584. }
  585. let idx = self.possible.pos(x, y);
  586. self.possible.possible[idx] = GenBits::<u32>(0); // .clear();
  587. self.board.board[idx] = value;
  588. }
  589. /// Validate the board
  590. /// Reuse reset_possible code, verify the values are possible.
  591. /// - This does not check if the board is completed.
  592. /// - It does check that blanks have possible values.
  593. pub fn validate_board(&mut self) -> bool {
  594. let mut has_blanks = false;
  595. self.possible.clear();
  596. for y in 0..self.board.width {
  597. for x in 0..self.board.width {
  598. let value = self.board.get(x, y);
  599. if value != 0 {
  600. if !self.possible.get(self.possible.pos(x, y), value as usize) {
  601. // I was going to reset_possible, but the board is broken!
  602. // Leave in a broken state.
  603. // log (maybe)
  604. // println!("Invalid at ({},{}) can't place {}.", x + 1, y + 1, value);
  605. // self.board.display();
  606. return false;
  607. }
  608. self.process_move(x, y, value);
  609. } else {
  610. has_blanks = true;
  611. }
  612. }
  613. }
  614. // Ok, the pieces given fit correctly with the sudoku constraints.
  615. if has_blanks {
  616. // Verify that the remaining value == 0 positions have possibles.
  617. // - If they are blank, then it isn't a valid puzzle!
  618. for y in 0..self.board.width {
  619. for x in 0..self.board.width {
  620. let value = self.board.get(x, y);
  621. if value == 0 {
  622. let count = self.possible.possible[self.possible.pos(x, y)].count_set();
  623. if count == 0 {
  624. // log (maybe)
  625. // println!("Invalid ({},{}) = no values possible.", x + 1, y + 1);
  626. // self.board.display();
  627. return false;
  628. }
  629. }
  630. }
  631. }
  632. }
  633. true
  634. }
  635. /// Reset the possible
  636. /// - For when a new puzzle has been loaded.
  637. /// - When something has changed, and the possibles are out of sync.
  638. pub fn reset_possible(&mut self) {
  639. self.possible.clear();
  640. for y in 0..self.board.width {
  641. for x in 0..self.board.width {
  642. let value = self.board.get(x, y);
  643. if value != 0 {
  644. self.process_move(x, y, value);
  645. }
  646. }
  647. }
  648. }
  649. /// set (x,y) to value.
  650. /// - This updates the board.
  651. /// - This updates all the possibles (row,column,cell).
  652. /// - Clears the possible for (x,y) [See process_move].
  653. pub fn set(&mut self, x: u8, y: u8, value: u8) {
  654. debug_assert!(
  655. x < self.board.width && y < self.board.width,
  656. "Expected ({}, {}) < {}",
  657. x,
  658. y,
  659. self.board.width
  660. );
  661. debug_assert!(
  662. value < self.board.width + 1,
  663. "Expected value {} < {}",
  664. value,
  665. self.board.width + 1
  666. );
  667. self.board.set(x, y, value);
  668. if value != 0 {
  669. self.process_move(x, y, value);
  670. }
  671. }
  672. /// Make completed board.
  673. /// - uses fill_board (recursive)
  674. pub fn make(&mut self) {
  675. let mut rng = ChaCha20Rng::from_entropy();
  676. self.reset_possible();
  677. self.fill_board(&mut rng);
  678. }
  679. /// Recursively completely fill the board.
  680. /// This takes - quite a bit of time - for a 25x25 board.
  681. fn fill_board(&mut self, rng: &mut ChaCha20Rng) -> bool {
  682. let backup = self.clone();
  683. let max_index = self.board.max_index;
  684. let width = self.board.width;
  685. for idx in 0..max_index {
  686. if self.board.board[idx] == 0 {
  687. let (x, y) = self.board.xy(idx);
  688. let mut available: Vec<u8> = Vec::new();
  689. available.reserve(width as usize);
  690. for t in self.possible.possible[idx].iter() {
  691. available.push(t + 1);
  692. }
  693. if available.len() == 0 {
  694. return false;
  695. }
  696. // print!("{:?}", available);
  697. // Randomize the possible items.
  698. available.shuffle(rng);
  699. // available.as_mut_slice().shuffle(rng);
  700. // print!("{:?}", available);
  701. for value in available.into_iter() {
  702. assert!(value != 0);
  703. self.set(x, y, value);
  704. // self.board.display();
  705. // self.possible.display();
  706. // I can't validate board, it might be invalid!
  707. // Really!
  708. /*
  709. if ! self.validate_board() {
  710. panic!("Whaaaat?!");
  711. }
  712. */
  713. if self.fill_board(rng) {
  714. return true;
  715. }
  716. // Failure
  717. self.board.copy(&backup.board);
  718. self.possible.copy(&backup.possible);
  719. }
  720. // We've run out of possible.
  721. return false;
  722. }
  723. }
  724. // We've visited everything, and it isn't 0.
  725. true
  726. }
  727. fn logic_pass1(&mut self) -> bool {
  728. // Pass 1: Look for singles in the possible sets.
  729. let mut pass1 = false;
  730. // Repeat pass 1 until all have been found.
  731. let mut pass1_again = true;
  732. while pass1_again {
  733. // Pass 1 - look for singles.
  734. pass1_again = false;
  735. let mut found_something = false;
  736. for i in 0..self.possible.max_index {
  737. if self.board.board[i] != 0 {
  738. // Skip, if position already filled.
  739. continue;
  740. }
  741. if self.possible.possible[i].count_set() == 1 {
  742. // Get value
  743. let value = self.possible.possible[i].iter().next().unwrap() + 1;
  744. let pos = self.board.xy(i);
  745. // println!("SET {}({},{})={}", i, pos.0 + 1, pos.1 + 1, value);
  746. self.set(pos.0, pos.1, value);
  747. found_something = true;
  748. }
  749. }
  750. if found_something {
  751. // We found something on this pass, so:
  752. // - Try it again.
  753. // - Record that we did something.
  754. pass1 = true;
  755. pass1_again = true;
  756. }
  757. }
  758. pass1
  759. }
  760. fn logic_pass2(&mut self) -> bool {
  761. let mut found_something = false;
  762. let mut pass2 = false;
  763. let mut pass2_again = true;
  764. let width = self.group.width;
  765. let grp = self.group.clone();
  766. while pass2_again {
  767. pass2_again = false;
  768. // let mut values = Bits(0); // HashSet<u8> = HashSet::new();
  769. let mut values = GenBits::<u32>(0);
  770. let mut group_process = |this: &mut Self, grp: &[usize]| {
  771. // Collect all the possible values within the group.
  772. values.clear();
  773. for gidx in 0..width {
  774. // println!("possible: {:?}", this.possible[grp.items[gidx as usize] as usize]);
  775. for v in this.possible.possible[grp[gidx as usize]].iter() {
  776. values.set(v as usize, true);
  777. }
  778. // values.extend(this.possible[grp.0[gidx as usize] as usize]);
  779. // println!("now : {:?}", this.possible[grp.items[gidx as usize] as usize]);
  780. }
  781. // println!("values {:?}", values);
  782. // Now, check for singles.
  783. for v in values.iter() {
  784. // println!("Check Value: {}", v);
  785. let mut count = 0;
  786. let mut pos = 0;
  787. for gidx in 0..width {
  788. if this.possible.possible[grp[gidx as usize]].get(v as usize) {
  789. // if this.possible[grp.0[gidx as usize] as usize].contains(&v) {
  790. count += 1;
  791. pos = grp[gidx as usize];
  792. if count > 1 {
  793. break;
  794. } else {
  795. // print!(" IDX {} POS {} ", gidx, pos);
  796. }
  797. }
  798. }
  799. if count == 1 {
  800. // don't need this, it was v!
  801. // let value = this.possible[pos as usize].iter().next().cloned().unwrap();
  802. let xy = this.board.xy(pos);
  803. // this.possible.display();
  804. // this.board.display();
  805. this.set(xy.0, xy.1, v + 1);
  806. // println!("SET {} ({},{}) = {}", pos, xy.0 + 1, xy.1 + 1, v+1);
  807. found_something = true;
  808. }
  809. }
  810. };
  811. for gr in Groups::iter() {
  812. for i in 0..width {
  813. let g = grp.group(gr, i);
  814. group_process(self, g);
  815. }
  816. }
  817. /*
  818. // Change to 0..WIDTH ... Keep it simple.
  819. for i in 0..width {
  820. // println!("Column {i}:");
  821. let mut g = grp.column(i);
  822. group_process(self, g);
  823. // println!("Row {i}:");
  824. g = grp.row(i);
  825. group_process(self, g);
  826. // println!("Cell {i}:");
  827. g = grp.cell(i);
  828. group_process(self, g);
  829. }
  830. */
  831. if found_something == true {
  832. // Ok, pass 2 found something.
  833. pass2 = true;
  834. found_something = false;
  835. pass2_again = true;
  836. // continue;
  837. }
  838. }
  839. pass2
  840. }
  841. /// Solve by logic alone.
  842. /// - Returns true if solved.
  843. /// - It might not be solved (if guessing is required).
  844. pub fn solve_logic(&mut self) -> bool {
  845. // self.reset_possible(); // destroys anything pass3 accomplishes ...
  846. // self.board.display();
  847. // self.possible.display();
  848. let mut found_more = true;
  849. while found_more {
  850. found_more = false;
  851. let mut result1 = true;
  852. // Pass 1: Look for singles in the possible sets.
  853. while result1 {
  854. result1 = self.logic_pass1();
  855. if result1 {
  856. println!("Pass1");
  857. };
  858. }
  859. let mut result2 = true;
  860. while result2 {
  861. result2 = self.logic_pass2();
  862. if result2 {
  863. println!("Pass2");
  864. found_more = true;
  865. };
  866. }
  867. /*
  868. // Pass 2: Is the same as Pass 1!
  869. // We just look in groups, instead of all the indexes.
  870. let mut found_something = false;
  871. let mut pass1 = false;
  872. // Repeat pass 1 until all have been found.
  873. let mut pass1_again = true;
  874. let width = self.group.width;
  875. let grp = self.group.clone();
  876. let mut pass2 = false;
  877. while pass1_again {
  878. // Pass 1 - look for singles.
  879. for i in 0..self.possible.max_index {
  880. if self.board.board[i] != 0 {
  881. // Skip, if position already filled.
  882. continue;
  883. }
  884. if self.possible.possible[i].count_set() == 1 {
  885. // Get value
  886. let value = self.possible.possible[i].iter().next().unwrap() + 1;
  887. let pos = self.board.xy(i);
  888. // println!("SET {}({},{})={}", i, pos.0 + 1, pos.1 + 1, value);
  889. self.set(pos.0, pos.1, value);
  890. found_something = true;
  891. }
  892. }
  893. if found_something {
  894. // We found something this pass.
  895. // - set pass1 to true (pass 1 found something)
  896. // - reset found_something so we can try again.
  897. pass1 = true;
  898. found_something = false;
  899. continue;
  900. } else {
  901. // Nothing found with this run of pass 1.
  902. // Pass 2 - Look for singles within the groups.
  903. // Are we done?
  904. /*
  905. if self.board.complete() {
  906. return false;
  907. }
  908. // We're getting stuck in pass 2 ...
  909. // not anymore. ;)
  910. println!("Pass 2:");
  911. self.board.display();
  912. */
  913. found_something = false;
  914. // let mut values = Bits(0); // HashSet<u8> = HashSet::new();
  915. let mut values = GenBits::<u32>(0);
  916. let mut group_process = |this: &mut Self, grp: &[usize]| {
  917. // Collect all the possible values within the group.
  918. values.clear();
  919. for gidx in 0..width {
  920. // println!("possible: {:?}", this.possible[grp.items[gidx as usize] as usize]);
  921. for v in this.possible.possible[grp[gidx as usize]].iter() {
  922. values.set(v as usize, true);
  923. }
  924. // values.extend(this.possible[grp.0[gidx as usize] as usize]);
  925. // println!("now : {:?}", this.possible[grp.items[gidx as usize] as usize]);
  926. }
  927. // println!("values {:?}", values);
  928. // Now, check for singles.
  929. for v in values.iter() {
  930. // println!("Check Value: {}", v);
  931. let mut count = 0;
  932. let mut pos = 0;
  933. for gidx in 0..width {
  934. if this.possible.possible[grp[gidx as usize]].get(v as usize) {
  935. // if this.possible[grp.0[gidx as usize] as usize].contains(&v) {
  936. count += 1;
  937. pos = grp[gidx as usize];
  938. if count > 1 {
  939. break;
  940. } else {
  941. // print!(" IDX {} POS {} ", gidx, pos);
  942. }
  943. }
  944. }
  945. if count == 1 {
  946. // don't need this, it was v!
  947. // let value = this.possible[pos as usize].iter().next().cloned().unwrap();
  948. let xy = this.board.xy(pos);
  949. // this.possible.display();
  950. // this.board.display();
  951. this.set(xy.0, xy.1, v + 1);
  952. // println!("SET {} ({},{}) = {}", pos, xy.0 + 1, xy.1 + 1, v+1);
  953. found_something = true;
  954. }
  955. }
  956. };
  957. // Change to 0..WIDTH ... Keep it simple.
  958. for i in 0..width {
  959. // println!("Column {i}:");
  960. let mut g = grp.column(i);
  961. group_process(self, g);
  962. // println!("Row {i}:");
  963. g = grp.row(i);
  964. group_process(self, g);
  965. // println!("Cell {i}:");
  966. g = grp.cell(i);
  967. group_process(self, g);
  968. }
  969. if found_something == true {
  970. pass2 = true;
  971. // Ok, pass 2 found something.
  972. found_something = false;
  973. continue;
  974. }
  975. //
  976. // - If pass1 set, reset the found_something (because it
  977. // did find something)
  978. // - Clear the pass1_again flag, we're done with pass 1.
  979. if pass1 {
  980. pass1_again = false;
  981. found_something = true;
  982. } else {
  983. // Ok, we didn't find anything.
  984. // Break out of loop, get unstuck.
  985. break;
  986. }
  987. }
  988. }
  989. // Pass 3:
  990. // - Find pairs & remove those numbers from corresponding group.
  991. let grp = self.group.clone();
  992. println!("Pass 3:");
  993. self.board.display();
  994. self.possible.display();
  995. assert_eq!(self.board.width, self.possible.width);
  996. // Pair processing.
  997. for i in 0..width {
  998. let mut g = grp.cell(i);
  999. println!("Cell {}: {:?}", i, g);
  1000. for gidx in 0..WIDTH - 1 {
  1001. let gpos = g[gidx as usize];
  1002. if self.possible.possible[gpos].count_set() == 2 {
  1003. // Found a pair
  1004. for fidx in gidx + 1..width {
  1005. let fpos = g[fidx as usize];
  1006. if self.possible.possible[fpos as usize].count_set() == 2 {
  1007. // Ok, there's another pair
  1008. // if self.possible[gpos as usize].is_subset(&self.possible[fpos as usize])
  1009. if self.possible.possible[gpos] == self.possible.possible[fpos] {
  1010. // Ok, they have the same values!
  1011. // Ok, remove the items in the pair from the cell.
  1012. // Don't touch the gpos/fpos records. Keep those!
  1013. // This looks .. WRONG! only z+1 when using set(value)!
  1014. let mut values: [u8; 2] = [0, 0];
  1015. let mut vpos = 0;
  1016. for z in self.possible.possible[gpos].iter() {
  1017. values[vpos] = z;
  1018. vpos += 1;
  1019. }
  1020. // Ok, other then being off by 1 (because x,y starts at 0 not 1),
  1021. // This is, at least, displaying the information properly.
  1022. self.possible.display();
  1023. println!(
  1024. "Pairs {gpos}({},{}) and {fpos}({},{}) {:?}",
  1025. self.possible.xy(gpos).0 + 1,
  1026. self.possible.xy(gpos).1 + 1,
  1027. self.possible.xy(fpos).0 + 1,
  1028. self.possible.xy(fpos).1 + 1,
  1029. values
  1030. );
  1031. let mut pair_removed = false;
  1032. // Check to see if anything was removed.
  1033. for remove in 0..width {
  1034. if (gidx == remove) || (fidx == remove) {
  1035. // Skip the found pair indexes. Don't remove those!
  1036. continue;
  1037. }
  1038. // Ok, these aren't the ones to save, so:
  1039. let rpos = g[remove as usize];
  1040. if self.possible.possible[rpos].get(values[0] as usize) {
  1041. self.possible.possible[rpos].set(values[0] as usize, false);
  1042. found_something = true;
  1043. pair_removed = true;
  1044. println!("Removed {} from {}({},{})", values[0], rpos, self.possible.xy(rpos).0, self.possible.xy(rpos).1);
  1045. }
  1046. if self.possible.possible[rpos].get(values[1] as usize) {
  1047. self.possible.possible[rpos].set(values[1] as usize, false);
  1048. found_something = true;
  1049. pair_removed = true;
  1050. println!("Removed {} from {}({},{})", values[1], rpos, self.possible.xy(rpos).0, self.possible.xy(rpos).1);
  1051. }
  1052. }
  1053. if pair_removed {
  1054. println!("pair removed...");
  1055. println!(
  1056. "--> Pairs {gpos}({},{}) and {fpos}({},{}) {:?}",
  1057. self.possible.xy(gpos).0 + 1,
  1058. self.possible.xy(gpos).1 + 1,
  1059. self.possible.xy(fpos).0 + 1,
  1060. self.possible.xy(fpos).1 + 1,
  1061. values
  1062. );
  1063. }
  1064. // Check the x's and y's to see if we can also process a row/column too.
  1065. if self.possible.xy(gpos).0 == self.possible.xy(fpos).0 {
  1066. // Matching X - process column
  1067. let column = xy(gpos).0;
  1068. vpos = 0;
  1069. for z in self.possible.possible[gpos].iter() {
  1070. values[vpos] = z + 1;
  1071. vpos += 1;
  1072. }
  1073. for remove in 0..WIDTH {
  1074. if (remove == xy(gpos).1) || (remove == xy(fpos).1) {
  1075. continue;
  1076. }
  1077. let pos = self.possible.pos(column, remove);
  1078. if self.possible.possible[pos].get(values[0] as usize) {
  1079. self.possible.possible[pos]
  1080. .set(values[0] as usize, false);
  1081. found_something = true;
  1082. pair_removed = true;
  1083. }
  1084. if self.possible.possible[pos].get(values[1] as usize) {
  1085. self.possible.possible[pos]
  1086. .set(values[1] as usize, false);
  1087. found_something = true;
  1088. pair_removed = true;
  1089. }
  1090. }
  1091. }
  1092. if self.possible.xy(gpos).1 == self.possible.xy(fpos).1 {
  1093. // Matching Y - process row
  1094. let row = self.possible.xy(gpos).1;
  1095. vpos = 0;
  1096. for z in self.possible.possible[gpos].iter() {
  1097. values[vpos] = z + 1;
  1098. vpos += 1;
  1099. }
  1100. for remove in 0..width {
  1101. if (remove == self.possible.xy(gpos).0)
  1102. || (remove == self.possible.xy(fpos).0)
  1103. {
  1104. continue;
  1105. }
  1106. let pos = self.possible.pos(remove, row);
  1107. if self.possible.possible[pos].get(values[0] as usize) {
  1108. self.possible.possible[pos]
  1109. .set(values[0] as usize, false);
  1110. found_something = true;
  1111. pair_removed = true;
  1112. }
  1113. if self.possible.possible[pos].get(values[1] as usize) {
  1114. self.possible.possible[pos]
  1115. .set(values[1] as usize, false);
  1116. found_something = true;
  1117. pair_removed = true;
  1118. }
  1119. }
  1120. }
  1121. if pair_removed {
  1122. if true {
  1123. println!(
  1124. "Pair found! {} {}: {} {:?} and {} {:?} !",
  1125. gidx,
  1126. fidx,
  1127. gpos,
  1128. self.board.xy(gpos),
  1129. fpos,
  1130. self.board.xy(fpos)
  1131. );
  1132. self.possible.display();
  1133. // panic!("... We're lost ...");
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. }
  1141. }
  1142. println!("Pass 3 - Ending...");
  1143. found_something
  1144. */
  1145. }
  1146. self.board.complete()
  1147. }
  1148. }
  1149. #[cfg(test)]
  1150. mod tests {
  1151. use crate::sudoku::*;
  1152. #[test]
  1153. fn display_board() {
  1154. let mut board = AnyBoard::new(3);
  1155. let result = board.load_from_tld(
  1156. 'b',
  1157. '_',
  1158. "__c_____e_h__cb___bd___ei_ch_jb__d___________i_eh__b__dg___ij_f_i__jg_____b_____g",
  1159. );
  1160. assert!(result.is_ok());
  1161. let strings = board.to_strings();
  1162. assert_eq!(
  1163. strings,
  1164. vec![
  1165. " 17 83 ",
  1166. " 73 68 ",
  1167. "2 9 4 1",
  1168. " 1 7 ",
  1169. " 2 9 ",
  1170. " 14 86 ",
  1171. " 83 19 ",
  1172. " ",
  1173. "4 2 5 6"
  1174. ]
  1175. );
  1176. // board.display();
  1177. let mut solver = AnySolver::new_from(&board);
  1178. assert!(solver.validate_board());
  1179. solver.reset_possible();
  1180. if solver.solve_logic() {
  1181. solver.board.display();
  1182. }
  1183. assert!(solver.validate_board());
  1184. assert!(solver.board.complete());
  1185. board = AnyBoard::new(4);
  1186. let result = board.load_from_tld('b', '_', "_bo_j_m_f__dp__ge_h_pcfdo___q__n___qio______df___f__l___hpnm_i___obig_p_qhl__k_m_dq_cn______o_g_p_____bi_kc__jn______fo____gi______eb____jd______jk__ml_bn_____i_m_b______oq_nj_d_n__jck_m_fgbq___i_medp___n__b___dg______qjk___j__p___fgohl_d_qo__mq__g_d_p_le_");
  1187. assert!(result.is_ok());
  1188. let strings = board.to_strings();
  1189. assert_eq!(
  1190. strings,
  1191. vec![
  1192. " D O C IN",
  1193. "A ENC IL ",
  1194. "NG AP J MHC ",
  1195. " P H D A FOL",
  1196. "IOHKFB A L P",
  1197. " BN M E L ID ",
  1198. "LE O AN K BC ",
  1199. " C H JO EF",
  1200. "EN GP A F ",
  1201. " OG J IM L NC",
  1202. " MK B C N PG ",
  1203. "C L F PEMIKO",
  1204. "OPC N H F J ",
  1205. " EHJ I MA CK",
  1206. " FM IPA D",
  1207. "FM L H P "
  1208. ]
  1209. );
  1210. // board.display();
  1211. let mut solver = AnySolver::new_from(&board);
  1212. assert!(solver.validate_board());
  1213. solver.board.display();
  1214. if solver.solve_logic() {
  1215. solver.board.display();
  1216. }
  1217. assert!(solver.validate_board());
  1218. solver.board.display();
  1219. assert!(solver.board.complete());
  1220. let mut board: AnyBoard = AnyBoard::new(5);
  1221. let result = board.load_from_tld('b', '_', "_m_kzg____h_s_n____ftd_u_u_dh_____f_b_t_w_____yg_c_rl_o_tdhy__m__uvig_w_sk_eg___p_q_jikouys_r_d___mlq_t_sb_emcwg_dlzyo_kp_i_ng__ir_b_fp_vhz_ce_y_jm__w__m__o_k_xul_qbt_d_s__e____otv_dhegn___mfkpz_blr____s_dv_n_mjx_ckg_w_bo_p___kqyelwjcz_____nxumoisdh_z__fp_vbi_______dkx_eg__r_y_mlwf_u__q_i__o_chdv_j_i_he_r_____________p_zl_k_d_vbjh_y__e_p__s_tguc_q_s__qj_kpn_______ufw_hx__i_hvntirfxw_____lbckympjg___u_kz_m_bfn_yvx_h_ir_o____rgm_otlnx___ipfes_kwc____p__c_v_ugh_krj_m_w__x__x__ci_j_qk_mpo_dr_u_zb__ht_i_qe_wjvcy_bhkzx_ng_u_syv___u_c_hsfrlqo_t_e___pj_cn_h_slzr__j__mqgp_y_vd_m_bs_____t_o_n_h_____ez_f_e_ufd____p_g_z____cqr_x_");
  1222. assert!(result.is_ok());
  1223. // board.display();
  1224. let strings: Vec<String> = board.to_strings();
  1225. assert_eq!(
  1226. strings,
  1227. vec![
  1228. " T DPF Y H R WSX L ",
  1229. "L QF J X C G UB D",
  1230. " CK S LNRP G UTQO H MA ",
  1231. "JG H S XELDUPM F B RT",
  1232. "Y N RQ UCDOK AISJL HP G E",
  1233. "F OA N UK VQI HY B DT C",
  1234. " S A C VUE GJQ N I R ",
  1235. " CPD JGMIA OELSU VBK ",
  1236. " G LE D BHT XMW K PI Y ",
  1237. " EXIBOWFLY VAMTJUGQS ",
  1238. "G HV TMI EWF BR O",
  1239. " A JFUK W P D M GLXE N ",
  1240. "R LN G O QI F",
  1241. " S TCYP B H O X JNAK M ",
  1242. "M XK ALJ UHQ GP Y",
  1243. " VTRYBSEFM KWOICJNLG ",
  1244. " U XD J WCN RTA E QY P ",
  1245. " HQN COVTJ EBGDL WSF ",
  1246. " F X Y LWB SVJ R T O ",
  1247. "E CJ R AN GOF XH V MD B",
  1248. "S V OI ANHDC TGLQJ YF X P",
  1249. "CX L K RFUYBWO V A DQ",
  1250. " FR H DQOC K INBW T UY ",
  1251. "T JL G I P F OC W",
  1252. " B KMV Q J H GRI E "
  1253. ]
  1254. );
  1255. let mut solver = AnySolver::new_from(&board);
  1256. assert!(solver.validate_board());
  1257. }
  1258. #[test]
  1259. fn solve_board() {
  1260. let mut board = AnyBoard::new(3);
  1261. let result = board.load_from_tld(
  1262. 'b',
  1263. '_',
  1264. "__c_____e_h__cb___bd___ei_ch_jb__d___________i_eh__b__dg___ij_f_i__jg_____b_____g",
  1265. );
  1266. assert!(result.is_ok());
  1267. assert_eq!(3, board.size);
  1268. assert_eq!(9, board.width);
  1269. assert_eq!(81, board.max_index);
  1270. // board.display();
  1271. let strings: Vec<String> = board.to_strings();
  1272. assert_eq!(
  1273. strings,
  1274. vec![
  1275. " 17 83 ",
  1276. " 73 68 ",
  1277. "2 9 4 1",
  1278. " 1 7 ",
  1279. " 2 9 ",
  1280. " 14 86 ",
  1281. " 83 19 ",
  1282. " ",
  1283. "4 2 5 6"
  1284. ]
  1285. );
  1286. let mut solver = AnySolver::new_from(&board);
  1287. assert!(solver.validate_board());
  1288. let solutions = solver.board.brute_force_solver(2);
  1289. assert!(solutions.0 == 1, "Expected 1 solution, got {}", solutions.0);
  1290. let strings: Vec<String> = solutions.1[0].to_strings();
  1291. assert_eq!(
  1292. strings,
  1293. vec![
  1294. "541768329",
  1295. "973512684",
  1296. "286934751",
  1297. "869157243",
  1298. "325486197",
  1299. "714293865",
  1300. "658341972",
  1301. "197625438",
  1302. "432879516",
  1303. ]
  1304. );
  1305. // 4x4 board takes 40 minutes
  1306. if false {
  1307. board = AnyBoard::new(4);
  1308. let result = board.load_from_tld('b', '_', "_bo_j_m_f__dp__ge_h_pcfdo___q__n___qio______df___f__l___hpnm_i___obig_p_qhl__k_m_dq_cn______o_g_p_____bi_kc__jn______fo____gi______eb____jd______jk__ml_bn_____i_m_b______oq_nj_d_n__jck_m_fgbq___i_medp___n__b___dg______qjk___j__p___fgohl_d_qo__mq__g_d_p_le_");
  1309. assert!(result.is_ok());
  1310. board.display();
  1311. let mut solver = AnySolver::new_from(&board);
  1312. assert!(solver.validate_board());
  1313. let solutions = solver.board.brute_force_solver(2);
  1314. assert!(solutions.0 == 1);
  1315. }
  1316. }
  1317. #[test]
  1318. fn make_board() {
  1319. // Making a 4x4 board varies (0.3-60 seconds).
  1320. // Maybe we don't want to do this in a test, because of the randomness involved.
  1321. let mut solver = AnySolver::new(3);
  1322. solver.make();
  1323. solver.board.display();
  1324. assert!(solver.validate_board());
  1325. }
  1326. #[test]
  1327. fn validated_board() {
  1328. // Create an invalid board. Position (5,9) can't possibly hold any value.
  1329. let mut board = AnyBoard::new(3);
  1330. board.set(4, 0, 1);
  1331. board.set(4, 1, 2);
  1332. board.set(4, 2, 3);
  1333. board.set(4, 3, 4);
  1334. board.set(4, 4, 5);
  1335. board.set(4, 5, 6);
  1336. board.set(0, 8, 7);
  1337. board.set(1, 8, 8);
  1338. board.set(2, 8, 9);
  1339. // board.display();
  1340. let mut solver = AnySolver::new_from(&board);
  1341. assert!(!solver.validate_board());
  1342. // Invalid board: Has two 1's in same column & cell.
  1343. let mut board = AnyBoard::new(3);
  1344. board.set(4, 0, 1);
  1345. board.set(4, 1, 1);
  1346. // board.display();
  1347. let mut solver = AnySolver::new_from(&board);
  1348. assert!(!solver.validate_board());
  1349. // Invalid board: Has two 1's in same row & cell.
  1350. let mut board = AnyBoard::new(3);
  1351. board.set(4, 0, 1);
  1352. board.set(5, 0, 1);
  1353. // board.display();
  1354. // Invalid board: Has two 1's in same column.
  1355. let mut board = AnyBoard::new(3);
  1356. board.set(4, 0, 1);
  1357. board.set(4, 4, 1);
  1358. // board.display();
  1359. let mut solver = AnySolver::new_from(&board);
  1360. assert!(!solver.validate_board());
  1361. // Invalid board: Has two 1's in same row.
  1362. let mut board = AnyBoard::new(3);
  1363. board.set(4, 0, 1);
  1364. board.set(7, 0, 1);
  1365. // board.display();
  1366. let mut solver = AnySolver::new_from(&board);
  1367. assert!(!solver.validate_board());
  1368. // Invalid board: Has two 1's in same cell.
  1369. let mut board = AnyBoard::new(3);
  1370. board.set(4, 0, 1);
  1371. board.set(5, 1, 1);
  1372. // board.display();
  1373. let mut solver = AnySolver::new_from(&board);
  1374. assert!(!solver.validate_board());
  1375. }
  1376. }
  1377. /*
  1378. /// Puzzle generation
  1379. /// - Removes a number, tests to see if the puzzle can still be solved by logic.
  1380. /// - Returns true when still a valid, solvable puzzle.
  1381. /// - Otherwise, restores number and returns false.
  1382. pub fn remove(&mut self) -> bool {
  1383. // Find a number, remove it. Save position.
  1384. let mut rng = ChaCha20Rng::from_entropy();
  1385. let puzrange = Uniform::new(0, WIDTH);
  1386. let mut x = 0;
  1387. let mut y = 0;
  1388. let mut value: u8 = 0;
  1389. while value == 0 {
  1390. x = puzrange.sample(&mut rng);
  1391. y = puzrange.sample(&mut rng);
  1392. value = self.get(x, y);
  1393. }
  1394. self.set(x, y, 0);
  1395. // Clone, and solve by logic.
  1396. let mut puzcopy = self.clone();
  1397. puzcopy.reset_possible();
  1398. /*
  1399. puzcopy.display();
  1400. puzcopy.display_possible();
  1401. */
  1402. // If solvable, return true.
  1403. while puzcopy.solve(false) {}
  1404. /*
  1405. puzcopy.display();
  1406. puzcopy.display_possible();
  1407. */
  1408. if puzcopy.puzzle_complete() {
  1409. return true;
  1410. }
  1411. // If not solvable, restore number, return false.
  1412. self.set(x, y, value);
  1413. return false;
  1414. }
  1415. */