Replace your grid_check() function with:
sub grid_check {
my @f = grep { !$grid[$_] } 0 ..80;
unless (@f) {
return sudoku_print();
}
my @min = (1..9);
my $idx = 0;
for my $cntr (@f) {
my %p = map { $_ => undef } 1 .. 9;
foreach my $cell (@{$search{$cntr}}) {
delete $p{ $grid[$cell] };
}
my @v = keys %p;
if (@min >= @v) {
@min = @v;
$idx = $cntr;
}
}
foreach my $val ( @min ) {
$grid[$idx] = $val;
grid_check();
}
return $grid[$idx] = 0;
}
The problem? You were calculating waaaay too much for each iteration, particularly since you threw away most of it anyways. This much better represents what you were trying to do. The results? For the devilish one, I went from 37.XX seconds to 1.XX seconds on my Macbook Pro. It's actually faster than the other hard one (2.7X seconds for me). That just has to do with path selection. It could be sped up about another 5-10% with a couple little things here and there, but I think this is the major improvement.
My criteria for good software:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|