in reply to Generating sequence of words
#!/usr/bin/perl -w use strict; use vars qw(@array); @array = qw( hey foo bar ); combinations(scalar(@array), [], \@array); sub combinations { my($count,$sofar,$remaining)=@_; if (!$count) { print join(" ",@$sofar),"\n"; return; } combinations($count-1,[@$sofar],[@$remaining]); foreach my $r (@$remaining) { combinations($count-1,[@$sofar, $r], [@$remaining]); } }
It's a recursive technique that selects all possibilities for each position in the output array, including leaving it empty. Each call to combinations iterates through all possible values for the current position, then calls itself to determine what can go in the subsequent positions.
A possible bug is that it outputs all of ('foo','',''), ('','foo',''), and ('','','foo'), even though all are the single word 'foo'. If that's a problem, you can store the combinations into an array then filter out duplicates.
|
|---|