diff options
| author | drbaggy <js5@sanger.ac.uk> | 2021-06-21 22:36:53 +0100 |
|---|---|---|
| committer | drbaggy <js5@sanger.ac.uk> | 2021-06-21 22:36:53 +0100 |
| commit | e6d311d1d550ec6fc1f118ad4906474e398defd7 (patch) | |
| tree | 2212e6d2893b73125447dcbcf3deb64cb2de5717 | |
| parent | 6e0ca6979d2318cc8ac0b3d127e7588559a79c84 (diff) | |
| download | perlweeklychallenge-club-e6d311d1d550ec6fc1f118ad4906474e398defd7.tar.gz perlweeklychallenge-club-e6d311d1d550ec6fc1f118ad4906474e398defd7.tar.bz2 perlweeklychallenge-club-e6d311d1d550ec6fc1f118ad4906474e398defd7.zip | |
3 x speed up by moving IF
| -rw-r--r-- | challenge-118/james-smith/perl/ch-2.pl | 16 |
1 files changed, 8 insertions, 8 deletions
diff --git a/challenge-118/james-smith/perl/ch-2.pl b/challenge-118/james-smith/perl/ch-2.pl index 4045d50ac0..a9d91e32f4 100644 --- a/challenge-118/james-smith/perl/ch-2.pl +++ b/challenge-118/james-smith/perl/ch-2.pl @@ -10,8 +10,8 @@ use Data::Dumper qw(Dumper); my @dir = ([-2,1],[2,1],[-2,-1],[2,-1],[-1,2],[1,2],[-1,-2],[1,-2]); -my( $SIZE, @treasures ) = ( 8, qw(a2 b1 b2 b3 c4 e6) ); -my( $sol, $best_len, $best_rt ) = ( 0, $SIZE*$SIZE + 1 ); +my @treasures = qw(a2 b1 b2 b3 c4 e6); +my( $sol, $best_len, $best_rt ) = ( 0, 65 ); $sol |= 1 << 8 * (substr $_,1) - 105 + ord $_ foreach @treasures; ## We convert the "letter/digit" co-ordinates into a square number @@ -31,29 +31,29 @@ $sol |= 1 << 8 * (substr $_,1) - 105 + ord $_ foreach @treasures; ## to bytes using chr/ord. -walk( 0, $SIZE-1, 0, '' ); ## Walk the tree starting from top-left +walk( 0, 7, 0, q() ); ## Walk the tree starting from top-left -say length $best_rt, ' - ', show_rt( $best_rt ); ## Show best rt +say length $best_rt, q( - ), show_rt( $best_rt ); ## Show best route sub walk { my( $x, $y, $seen, $rt ) = @_; ## Skip if the new "chain" will be bigger than the best chain so far ## If we have fallen off the sides of the board ## Or if we have already visited the square. - return if $best_len <= length $rt - || $x < 0 || $y < 0 || $x >= $SIZE || $y >= $SIZE - || $seen & ( my $v = 1 << (my $t = 8*$y + $x ) ); + return if $x < 0 || $y < 0 || $x > 7 || $y > 7 + || $seen & ( my $v = 1 << ( my $t = 8*$y + $x ) ); $seen |= $v; $rt .= chr $t; return ($best_rt,$best_len) = ($rt,-1+length $rt) if ($seen & $sol) == $sol; + return if $best_len <= length $rt; walk( $x + $_->[0], $y + $_->[1], $seen, $rt ) foreach @dir; } sub show_rt { my %t = map { $_ => 1 } @treasures; return join q(), - map { sprintf ' %s%s', exists$t{$_}?'*':' ', $_ } + map { sprintf ' %s%s', exists$t{$_}?q(*):q( ), $_ } map { chr( ($_&7) + 97 ).(1 + ($_>>3)) } map { ord $_ } split m{}, shift; |
