-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.go
121 lines (104 loc) · 2.16 KB
/
sudoku.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
)
var board [][]int
func solve(board [][]int) [][]int {
var keyValue map[string]int
keyValue = map[string]int{}
var empty []map[string]int
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == 0 {
keyValue["row"] = i
keyValue["col"] = j
keyValue["val"] = 0
empty = append(empty, keyValue)
keyValue = map[string]int{}
}
}
}
for i := 0; i < len(empty); i++ {
row := empty[i]["row"]
col := empty[i]["col"]
val := empty[i]["val"]
for {
if val > 9 {
board[row][col] = 0
empty[i]["val"] = 0
i -= 2
break
}
if checkHorizontal(board[row], val) && checkVertical(col, val) && checkGrid(row, col, val) {
board[row][col] = val
empty[i]["val"] = val
break
} else {
val++
}
}
}
return board
}
func checkVertical(col, val int) bool {
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if j == col && board[i][j] == val {
return false
}
}
}
return true
}
func checkHorizontal(horizontalLine []int, val int) bool {
for i := 0; i < len(horizontalLine); i++ {
if horizontalLine[i] == val {
return false
}
}
return true
}
func checkGrid(startX, startY int, val int) bool {
x := (startX / 3) * 3
y := (startY / 3) * 3
for i := x; i <= (x + 2); i++ {
for j := y; j <= (y + 2); j++ {
if board[i][j] == val {
return false
}
}
}
return true
}
func generateMultiDimensionalSlice(uintArr []uint8) [][]int {
var responseArr [][]int
responseArr = [][]int{}
var counter int
for i := 0; i < 9; i++ {
var arrTemp []int
for j := 0; j < 9; j++ {
parsedInt, _ := strconv.Atoi(string(uintArr[counter]))
arrTemp = append(arrTemp, parsedInt)
counter++
}
responseArr = append(responseArr, arrTemp)
arrTemp = nil
}
return responseArr
}
func main() {
file, err := os.Open("text.txt")
if err != nil {
fmt.Println("err on", err)
}
parsedFile, err := ioutil.ReadAll(file)
board = generateMultiDimensionalSlice(parsedFile)
var solvedBoard [][]int
solvedBoard = solve(board)
for i := 0; i < len(solvedBoard); i++ {
fmt.Println(solvedBoard[i])
}
}