-
-
Save vickean/ec6264fafcf81f8d5be0fb31eb009021 to your computer and use it in GitHub Desktop.
Sudoku
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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