Skip to content

Instantly share code, notes, and snippets.

@gugod
Last active June 10, 2016 19:24
Show Gist options
  • Save gugod/eb01975c495d2d226a9a0c3abe78c2ee to your computer and use it in GitHub Desktop.
Save gugod/eb01975c495d2d226a9a0c3abe78c2ee to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use v5.18;
sub next_permutation {
my $p = shift;
my $l = @$p;
my $i;
for ($i = $l-1; $i > 0; $i--) {
last if $p->[$i] > $p->[$i-1];
}
$i--;
return 0 if $i < 0;
my @q = @$p;
my $j = $i+1;
for ($i+1 ... $l-1) {
next unless $p->[$_] > $p->[$i];
$j = $_ if $p->[$_] < $p->[$j];
}
@q[$i, $j] = @$p[$j, $i];
@q[$i+1 ... $l-1] = reverse( @q[$i+1 ... $l-1] );
@$p = @q;
return 1;
}
my @p = (0, 1, 2, 3, 4);
say join " ", @p;
while(1) {
if ( next_permutation(\@p) ) {
say join " ", @p;
} else {
last;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment