-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.mk2.rb
87 lines (77 loc) · 1.83 KB
/
sudoku.mk2.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require 'colorize'
class Sudoku
def initialize
@board = Hash.new
@known_keys = []
@sub_range = [[0,1,2], [3,4,5], [6,7,8]]
File.open('sample') do |f|
row = 0
while line = f.gets
line.split.each_with_index do |number, col|
value = number.to_i
@board[[col, row]] = value
@known_keys << [col, row] if value > 0
#print "#{value} "
end
#puts
row += 1
end
end
show_result
puts
puts "Just a moment..."
puts
#puts @known_keys.to_s
end
def check_row(x, y)
row = (0..8).to_a.product([y]).collect{|key| @board[key]}
row.delete 0
return row == row.uniq
end
def check_column(x, y)
col = [x].product((0..8).to_a).collect{|key| @board[key]}
col.delete 0
return col == col.uniq
end
def check_sub(x, y)
x_r = @sub_range[ x / 3 ]
y_r = @sub_range[ y / 3 ]
nine = x_r.product(y_r).collect{|key| @board[key] }
nine.delete 0
return nine == nine.uniq
end
def try(step=0)
if step == 81
show_result
return true
end
y = step / 9
x = step % 9
key = [x, y]
return try( step + 1 ) if @known_keys.include? key
guesses = (1..9).to_a - (0..8).to_a.product([y]).collect{|key| @board[key]}
guesses.each do |g|
@board[key] = g
return true if check_column(x,y) && check_sub(x,y) && try(step + 1)
end
@board[key] = 0
return false
end
def show_result()
#(0..8).to_a.product((0..8).to_a).collect{|key| @board[key]}.each
for y in (0..8)
for x in (0..8)
if @known_keys.include? [x,y]
print @board[[x,y]].to_s.red
else
print @board[[x,y]] > 0 ? @board[[x,y]] : '.'
end
print ' '
end
print "\n"
end
end
end
s = Sudoku.new
s.check_row 1,3
s.try