Skip to content

Instantly share code, notes, and snippets.

@jezinka

jezinka/SudokuBacktracking.groovy Secret

Last active May 24, 2020
Embed
What would you like to do?
validation
private boolean isValid() {
boolean right = true
board.each { row ->
if (row.findAll { it != 0 }.countBy { it }.any { k, v -> v != 1 }) {
right = false
}
}
(0..this.board.size() - 1).each { colNum ->
List<Integer> column = board.collect { it[colNum] }
if (column.findAll { it != 0 }.countBy { it }.any { k, v -> v != 1 }) {
right = false
}
}
Map<String, List<Integer>> squares = [:]
board.eachWithIndex { List<Integer> row, int i ->
row.eachWithIndex { int entry, int j ->
String key = findSquare(i, j)
if (!squares.containsKey(key)) {
squares[key] = [entry]
} else {
squares[key] << entry
}
}
}
squares.values().each { square ->
if (square.findAll { it != 0 }.countBy { it }.any { k, v -> v != 1 }) {
right = false
}
}
return right
}
private String findSquare(int i, int j) {
int squareCount = Math.sqrt(board.size()) as Integer
return "${Math.floor(i / squareCount)}${Math.floor(j / squareCount)}".toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment