-
Notifications
You must be signed in to change notification settings - Fork 34
/
sudoku_solver.pl
executable file
·119 lines (93 loc) · 2.13 KB
/
sudoku_solver.pl
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
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 30 January 2017
# https://github.com/trizen
# Recursive brute-force Sudoku solver.
# See also:
# https://en.wikipedia.org/wiki/Sudoku
use 5.016;
use strict;
sub check {
my ($i, $j) = @_;
use integer;
my ($id, $im) = ($i / 9, $i % 9);
my ($jd, $jm) = ($j / 9, $j % 9);
$jd == $id && return 1;
$jm == $im && return 1;
$id / 3 == $jd / 3
and $jm / 3 == $im / 3;
}
my @lookup;
foreach my $i (0 .. 80) {
foreach my $j (0 .. 80) {
$lookup[$i][$j] = check($i, $j);
}
}
sub solve_sudoku {
my ($callback, @grid) = @_;
sub {
foreach my $i (0 .. 80) {
if (!$grid[$i]) {
my %t;
undef @t{@grid[grep { $lookup[$i][$_] } 0 .. 80]};
foreach my $k (1 .. 9) {
if (!exists $t{$k}) {
$grid[$i] = $k;
__SUB__->();
$grid[$i] = 0;
}
}
return;
}
}
$callback->(@grid);
}->();
}
#<<<
my @grid = qw(
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
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
);
@grid = qw(
0 0 0 8 0 1 0 0 0
0 0 0 0 0 0 0 4 3
5 0 0 0 0 0 0 0 0
0 0 0 0 7 0 8 0 0
0 0 0 0 0 0 1 0 0
0 2 0 0 3 0 0 0 0
6 0 0 0 0 0 0 7 5
0 0 3 4 0 0 0 0 0
0 0 0 2 0 0 6 0 0
) if 0;
@grid = qw(
8 0 0 0 0 0 0 0 0
0 0 3 6 0 0 0 0 0
0 7 0 0 9 0 2 0 0
0 5 0 0 0 7 0 0 0
0 0 0 0 4 5 7 0 0
0 0 0 1 0 0 0 3 0
0 0 1 0 0 0 0 6 8
0 0 8 5 0 0 0 1 0
0 9 0 0 0 0 4 0 0
) if 0;
#>>>
solve_sudoku(
sub {
say "Solution:";
my (@solution) = @_;
foreach my $i (0 .. $#solution) {
print "$solution[$i] ";
print " " if ($i + 1) % 3 == 0;
print "\n" if ($i + 1) % 9 == 0;
print "\n" if ($i + 1) % 27 == 0;
}
}, @grid
);