Rename field to grid because it is more clear and add time spent to find the solution

This commit is contained in:
adrien 2022-03-02 00:15:57 +01:00
parent 1bc9ef6af2
commit fa7857a98e
Signed by: adrien
GPG Key ID: 4F17BEA67707AC21

27
main.go
View File

@ -1,8 +1,11 @@
package main
import "fmt"
import (
"fmt"
"time"
)
var field = [9][9]int{
var grid = [9][9]int{
{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},
@ -15,7 +18,7 @@ var field = [9][9]int{
}
func draw() {
for _, row := range field {
for _, row := range grid {
fmt.Println(row)
}
fmt.Println()
@ -29,7 +32,7 @@ func canPut(x int, y int, value int) bool {
func alreadyInVertical(x int, y int, value int) bool {
for i := range [9]int{} {
if field[i][x] == value {
if grid[i][x] == value {
return true
}
}
@ -38,7 +41,7 @@ func alreadyInVertical(x int, y int, value int) bool {
func alreadyInHorizontal(x int, y int, value int) bool {
for i := range [9]int{} {
if field[y][i] == value {
if grid[y][i] == value {
return true
}
}
@ -49,7 +52,7 @@ func alreadyInSquare(x int, y int, value int) bool {
sx, sy := int(x/3)*3, int(y/3)*3
for dy := range [3]int{} {
for dx := range [3]int{} {
if field[sy+dy][sx+dx] == value {
if grid[sy+dy][sx+dx] == value {
return true
}
}
@ -69,17 +72,17 @@ func solve(x int, y int) bool {
if y == 9 {
return true
}
if field[y][x] != 0 {
if grid[y][x] != 0 {
return solve(next(x, y))
} else {
for i := range [9]int{} {
var v = i + 1
if canPut(x, y, v) {
field[y][x] = v
grid[y][x] = v
if solve(next(x, y)) {
return true
}
field[y][x] = 0
grid[y][x] = 0
}
}
return false
@ -89,10 +92,12 @@ func solve(x int, y int) bool {
func main() {
fmt.Println("Grid to be completed:")
draw()
startSolving := time.Now()
if solve(0, 0) {
fmt.Println("I found a solution, see below")
stopSolving := time.Since(startSolving)
fmt.Printf("I found a solution (in %v):\n", stopSolving)
draw()
} else {
fmt.Println("I did not find a solution")
fmt.Println("I did not find a solution...")
}
}