Skip to content

Instantly share code, notes, and snippets.

@KevinSia
Forked from vickean/elegant_sudoku_solver.rb
Created June 9, 2016 18:47
Show Gist options
  • Save KevinSia/497dac2cf9409e50beaa5de67e12024a to your computer and use it in GitHub Desktop.
Save KevinSia/497dac2cf9409e50beaa5de67e12024a to your computer and use it in GitHub Desktop.
Sudoku
require 'Benchmark'
class Sudoku
attr_accessor :puzzle
def initialize
@puzzle = ''
@game = Array.new(9)
@game.map! { Array.new(9) }
9.times do |i|
9.times do |j|
@game[i][j] = nil
end
end
end
def file_read name
f = File.open(name, "r")
while(line = f.gets)
@puzzle << line
end
end
def to_s
puzzle = ''
9.times do |i|
9.times do |j|
puzzle << ' ' if j % 3 == 0 and j != 1
if @game[i][j] == nil
puzzle << "-"
else
puzzle << @game[i][j].to_s
end
end
puzzle << "\n"
puzzle << "\n" if (i + 1) % 3 == 0
end
return puzzle
end
def set(val)
i=0
val = val.delete("\n")
9.times do |row|
9.times do |col|
x = val[i].to_i
x = nil if x == 0
@game[row][col] = x
i+=1
end
end
end
def solve
9.times do |r|
9.times do |c|
next if @game[r][c]
1.upto(9) do |v|
# check -|-
next unless 9.times { |i| break if @game[i][c] == v || @game[r][i] == v }
# check 3x3
next unless 3.times do |i|
break unless 3.times do |j|
break if @game[i + r / 3 * 3][j + c / 3 * 3] == v
end
end
@game[r][c] = v
if solve
return true
else
@game[r][c] = nil # backtracking
end
end
return false
end
end
return true
end
end
sudo = Sudoku.new
sudo.file_read("tests.txt")
sudo.set(sudo.puzzle)
print sudo.to_s
Benchmark.bm do |x|
x.report("Sudoku:") { sudo.solve }
end
sudo.solve ? (print sudo.to_s) : "brak rozwiazania"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment