Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.02 KB | None | 0 0
  1. class Sudoku
  2.   def initialize(puzzle)
  3.     @puzzle = puzzle
  4.     9.times do |x|
  5.       9.times do |y|
  6.         @puzzle[x][y] = Set.new(1..9) if @puzzle[x][y] == 0
  7.       end
  8.     end
  9.   end
  10.  
  11.   def react(x, y, val=nil)
  12.     if @puzzle[x][y].is_a?(Set)
  13.       @puzzle[x][y].delete(val)
  14.       if @puzzle[x][y].length == 1
  15.         @puzzle[x][y] = @puzzle[x][y].to_a[0]
  16.         9.times do |i|
  17.           react(x, i, @puzzle[x][y])
  18.           react(i, y, @puzzle[x][y])
  19.           react((x / 3 ) * 3 + i % 3, (y / 3 ) * 3 + i / 3, @puzzle[x][y])
  20.         end
  21.       end
  22.     end
  23.   end
  24.  
  25.   def solve
  26.     9.times do |x|
  27.       9.times do |y|
  28.         if @puzzle[x][y].is_a?(Integer)
  29.           9.times do |i|
  30.             react(x, i, @puzzle[x][y])
  31.             react(i, y, @puzzle[x][y])
  32.             react((x / 3 ) * 3 + i % 3, (y / 3 ) * 3 + i / 3, @puzzle[x][y])
  33.           end
  34.         end
  35.       end
  36.     end
  37.     self
  38.   end
  39.  
  40.   def puzzle
  41.     @puzzle
  42.   end
  43. end
  44.  
  45. def sudoku(puzzle)
  46.   Sudoku.new(puzzle).solve.puzzle
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement