in reply to Please help me understand this permutation sub?

Maybe printing the @set with the recursion depth shown as indentation can enlighten you?
#!/usr/bin/perl use strict; use warnings; sub permutation { my ($perm, $depth, @set) = @_; print "\t" x $depth, "@set\n"; print "$perm\n" unless @set; permutation($perm . $set[$_], $depth + 1, @set[ 0 .. $_ - 1], @set[ $_ + 1 .. $#set] ) for 0 .. $#set; } my @input = (qw/a b c d/); permutation("", 1, @input);

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Please help me understand this permutation sub?
by mdunnbass (Monk) on Dec 09, 2020 at 13:55 UTC

    Thanks choroba,

    Your print statements are very much in line with what LanX posted as well. Both of them make the recursion very much more obvious to me. But my problem is in 'backing up' the recursion, for lack of a better way to put it. In my reply to LanX above, I laid out the exact spot that is tripping me up. There's something about going from the first completed permutation, resulting in $perm = abcd, to the next line of output, where the $perm is now abd, missing the c.

      > There's something about going from the first completed permutation, resulting in $perm = abcd, to the next line of output, where the $perm is now abd, missing the c.

      In short: Level4 calls Level5 only one time, always! This means 4 returns to Level3 immediately after 5 returns.

      And Level3 calls Level4 for the second time, but now with $perm="ab"."d" .

      I hope it's clearer now, have a look at the extensive explanations in my other replies, especially the nested loop analogy.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery