diff options
| author | drbaggy <js5@sanger.ac.uk> | 2021-10-14 05:35:14 +0100 |
|---|---|---|
| committer | drbaggy <js5@sanger.ac.uk> | 2021-10-14 05:35:14 +0100 |
| commit | 814c3433d9062abaaedbcd217d332aca019b257a (patch) | |
| tree | 4dcef049fb0f549bc698d75dc9c10a349d52cdc1 | |
| parent | aaded2bab8eac9197a35818fe0a0576467894f99 (diff) | |
| download | perlweeklychallenge-club-814c3433d9062abaaedbcd217d332aca019b257a.tar.gz perlweeklychallenge-club-814c3433d9062abaaedbcd217d332aca019b257a.tar.bz2 perlweeklychallenge-club-814c3433d9062abaaedbcd217d332aca019b257a.zip | |
use slice for both swaps
| -rw-r--r-- | challenge-134/james-smith/perl/ch-1.pl | 37 |
1 files changed, 20 insertions, 17 deletions
diff --git a/challenge-134/james-smith/perl/ch-1.pl b/challenge-134/james-smith/perl/ch-1.pl index d18ca48222..665acde010 100644 --- a/challenge-134/james-smith/perl/ch-1.pl +++ b/challenge-134/james-smith/perl/ch-1.pl @@ -8,30 +8,33 @@ use Test::More; use Benchmark qw(cmpthese timethis); use Data::Dumper qw(Dumper); -my $S = 10; -my @s = (1,0,2..$S-1); ## Cheat we jump into the first pemutation which - ## doesn't start with a "0" 1023456789 - avoids - ## us having to check for a leading 0... -my $count=5; - -do { - say @s; -} while next_perm && --$count; - +my @s = (0,reverse 1..9); ## Cheat we start with the last perumation + ## starting with 0 - 0987654321 + ## Saves us looping through the first + ## combinations checking for number starting + ## with non-zero (362880 combinations) +my $count = @ARGV ? $ARGV[0] : 5; sub next_perm { - my($i,$j,$p); + my( $i, $j ); + ## Find largest index for which Si+1 > Si - ( $s[$_] < $s[$_+1] ) && ( $i=$_ ) foreach 0 .. $S-2; ## Find i + ( $s[$_] < $s[$_+1] ) && ( $i = $_ ) foreach 0 .. @s-2; ## Find i return unless defined $i; ## Got to the end of the list of permutations ## Find latest index for which Sj > Si for j>i - ( $s[$i] < $s[$_] ) && ( $j=$_ ) foreach $i+1 .. $S-1; ## Find j + ( $s[$i] < $s[$_] ) && ( $j = $_ ) foreach $i+1 .. @s-1; ## Find j + + ## Flip ith & jth elements..., then all numbers greater than i.. + @s[ $i, $j ] = @s[ $j, $i ]; + @s[ $i+1 .. @s-1 ] = @s[ reverse $i+1 .. @s-1 ]; - ## Flip i & jth elements..., then all numbers greater than i.. - ( $s[$i], $s[$j] ) = ( $s[$j], $s[$i] ); ## Flip numbers over... - @s[ $i+1 .. $S-1 ] = @s[ reverse $i+1 .. $S-1 ]; ## Flip remaining list - return 1; + return 1; ## Return true to say can continue... } + +say @s while next_perm && $count--; + + + |
