in reply to character generator

As an exercise, this is actually a good candidate for recursion (we have a recursion fever here these days): (I simplified the question a little bit, and assume we only want full length strings, strings that are formed by all characters in the set, so we can focus on recursion)

use Data::Dumper; use strict; use warnings; my @set = ('1', '2', '3'); my @strings = generate(@set); print Dumper(\@strings); sub generate { my @set = @_; my @strings; if ($#set == 0) { return ($set[0]); } else { for (0 .. $#set) { my @temp = @set; my $t = splice(@temp, $_, 1); push @strings, "$t$_" foreach (generate(@temp)); } return @strings; } }

Replies are listed 'Best First'.
Re^2: character generator
by pg (Canon) on Oct 24, 2004 at 20:00 UTC

    Actually can be easily modified to generate strings with a specified length (not just the full length):

    use Data::Dumper; use strict; use warnings; my @set = ('1', '2', '3', '4'); my $len = 3; #test shows that it is safe to specify len greater than s +et size, or equal to set size, or less than my @strings = generate($len, @set); print Dumper(\@strings); sub generate { my $len = shift; my @set = @_; my @strings; if ($#set == 0) { return ($set[0]); } else { if ($len == 1) { push @strings, "$_" foreach (@set); } else { for (0 .. $#set) { my @temp = @set; my $t = splice(@temp, $_, 1); push @strings, "$t$_" foreach (generate($len - 1, @temp)); } } return @strings; } }