in reply to Searching for a Permutation Algorithm for nPr where n != r
I suggest a recursive approach. While this might not be the fastest one, it is easy to write:
sub vari { my ($set,$num,$act)= @_; my(%h,$rec,@s); $h{$_}= 0 for @$set; $rec= sub { $_[0] or return $act->(@s); $h{$_} or do { local $h{$_}= 1; push @s, $_; $rec->($_[0]-1); pop @s; } for @$set; }; $rec->($num); } vari [qw{a b c d e f g}], 3, sub { print join(" ",@_), $/; };
Update: changed code to be stable.
|
|---|