File: Permute.plx

package info (click to toggle)
libalgorithm-loops-perl 1.032-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 208 kB
  • sloc: perl: 455; makefile: 2
file content (68 lines) | stat: -rw-r--r-- 1,631 bytes parent folder | download
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
#!/usr/bin/perl -w
use strict;

use Algorithm::Loops qw( NextPermute NextPermuteNum );

Main( @ARGV );
exit 0;


sub Main {
    my @tokens= @_;
    my $noSort= 0;
    my $numComp= 0;
    while(  1 < @tokens  &&  $tokens[0] =~ /^-[^-]/  ) {
        ( my $flag= shift @tokens ) =~ s/^-//;
        while(  '' ne $flag  ) {
            if(  $flag =~ s/^s//  ) {
                $noSort= 1;
            } elsif(  $flag =~ s/^n//  ) {
                $numComp= 1;
            } else {
                die "$0: Unknown command-line option (-$flag).\n";
            }
        }
    }
    if(  0 == @tokens  ) {
        die "Usage: $0 [-s] word\n",
            "   or: $0 [-sn] t o k e n s\n",
            "Prints all unique permutations of the letters or words given.\n",
            "-s prevents the initial sorting of the letters/words.\n",
            "-n compares words as numbers.\n";
    } elsif(  1 == @tokens  ) {
        @tokens= $tokens[0] =~ /(.)/gs;
        $"= "";
    }

    #Sample use:
    my $cnt= 0;

    if(  $noSort  ) {

        if(  $numComp  ) {
            undef &NextPermute;
            *NextPermute= \&NextPermuteNum;
        }

        my $start= "@tokens";
        do {
            print ++$cnt, ": @tokens\n";
            NextPermute(@tokens);
        } while(  $start ne "@tokens"  );

    } elsif(  $numComp  ) {

        @tokens= sort {$a<=>$b} @tokens;
        do {
            print ++$cnt, ": @tokens\n";
        } while(  NextPermuteNum(@tokens)  );

    } else {

        @tokens= sort @tokens;
        do {
            print ++$cnt, ": @tokens\n";
        } while(  NextPermute(@tokens)  );

    }
}