Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- board = {}
- shell.run("delete console")
- local h = fs.open("console","a")
- function createEmptyBoard()
- for i = 1,4 do
- board[i] = {}
- for j = 1,4 do
- board[i][j] = {}
- board[i][j].num = 0
- board[i][j].exceptions = {}
- board[i][j].options = {}
- end
- end
- end
- function printBoard()
- for i=1,4 do
- for j=1,4 do
- term.setCursorPos(i,j)
- term.write(board[i][j].num)
- end
- end
- end
- --==Sudoku Functions==--
- function findEmpty()
- for y = 1,4 do
- for x = 1,4 do
- if board[x][y].num == 0 then
- return true,x,y
- end
- end
- end
- end
- local function findQuadrant(x,y)
- quadrant = {}
- quadrant.num = 0
- quadrant.x = 0
- quadrant.y = 0
- if x <= 2 then
- if y<=2 then
- quadrant.num = 1
- quadrant.x = 1
- quadrant.y = 1
- elseif y<=4 then
- quadrant.num = 3
- quadrant.x = 1
- quadrant.y = 3
- end
- elseif x<=4 then
- if y<=2 then
- quadrant.num = 2
- quadrant.x = 3
- quadrant.y = 1
- elseif y<=4 then
- quadrant.num = 4
- quadrant.x = 3
- quadrant.y = 3
- end
- end
- return quadrant
- end
- local function organizeOptions(x,y)
- for i=1,9 do
- board[x][y].options[i] = i
- end
- for i = 1,9 do
- for _,k in pairs(board[x][y].exceptions) do
- if i == k then
- board[x][y].options[i] = 0
- end
- end
- end
- end
- function findOptions(x,y)
- for i = 1,4 do
- if board[i][y].num ~= 0 then
- table.insert(board[x][y].exceptions,board[i][y].num)
- end
- if board[x][i].num ~= 0 then
- table.insert(board[x][y].exceptions,board[x][i].num)
- end
- end
- quadrant = findQuadrant(x,y)
- for i = quadrant.x,quadrant.x+1 do
- for j = quadrant.y,quadrant.y+1 do
- if board[i][j].num ~= 0 then
- table.insert(board[x][y].exceptions,board[i][j].num)
- end
- end
- end
- organizeOptions(x,y)
- end
- function recursive()
- unsolved,x,y = findEmpty()
- if unsolved then
- findOptions(x,y)
- for _,v in pairs(board[x][y].options) do
- if v~= 0 then
- board[x][y].num = v
- recursive()
- end
- end
- board[x][y].num = 0
- else
- printBoard()
- print("FINISHED :D")
- error()
- end
- end
- --==Debug Functions==--
- function fillRand()
- for i=1,4 do
- for j=1,4 do
- board[i][j].num = math.random(1,9)
- end
- end
- end
- function tab(t)
- for i,v in pairs(t) do
- if type(v) == "table" then
- tab(v)
- else
- print("i: ",i," v: ",v)
- end
- end
- end
- function log(s)
- if type(s) == "string" then
- h.writeLine(s)
- else
- for i,v in pairs(s) do
- h.write("i: ")
- h.write(i)
- h.write(" v: ")
- h.writeLine(v)
- end
- end
- h.flush()
- end
- createEmptyBoard()
- term.clear()
- board[1][1].num = 8
- board[2][1].num = 3
- board[3][2].num = 6
- board[4][2].num = 2
- board[2][3].num = 1
- board[4][3].num = 5
- board[4][4].num = 4
- --fillRand()
- recursive()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement