SudokuLua/sudoku/utils.lua

85 lines
1.7 KiB
Lua

local function table2string(t)
local myself = table2string
local l = {}
local n = 0
for k, v in pairs(t) do
n = n + 1
if type(v) == "table" then
l[n] = k .. ': ' .. myself(v)
elseif type(v) == "string" then
l[n] = k .. ': ' .. '"' .. v .. '"'
else
l[n] = k .. ': ' .. v
end
end
return "{" .. table.concat(l, ", ") .. "}"
end
local function find(array, element)
local index = 0
for i = 1, #array do
if array[i] == element then
index = i
break
end
end
return index
end
local function createEmptyBoard()
local b = {}
for i = 1, 9 do
b[i] = {}
for j = 1, 9 do
b[i][j] = 0
end
end
return b
end
local function cloneBoard(b)
local c = {}
for i = 1, 9 do
c[i] = {}
for j = 1, 9 do
c[i][j] = b[i][j]
end
end
return c
end
local function loadBoard(fn)
local boards = {}
local r = 0
local board = {}
for line in io.lines(fn) do
if line:gsub("%s+", "") == "" then
table.insert(boards, board)
board = {}
r = 0
else
r = r + 1
local c = 0
board[r] = {}
for item in line:gmatch("%w+") do
c = c + 1
board[r][c] = tonumber(item)
end
end
end
table.insert(boards, board)
return boards
end
local function showBoard(board)
for row = 1, 9 do
print(table.concat(board[row], " "))
end
end
return {
createEmptyBoard = createEmptyBoard,
cloneBoard = cloneBoard,
loadBoard = loadBoard,
}