Skip to content

Instantly share code, notes, and snippets.

@j2labs
Last active October 9, 2017 17:25
Show Gist options
  • Save j2labs/f09b6a2d0cf41b15d797 to your computer and use it in GitHub Desktop.
Save j2labs/f09b6a2d0cf41b15d797 to your computer and use it in GitHub Desktop.
Swift sudoku solver
#!/usr/bin/env xcrun swift
class Board {
let b = -1 // a blank, written as b so the board below looks nice
let hborder = "-------------\n"
let vborder = "|"
let width = 9
let height = 9
var board: [[Int]]
init() {
board = [[b, b, b, b, b, 5, b, 1, b],
[b, b, b, b, 1, b, 6, b, 9],
[6, b, 1, 9, 3, b, b, b, 4],
[5, b, 2, 6, 9, b, b, 7, b],
[b, 3, b, 7, b, 1, b, 9, b],
[b, 9, b, b, 4, 8, 1, b, 5],
[1, b, b, b, 7, 9, 8, b, 2],
[9, b, 3, b, 8, b, b, b, b],
[b, 7, b, 1, b, b, b, 4, b]]
}
func to_string() -> String {
var s = ""
for i in 0..<height {
if i == 0 {
s += hborder
}
for j in 0..<width {
if j == 0 {
s += vborder
}
var current = board[i][j]
if current == -1 {
s += " "
}
else {
s += String(board[i][j])
}
if j % 3 == 2 {
s += vborder
}
}
s += "\n"
if (i % 3) == 2 {
s += hborder
}
}
return s
}
}
func solve_init(board: Board) -> Bool {
return solve(0, 0, board)
}
func solve(var row: Int, var col: Int, board: Board) -> Bool {
// Are we finished?
if row == board.height {
row = 0
col += 1
if col == board.width {
return true
}
}
// Skip if we're on a filled spot
if board.board[row][col] != board.b {
return solve(row+1, col, board)
}
// TRY TRY TRY
for val in 1..<10 {
if okPlacement(row, col, board, val) {
board.board[row][col] = val
if solve(row+1, col, board) {
return true
}
}
}
board.board[row][col] = board.b
return false
}
func okPlacement(row: Int, col: Int, board: Board, attempt: Int) -> Bool {
// Check row
for check in 0..<board.width {
if attempt == board.board[check][col] {
return false
}
}
// Check column
for check in 0..<board.height {
if attempt == board.board[row][check] {
return false
}
}
let xBox = row / 3 * 3
let yBox = col / 3 * 3
for x in 0..<3 {
for y in 0..<3 {
if attempt == board.board[(xBox + x)][(yBox + y)] {
return false
}
}
}
return true
}
var b = Board()
println(b.to_string())
solve_init(b)
println(b.to_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment