in reply to Please help me understand this permutation sub?
I find it helps to unpack this sort of code and figure out names for intermediate variables. It also helps to add a little white space.
use strict; use warnings; my @input = (qw/a b c d/); permutation('', @input); sub permutation { my ($perm, @set) = @_; if (!@set) { print "$perm\n"; return; } for my $partition (0 .. $#set) { my $firstEnd = $partition - 1; my $lastStart = $partition + 1; my @newSet = @set[0 .. $firstEnd]; push @newSet, @set[$lastStart .. $#set]; permutation($perm . $set[$partition], @newSet); } }
This is a recursive algorithm (the function calls itself). With recursion there are two important parts - the recursion process and the stop recursing condition. The stop recursing condition is that the @set parameter is empty. In the stop condition processing $perm is printed (the result of the current recursive branch) and the function returns.
For the recursive processing the loop takes each element from @set and concatenates it on to the passed in $perm then passes the new string and @set with the current element removed down to the next recursion level. Because each recursion level removes one element from @set and tacks it onto $perm eventually all elements are removed from @set and tacked onto $perm and each of the ordering of the passed in @set are generated.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Please help me understand this permutation sub?
by mdunnbass (Monk) on Dec 09, 2020 at 14:12 UTC |