117 lines
3.0 KiB
Lua
117 lines
3.0 KiB
Lua
local function checkCT(ct)
|
|
local r = {}
|
|
for i = 1, 8 do
|
|
for j = i+1, 9 do
|
|
if ct[i] == ct[j] and ct[i] ~= 0 then
|
|
table.insert(r, {i, j})
|
|
end
|
|
end
|
|
end
|
|
if #r > 0 then return false, r end
|
|
return true
|
|
end
|
|
|
|
local function findThisTable(this, that)
|
|
for i = 1, #that do
|
|
if #that[i] == #this then
|
|
local flag = true
|
|
for j = 1, #this do
|
|
if this[j] ~= that[i][j] then flag = false; break end
|
|
end
|
|
if flag then return true, i end
|
|
end
|
|
end
|
|
return false
|
|
end
|
|
|
|
function check(board)
|
|
local rr = {}
|
|
for x = 1, 9 do
|
|
local ct = {}
|
|
for y = 1, 9 do
|
|
ct[y] = board[x][y]
|
|
end
|
|
local ok, r = checkCT(ct)
|
|
if not ok then
|
|
for _, p in ipairs(r) do
|
|
local t = {x, p[1], x, p[2], board[x][p[1]]}
|
|
if not findThisTable(t, rr) then
|
|
table.insert(rr, t)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
for y = 1, 9 do
|
|
local ct = {}
|
|
for x = 1, 9 do
|
|
ct[x] = board[x][y]
|
|
end
|
|
local ok, r = checkCT(ct)
|
|
if not ok then
|
|
for _, p in ipairs(r) do
|
|
local t = {p[1], y, p[2], y, board[p[1]][y]}
|
|
if not findThisTable(t, rr) then
|
|
table.insert(rr, t)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
for i = 0, 2 do
|
|
for j = 0, 2 do
|
|
local ct = {}
|
|
for x = 1, 3 do
|
|
for y = 1, 3 do
|
|
ct[(x-1)*3+y] = board[x+i*3][y+j*3]
|
|
end
|
|
end
|
|
local ok, r = checkCT(ct)
|
|
if not ok then
|
|
for _, p in ipairs(r) do
|
|
local x1 = ((p[1] - 1) // 3 + 1) + i * 3
|
|
local y1 = ((p[1] - 1) % 3 + 1) + j * 3
|
|
local x2 = ((p[2] - 1) // 3 + 1) + i * 3
|
|
local y2 = ((p[2] - 1) % 3 + 1) + j * 3
|
|
local t = {x1, y1, x2, y2, board[x1][y1]}
|
|
if not findThisTable(t, rr) then
|
|
table.insert(rr, t)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
if #rr > 0 then
|
|
return false, rr
|
|
end
|
|
return true
|
|
end
|
|
|
|
function checkSolved(board)
|
|
local r = {}
|
|
for i = 1, 9 do
|
|
for j = 1, 9 do
|
|
if board[i][j] < 1 or board[i][j] > 9 then
|
|
table.insert(r, {i, j, board[i][j]})
|
|
end
|
|
end
|
|
end
|
|
local ok, rr = check(board)
|
|
if #r > 0 or (rr and #rr > 0) then
|
|
return false, r, rr
|
|
end
|
|
return true
|
|
end
|
|
|
|
function pcheck(board)
|
|
local ok, r, rr = checkSolved(board)
|
|
if ok then
|
|
print("Board is solved!")
|
|
return
|
|
end
|
|
for _, p in ipairs(r) do
|
|
print(S("(%d, %d) = %d", unpack(p)))
|
|
end
|
|
for _, p in ipairs(rr) do
|
|
print(S("(%d, %d) = (%d, %d) = %d", unpack(p)))
|
|
end
|
|
end
|