-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sudoku.ps1
110 lines (93 loc) · 2.56 KB
/
Sudoku.ps1
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
$global:board = @(
@(0,0,0, 0,3,0, 0,0,0),
@(0,0,1, 0,7,6, 9,4,0),
@(0,8,0, 9,0,0, 0,0,0),
@(0,4,0, 0,0,1, 0,0,0),
@(0,2,8, 0,9,0, 0,0,0),
@(0,0,0, 0,0,0, 1,6,0),
@(7,0,0, 8,0,0, 0,0,0),
@(0,0,0, 0,0,0, 4,0,2),
@(0,9,0, 0,1,0, 3,0,0)
)
function print_board {
foreach ($i in 0..8) {
if ($i % 3 -eq 0 -and $i -ne 0) {
Write-Host "- - - - - - - - - - -"
}
foreach ($j in 0..8) {
if ($j % 3 -eq 0 -and $j -ne 0) {
Write-Host "| " -NoNewline
}
if ($j -eq 8) {
Write-Host $global:board[$i][$j]
}
else {
Write-Host ([string]$global:board[$i][$j] + " ") -NoNewline
}
}
}
}
function find_empty {
foreach ($i in 0..8) {
foreach ($j in 0..8) {
if ($global:board[$i][$j] -eq 0) {
return $i, $j # row, col
}
}
}
return $null
}
function valid($num, $pos) {
# Check row
foreach ($i in 0..8) {
if ($global:board[$pos[0]][$i] -eq $num -and $pos[1] -ne $i) {
return $False
}
}
# Check column
foreach ($i in 0..8) {
if ($global:board[$i][$pos[1]] -eq $num -and $pos[0] -ne $i) {
return $False
}
}
# Check box
$box_x = [math]::floor($pos[1] / 3)
$box_y = [math]::floor($pos[0] / 3)
foreach ($i in ($box_y*3)..($box_y*3 + 2)) {
foreach ($j in ($box_x * 3)..($box_x*3 + 2)) {
if ($global:board[$i][$j] -eq $num -and @($i,$j) -ne $pos) {
return $False
}
}
}
return $True
}
function solve {
$find = find_empty
if (-not $find) {
return $True
}
else {
$row, $col = $find
#Write-Progress -Activity "Solving..." -CurrentOperation "Row: $($row+1), Col: $($col+1)" -PercentComplete ([math]::round($row*$col/64*100))
#[Console]::Write("`rSolving... Row: $($row+1), Col: $($col+1)")
}
foreach ($i in 1..9) {
if (valid $i @($row, $col)) {
$global:board[$row][$col] = $i
#print_board
if (solve) {
return $True
}
$global:board[$row][$col] = 0
}
}
return $False
}
print_board
$time = Measure-Command {solve}
Write-Host ""
Write-Host "Seconds to Solve: $($time.TotalSeconds)"
Write-Host ""
Write-Host "_____________________"
print_board