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
my @typeset = ('P', 'K', 'L', 'G');
my $length = 10;
my @lchain = ();
strangemultiset($length, \@typeset, \@lchain);
exit 0;
sub strangemultiset
{
my $len=$_[0];
my @types=@{$_[1]};
my @chain=@{$_[2]};
my $ltype=shift(@types);
my $var=$len - scalar(@chain) - scalar(@types);
for(my $iter=1; $iter<=$var; ++$iter)
{
push(@chain, $ltype);
if (scalar(@types) == 0)
{
if (scalar(@chain) == $len)
{ # we have a valid set, print it.
print join('.', @chain), "\n";
}
}
else
{
strangemultiset($len, \@types, \@chain);
}
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
my @typeset = qw(P K L G); my $length = 10; strangemultiset($length, \@typeset, 0, ''); sub strangemultiset { my ($len, $set, $start, $string) = @_; if ($len == 0) { print "$string\n"; return; } my $max = $len - @$set + $start + 1; my $min = $start == @$set - 1 ? $max : 1; for my $currentLen ($min..$max) { strangemultiset($len-$currentLen, $set, $start + 1, $string . ($set->[$start] x $currentLen)); } }
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
#!/usr/bin/perl use strict; use warnings; my @typeset = qw(P K L G); my $length = 10; strangemultiset(\@typeset,$length); sub strangemultiset { my ($typeset,$length)=@_; my @lst=map{1}@$typeset; while(@lst <= @$typeset) { my $len=0; $len+=$_ for(@lst); if($len >= $length) { my @out; push(@out, ($typeset[$_]) x $lst[$_]) for(0..$#$typeset); print join('.',@out)."\n"; } $lst[0]++; for my $p (0..$#lst) { my $left = 0; $left += $_ for(@lst); if($left > $length) { $lst[$p] = 1; $lst[$p+1] ++ ; } } } }
2013-10-06T17:40:32 ariserBeweist das, dass rekursive Algorithmen schnell sind? Und wenn ja, warum eigentlich?