Permutation Generator

This little program uses currying to create a nested function reference that prints out a table with all possible permutations of the @states array in as many columns as you like.

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';

## Scott Wiersdorf
## Created: Sat Aug 18 14:29:03 MDT 2012

## permutation/truth table generator

my $inputs = shift @ARGV || 3;  ## table columns
my @states = ('T', 'F', '-');   ## possible states

my $func = sub { say join "\t" => @_ };
for (1..$inputs) {
    $func = loop_maker($func);
}
$func->();

exit;

sub loop_maker {
    my $inner = shift;

    return sub {
        for my $state ( @states ) {
            $inner->(@_, $state);
        }
    };
}

The output with an argument of ‘2’ looks like:

1
2
3
4
5
6
7
8
9
T	T
T	F
T	-
F	T
F	F
F	-
-	T
-	F
-	-

while an argument of ‘3’ yields:

 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
T	T	T
T	T	F
T	T	-
T	F	T
T	F	F
T	F	-
T	-	T
T	-	F
T	-	-
F	T	T
F	T	F
F	T	-
F	F	T
F	F	F
F	F	-
F	-	T
F	-	F
F	-	-
-	T	T
-	T	F
-	T	-
-	F	T
-	F	F
-	F	-
-	-	T
-	-	F
-	-	-

Last modified on 2012-08-24