Advertisement
saltycracker

Sudoku(9x9).rb

Dec 14th, 2020 (edited)
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.96 KB | None | 0 0
  1. #! /usr/bin/env ruby
  2.  
  3. SudokuSize = 81
  4. SudokuRow = 9
  5. SudokuBox = 3
  6. SudokuValidCharacters = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  7. SudokuStr = "000008000200059000100000250008001460300000100904083000000500084000004900023000000"
  8.  
  9. arr =
  10.   SudokuStr
  11.   .chars
  12.   .map{|c| c.to_i}
  13.  
  14. def buildRow (p)
  15.   r = p % SudokuRow
  16.   rp = p / SudokuRow
  17.   row = []
  18.   0.upto(SudokuRow - 1).each{
  19.     |e|
  20.     if e != r
  21.     then
  22.       row.push(e + (rp * SudokuRow))
  23.     end
  24.   }
  25.   row
  26. end
  27.  
  28. def buildCol (p)
  29.   r = p % SudokuRow
  30.   rp = p / SudokuRow
  31.   col = []
  32.   0.upto(SudokuRow - 1).each{
  33.     |e|
  34.     if e != rp
  35.     then
  36.       col.push(r + (e * SudokuRow))
  37.     end
  38.   }
  39.   col
  40. end
  41.  
  42. def buildBoxArr (p)
  43.   if p == 0
  44.   then
  45.     [1, 2]
  46.   elsif p == 1
  47.   then
  48.     [-1, 1]
  49.   else
  50.     [-2, -1]
  51.   end  
  52. end
  53.  
  54. def buildBox (p)
  55.   r = buildBoxArr((p / SudokuRow) % SudokuBox)
  56.   c = buildBoxArr(p % SudokuBox)
  57.   r.reduce([]){|ar, dr| c.reduce(ar){|ac, dc| ac.push(dc + p + (dr * SudokuRow))}}
  58. end
  59.  
  60. def buildStartingValues(e, ar)
  61.   SudokuValidCharacters
  62.     .reduce([]){
  63.       |a, s|
  64.       if (e.find{|ed| ar[ed] == s})
  65.       then
  66.         a
  67.       else
  68.         a.push(s)
  69.       end
  70.     }
  71. end
  72.  
  73. sudokuArr =  
  74.   arr
  75.   .map
  76.   .each_with_index{
  77.     |v, i|
  78.     fixed = v == 0 ? false : true
  79.     edges = fixed ? [] : (buildRow i) + (buildCol i) + (buildBox i)
  80.     startingValues = fixed ? [] : buildStartingValues(edges, arr)
  81.     [i, v, fixed, edges, startingValues]
  82.   }
  83.  
  84. def solveIt(sa, pos, ar)
  85.   if pos < SudokuSize
  86.   then
  87.     elem = sa[pos]
  88.     pe = elem[0]
  89.     v = elem[1]
  90.     f = elem[2]
  91.     e = elem[3]
  92.     sv = elem[4]
  93.     if f
  94.     then
  95.       solveIt(sa, pos + 1, ar)
  96.     else
  97.       sv.each{
  98.         |s|
  99.         if (e.find{|ed| ar[ed] == s})
  100.         then
  101.        
  102.         else
  103.           ar[pos] = s
  104.           solveIt(sa, pos + 1, ar)
  105.           ar[pos] = 0
  106.         end
  107.       }
  108.     end
  109.   else
  110.     p ar
  111.   end
  112. end
  113.  
  114. solveIt(sudokuArr, 0, arr)
  115.  
  116.  
  117.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement