Advertisement
Revolucent

Rust Sudoku Validator

Jul 16th, 2021
1,911
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.56 KB | None | 0 0
  1. // This probably sucks and is horribly inefficient, but I'm still learning Rust.
  2.  
  3. type Row = [u32; 9];
  4. type Sudoku = [Row; 9];
  5.  
  6. static SUDOKU: Sudoku = [
  7.   [8, 2, 7, 1, 5, 4, 3, 9, 6],
  8.   [9, 6, 5, 3, 2, 7, 1, 4, 8],
  9.   [3, 4, 1, 6, 8, 9, 7, 5, 2],
  10.   [5, 9, 3, 4, 6, 8, 2, 7, 1],
  11.   [4, 7, 2, 5, 1, 3, 6, 8, 9],
  12.   [6, 1, 8, 9, 7, 2, 4, 3, 5],
  13.   [7, 8, 6, 2, 3, 5, 9, 1, 4],
  14.   [1, 5, 4, 7, 9, 6, 8, 2, 3],
  15.   [2, 3, 9, 8, 4, 1, 5, 6, 7]
  16. ];
  17.  
  18. static VALID_ROW: Row = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  19.  
  20. fn is_valid(row: &[u32]) -> bool {
  21.   let mut clone = [0u32; 9];
  22.   clone.clone_from_slice(row);
  23.   clone.sort();
  24.   clone == VALID_ROW
  25. }
  26.  
  27. fn rotate(sudoku: &Sudoku) -> Sudoku {
  28.   let mut rotated = [[0u32; 9]; 9];
  29.   for r in 0..9 {
  30.     for c in 0..9 {
  31.       rotated[c][r] = sudoku[r][c];
  32.     }
  33.   }
  34.   rotated
  35. }
  36.  
  37. fn chunk(sudoku: &Sudoku) -> Sudoku {
  38.   let mut chunked = [[0u32; 9]; 9];
  39.   let mut c = 0;
  40.   let chunks = [0..3, 3..6, 6..9];
  41.   for outer in chunks.iter() {
  42.     for inner in chunks.iter() {
  43.       let mut chunk: Vec<u32> = vec![];
  44.       for o in outer.clone() {
  45.         for i in inner.clone() {
  46.           chunk.push(sudoku[o][i]);
  47.         }
  48.       }
  49.       chunked[c].clone_from_slice(&chunk);
  50.       c += 1;
  51.     }
  52.   }
  53.   chunked
  54. }
  55.  
  56. fn is_sudoku_valid(sudoku: &Sudoku) -> bool {
  57.   sudoku.iter().map(|row| is_valid(row)).fold(true, |a, b| a && b)
  58. }
  59.  
  60. fn validate(sudoku: &Sudoku) -> bool {
  61.   is_sudoku_valid(sudoku) && is_sudoku_valid(&rotate(sudoku)) && is_sudoku_valid(&chunk(sudoku))
  62. }
  63.  
  64. fn main() {
  65.   println!("{:?}", validate(&SUDOKU));
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement