数独 RUBY 算法、baltctf-2013-sudoku

这篇博客介绍了将牛人的Python数独算法转换为Ruby实现的过程,包括数独的解决和生成算法。链接指向了原作者的详细文章。
摘要由CSDN通过智能技术生成

根据牛人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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值