permute.pl


#!/usr/bin/perl 

# permutations test (with iterators)
# by Mark Jason Dominus
# Cf. Higher Order Perl, p. 130
# (adaptation: emilbarton 2013)

# modules:
######################################################################
use strict;
use warnings FATAL => "all";
use sigtrap 'handler' => \&inthandler, 'INT';

# global vars:
######################################################################
our $Got_sigint = 0;
our @Items;
our $N = 0;
# args
######################################################################
if ((@ARGV)== 0 || $ARGV[0] =~ /help|usage/){ &usage() };
my $it = permute(split(//,$ARGV[0]));
$N = $ARGV[1] if ($ARGV[1]);
while (my @p = $it->()) {
  print "@p $N\n";
  $Got_sigint && interrupt();
};

# subroutines
######################################################################

## permute:
sub permute {
 @Items = @_;
 return sub {
    $N++, return @Items if $N==0;
    my $i;
    my $p = $N;
    for ($i=1; $i<=@Items && $p%$i==0; $i++) {
      $p /= $i;
    }
    my $d = $p % $i;
    my $j = @Items - $i;
    return if $j < 0;
    @Items[$j+1..$#Items] = reverse @Items[$j+1..$#Items];
    @Items[$j,$j+$d] = @Items[$j+$d,$j];
    $N++;
    return @Items;
 };
}


## sigint handler:
sub inthandler { $Got_sigint = 1; }

## interrupt:
sub interrupt { 
  my $items = join '',@Items;
  die("interruption: $items $N\n");
}


## usage:
sub usage {
  my $data;
  while (<DATA>) { $data .= $_ };
  die "Usage:\n$data";
} ## END usage()

__DATA__

This program can be used to compute a full set of permutations. 
It can be interrupted by SIGINT provided that when restarted
it is fed with the last permutation output and the last index number
(these are shown in case of interruption).

Try:

  ./permute "01234567"

then press ctl-C and restart where it left off:

  ./permute-6.pl "73206514" 37703


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s