in reply to The 15 Puzzle
I'm proud of it, so give a nonexpert a break. That said, any constructive feedback would be most welcome.
For a non-expert it's pretty good. There are a few inconsistencies but I'm sure you can spot those and polish them out in due course. The only bit which really grates is this:
# GENERATE THE BOARD my @board; my $inversions; GEN: @board = (0, shuffle(1..15)); # @board = (1,0,2..15); # for testing $inversions = 0; for my $a(1..15) { for my $b(1..15) { ++$inversions if($a<$b and $board[$a]>$board[$b]) } } goto GEN if $inversions % 2;
There's really no need for a goto in here. You are clearly aware of conditional loops in Perl as you've used them elsewhere in this script. Let's re-write this to avoid the goto, avoid the special variables $a and $b and make it marginally more efficient by only checking the triangle rather than the square.
my @board; my $inversions = 1; while ($inversions % 2) { @board = (0, shuffle(1..15)); $inversions = 0; for my $x (1 .. 15) { for my $y ($x + 1 .. 15) { $inversions++ if $board[$x] > $board[$y]; } } }
Hopefully I have not altered the logic of your board construction at all, just tweaked the code to do the same thing but in a slightly more Perlish way. For completeness I would probably put this in its own subroutine and just call my @board = setup_board() in the main script as the setup is entirely independent of the rest of the script.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: The 15 Puzzle
by msh210 (Monk) on Jun 10, 2020 at 20:48 UTC | |
by hippo (Bishop) on Jun 10, 2020 at 21:35 UTC | |
Re^2: The 15 Puzzle
by msh210 (Monk) on Jun 10, 2020 at 09:55 UTC |