Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions dana/programs/sudoku.dana
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
def main

var board is int[9][9]

def printBoard: b as int[][9]
var i j is int
i := 0
loop:
if i < 9:
j := 0
loop:
if j < 9:
writeInteger: b[i][j]
if j < 8: writeString: " "
j := j + 1
else: break
writeString: "\n"
i := i + 1
else: break

def isSafe is byte: b as int[][9], row col num as int
var i j boxStartRow boxStartCol is int

# Row check
j := 0
loop:
if j < 9:
if b[row][j] = num: return: false
j := j + 1
else: break

# Column check
i := 0
loop:
if i < 9:
if b[i][col] = num: return: false
i := i + 1
else: break

# 3x3 box check
boxStartRow := (row / 3) * 3
boxStartCol := (col / 3) * 3
i := 0
loop:
if i < 3:
j := 0
loop:
if j < 3:
if b[boxStartRow + i][boxStartCol + j] = num: return: false
j := j + 1
else: break
i := i + 1
else: break

return: true

def findEmpty is byte: b as int[][9], rowRef colRef as ref int
var i j is int
i := 0
loop:
if i < 9:
j := 0
loop:
if j < 9:
if b[i][j] = 0:
rowRef := i
colRef := j
return: true
j := j + 1
else: break
i := i + 1
else: break
return: false

def solve is byte: b as int[][9]
var row col num is int
var hasEmpty is byte

hasEmpty := findEmpty(b, row, col)
if hasEmpty = false:
return: true

num := 1
loop:
if num <= 9:
if isSafe(b, row, col, num):
b[row][col] := num
if solve(b):
return: true
b[row][col] := 0 # backtrack
num := num + 1
else: break

return: false

# Read 9x9 grid (0 = empty)
var i j is int
i := 0
loop:
if i < 9:
j := 0
loop:
if j < 9:
board[i][j] := readInteger()
j := j + 1
else: break
i := i + 1
else: break

if solve(board):
printBoard: board
else:
writeString: "No solution\n"
9 changes: 9 additions & 0 deletions dana/programs/sudoku.input
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
5 3 0 0 7 0 0 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
9 changes: 9 additions & 0 deletions dana/programs/sudoku.result
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9