-
Notifications
You must be signed in to change notification settings - Fork 0
/
permute.pl
executable file
·93 lines (78 loc) · 1.97 KB
/
permute.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/local/bin/perl5 -w
# Usage: permute $seq $length
# Author: Floyd Moore <[email protected]>
# Reference: Copied from permute code (mjd-permute) in Example 4-4 of the
# Perl Cookbook (page 126).
# Date: Tue May 23 10:21:58 MDT 2000
# Description:
# Create a sequence of numbers $length long and choosing the $seq from
# the available $length factorial sequences.
#
use strict;
use Getopt::Std;
use subs qw(usage n2pat n2perm pat2perm);
use vars qw($opt_s $opt_l $opt_m);
use vars qw($seq $length $max @list);
if ($#ARGV<0){
usage;
exit 1;
}
unless (&Getopt::Std::getopts('s:l:m:')) {
usage;
exit 1;
}
if (defined($opt_s)){
$seq = $opt_s;
} else {
usage
$seq = 0;
}
if (defined($opt_l)){
$length = $opt_l;
} else {
$length = 5;
}
$max=$length+1;
if (defined($opt_m)) {
$max=$opt_m;
if ($max > $length){ $max = $length+1; }
}
#print "Looking up $seq permuted index\n";
@list=n2perm($seq,$length-1);
@list=splice(@list, 0, $max);
print "@list\n";
#----------------------------------------------------
# usage
sub usage {
print "Usage: permute.pl -s <sequence number> [ -l <length> -m <max> ]\n";
print " Default is a length 5 and display the full sequence.\n";
}
#----------------------------------------------------
# n2pat($N, $len) : pruduce the $N-th pattern of length $len
sub n2pat {
my $i = 1;
my $N = shift;
my $len = shift;
my @pat;
while ($i <= $len + 1){
push @pat, $N % $i;
$N = int($N/$i);
$i++;
}
return @pat;
}
#----------------------------------------------------
# pat2perm(@pat) : turn pattern returnned by n2pat() into
# permutation of integers. XXX: splice is already O(N)
sub pat2perm {
my @pat = @_;
my @source = (0 .. $#pat);
my @perm;
push @perm, splice(@source, (pop @pat), 1) while @pat;
return @perm;
}
#----------------------------------------------------
# n2perm($N, $len) : generate the Nth permutation of $len objects
sub n2perm {
pat2perm(n2pat(@_));
}