
KevinR
Veteran

Feb 22, 2006, 5:06 PM
Post #13 of 21
(1042 views)
|
|
Re: [cold_one] List generation
[In reply to]
|
Can't Post
|
|
Sorry, no IM. The code works fine for me:
use Permutor; my $string = 'ab12'; my $integer = 4; my $word = 'blue'; my @characters = split(//,$string); if(@characters > $integer) { print "Error: too many characters is string\n"; exit(0); } my $perm =new Permutor @characters; while (my @set = $perm->next) { print join ('',@set)."$word\n"; } and Permutor.pm in the cgi-bin with the above script:
package Permutor; use strict; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK); require Exporter; @ISA = qw(Exporter); @EXPORT = qw(); $VERSION = '0.022'; sub new { my $class = shift; my $items = [ @_ ]; bless [ $items, [ 0..$#$items ] ], $class; } sub reset { my $self = shift; my $items = $self->[0]; $self->[1] = [ 0..$#$items ]; 1; # No useful return value } sub peek { my $self = shift; my $items = $self->[0]; my $rv = $self->[1]; @$items[ @$rv ]; } sub next { my $self = shift; my $items = $self->[0]; my $rv = $self->[1]; # return value array return unless @$rv; my @next = @$rv; # The last N items in @next (for 1 <= N <= @next) are each # smaller than the one before. Move those into @tail. my @tail = pop @next; while (@next and $next[-1] > $tail[-1]) { push @tail, pop @next; } # Then there's one more. Right? if (defined(my $extra = pop @next)) { # The extra one exchanges with the next larger one in @tail my($place) = grep $extra < $tail[$_], 0..$#tail; ($extra, $tail[$place]) = ($tail[$place], $extra); # And the next order is what you get by assembling the three $self->[1] = [ @next, $extra, @tail ]; } else { # Guess that's all.... $self->[1] = []; } return @$items[ @$rv ]; } 1; prints:
ab12blue ab21blue a1b2blue a12bblue a2b1blue a21bblue ba12blue ba21blue b1a2blue b12ablue b2a1blue b21ablue 1ab2blue 1a2bblue 1ba2blue 1b2ablue 12abblue 12bablue 2ab1blue 2a1bblue 2ba1blue 2b1ablue 21abblue 21bablue -------------------------------------------------
|