根据牛人PYTHON改的 数独 RUBY 算法,以及牛人的PYTHON数独生成算法。
#!/usr/bin/env ruby
require "socket"
require "pp"
s = TCPSocket.new 'localhost', 3
s.recv 1024
b = s.recv 1024
p b if $DEBUG
out = []
outout = [[],[],[],[],[],[],[],[],[]]
size = b.size
0.upto(size-1) do | i |
if b[i] =~ (/\d/)
out << b[i]
elsif b[i] =~ (/_/)
out << b[i]
end
end
for x in 0..80 do
tmp = x.divmod(9)[0]
outout[tmp] << out[x]
end
back = [[],[],[],[],[],[],[],[],[]]
pp outout if $DEBUG
guess = -1
solved = 0
while 1
p "guess: #{guess}" if $DEBUG
found = 0
0.upto(8) do | x |
print "x: #{x}" if $DEBUG
0.upto(8) do | y |
all = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
print "y: #{y}" if $DEBUG
if outout[x][y] == "_"
0.upto(8) do | yy |
all.delete(outout[x][yy])
#print "x : #{x}, y: #{yy} "
end
0.upto(8) do | xx |
all.delete(outout[xx][y])
end
( 3 * (x/3) ).upto( 3 * (x/3) + 2 ) do | zx |
( 3 * (y/3) ).upto( 3 * (y/3) + 2 ) do | zy |
all.delete(outout[zx][zy])
end
end
if all.size == 1
outout[x][y] = all[0]
found = 1
p x if $DEBUG
p y if $DEBUG
pp all if $DEBUG
pp outout if $DEBUG
elsif all.size == 0
#guess wrong
p "guess failed!!!!!!!!!!!!!!!!!!!!!!!!!" if $DEBUG
pp outout if $DEBUG
0.upto(8) do | i |
0.upto(8) do | j |
outout[i][j] = back[i][j]
end
end
p "outout recover: " if $DEBUG
pp outout if $DEBUG
back = [[],[],[],[],[],[],[],[],[]]
p "back . clear" if $DEBUG
p back if $DEBUG
found = 0
elsif guess != -1 && guess == x
r = rand(all.size)
p "guess line#{x}," if $DEBUG
p all[r] if $DEBUG
outout[x][y] = all[r]
guess = -1
found = 1
end
end
end
end
guess = -1
if found == 0
#if solved
solution = "solution "
outout.flatten.each do | one |
solution << one
end
p solution if $DEBUG
if /_/ =~ solution
#unsolved, guess
guess = rand(9)
p guess if $DEBUG
if back == [[],[],[],[],[],[],[],[],[]]
0.upto(8) do | i |
0.upto(8) do | j |
back[i][j] = outout[i][j]
end
end
p "back outout: " if $DEBUG
pp back if $DEBUG
end
else
p "SOLUTION: #{solution}"
solved += 1
s.send(solution, solution.size)
p "Solved: #{solved}x!"
if solved == 100
2.times do
p s.recv(1024)
end