Last active
April 14, 2017 04:56
-
-
Save possen/b865402e2d70b6ed3b945b93c6b33823 to your computer and use it in GitHub Desktop.
Validates a sudoku puzzle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func validateSudoku(array : [Int]) -> Bool { | |
let width = 9 | |
func valueAtPos(x: Int, y: Int, array: [Int]) -> Int { | |
return array[y * width + x] | |
} | |
func validateGroup(array:[Int]) -> Bool { | |
var allThereSet = Set<Int>() | |
array.map { allThereSet.insert($0) } | |
return allThereSet.count == 9 | |
} | |
for y in 0..<9 { | |
if !validateGroup(array: (0..<9).map { valueAtPos(x: $0, y: y, array: array)}) { | |
return false | |
} | |
} | |
for x in 0..<9 { | |
if !validateGroup(array: (0..<9).map { valueAtPos(x: x, y: $0, array: array)}) { | |
return false | |
} | |
} | |
for y in 0..<3 { | |
let first = (0..<3).map { valueAtPos(x: $0 * 1, y: y * 1, array: array)} | |
let second = (0..<3).map { valueAtPos(x: $0 * 2, y: y * 2, array: array)} | |
let third = (0..<3).map { valueAtPos(x: $0 * 3, y: y * 3, array: array)} | |
if validateGroup(array: first + second + third) { | |
return false | |
} | |
} | |
return true | |
} | |
assert(!validateSudoku(array:Array( | |
[[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9], | |
[1,2,3,4,5,6,7,8,9]].joined()))) | |
assert(validateSudoku(array:Array( | |
[[5,1,3,6,8,7,2,4,9], | |
[8,4,9,5,2,1,6,3,7], | |
[2,6,7,3,4,9,5,8,1], | |
[1,5,8,4,6,3,9,7,2], | |
[9,7,4,2,1,8,3,6,5], | |
[3,2,6,7,9,5,4,1,8], | |
[7,8,2,9,3,4,1,5,6], | |
[6,3,5,1,7,2,8,9,4], | |
[4,9,1,8,5,6,7,2,3]].joined()))) | |
assert(!validateSudoku(array:Array( | |
[[5,1,3,6,8,7,2,4,9], | |
[8,4,9,5,2,1,6,3,7], | |
[2,6,7,3,4,8,5,9,1], | |
[1,5,8,4,6,3,9,7,2], | |
[9,7,4,2,1,8,3,6,5], | |
[3,2,6,7,9,5,4,1,8], | |
[7,8,2,9,3,4,1,5,6], | |
[6,3,5,1,7,2,8,9,4], | |
[4,9,1,8,5,6,7,2,3]].joined()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment