<lang Perl>#!/usr/bin/perl
use integer;
use strict;
my @A = qw(
sub usage {
5 3 0 0 2 4 7 0 0
print "usage: $0 sudoku_file.txt\n";
0 0 2 0 0 0 8 0 0
exit;
1 0 0 7 0 3 9 0 2
}
0 0 8 0 7 2 0 4 9
usage() if grep { /^-+(?:h|help|usage|\?)$/ } @ARGV;
0 2 0 9 8 0 0 7 0
7 9 0 0 0 0 0 8 0
0 0 0 0 3 0 5 0 6
my $opened_file = 0;
9 6 0 0 1 0 3 0 0
0 5 0 6 9 0 0 1 0
);
ifsub (@ARGV)solve {
my $i;
$opened_file = 1 if sysopen FILE, shift @ARGV, 0;
foreach $i ( 0 .. 80 ) {
}
next if $A[$i];
my $sudoku%t = map {
$_ / 9 == $i / 9 ||
"53..247..
$_ % 9 == $i % 9 ||
..2...8..
$_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3
1..7.39.2
? $A[$_] : 0,
..8.72.49
1;
.2.98..7.
} 0 .. 80;
79.....8.
solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9;
.4..3.5.6
return $A[$i] = 0;
96..1.3..
.5.69..1."
unless $opened_file;
my $file;
if ($opened_file) {
my $i = 0;
while (defined($_ = <FILE>)) {
next if /^$/;
$file .= $_;
++$i;
last if $i == 9;
}
$i = 0;
}
foreach (@A) {
else {
print "-----+-----+-----\n" if !($i%27) && $i;
my $ref = \$sudoku;
print !($i%9) ? '': $i%3 ? ' ' : '|', $_;
print "\n" unless ++$i%9;
open my $fh, '<', $ref;
my $i = 0;
while (defined($_ = <$fh>)) {
next if /^$/;
++$i;
$file .= $_;
last if $i == 9;
}
close $fh;
}
close FILE if $opened_file;
$file =~ s/\n//g;
$file =~ s/[^1-9]/0/g;
my (@A) = split(//, $file, 0);
sub solve {
foreach my $i ( 0 .. 80 ) {
next if $A[$i];
my (%t) = map( {
$_ / 9 == $i / 9
|| $_ % 9 == $i % 9
|| $_ / 27 == $i / 27
&& $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0,
1;
} 0 .. 80 );
&solve( $A[$i] = $_ ) foreach ( grep { not $t{$_} } 1 .. 9 );
return $A[$i] = 0;
}
&print_sudoku;
}
solve();
sub print_sudoku {
my $sudoku = join(' ', @A);
$sudoku =~ s/([1-9 ]{17}) /$1\n/g;
$sudoku =~ s/([1-9 ]{5}) /$1 | /g;
my (@sudoku) = split(/\n/, $sudoku, 0);
my $n = 0;
foreach $_ (@sudoku) {
print ' ', '-' x 23, "\n" if $n =~ /^(?:0|3|6|9)$/;
print '| ', $_, " |\n";
++$n;
}
print ' ', '-' x 23, "\n";
exit 0;
}
</lang>
Output:
<pre>
<pre> -----------------------
| 5 3 9 | 8 2 4 | 7 6 1 |
| 6 7 2 | 1 5 9 | 8 3 4 |
| 1 8 4 | 7 6 3 | 9 5 2 |
-------------+-----+-----
| 3 1 8 | 5 7 2 | 6 4 9 |
| 4 2 5 | 9 8 6 | 1 7 3 |
| 7 9 6 | 3 4 1 | 2 8 5 |
-------------+-----+-----
| 8 4 1 | 2 3 7 | 5 9 6 |
| 9 6 7 | 4 1 5 | 3 2 8 |
| 2 5 3 | 6 9 8 | 4 1 7 |
</pre>
-----------------------</pre>
=={{header|PicoLisp}}==
|