in reply to Re^2: Please help me understand this permutation sub?
in thread Please help me understand this permutation sub?
here new code to highlight whats happening.
Please note the recursion here is effectively used to implement 4 nested loops, see second part of the code
#https://perlmonks.org/?node_id=11124854 use strict; use warnings; use Data::Dump qw/pp dd/; use 5.10.0; sub permutation { my ($perm,@set) = @_; my $level = 5 - @set; my $marker = " "x$level . "$level: " ; say "$marker ENTER perm='$perm' set=(@set)"; unless (@set) { say "$marker RESULT: $perm"; } else { permutation( $perm.$set[$_], @set[0..$_-1], @set[$_+1..$#set] ) for (0..$#set); } say "$marker RETURN"; return; } my @input = (qw/a b c d/); permutation('',@input); my @set = @input; my $perm = ""; for (0..3) { # level 1 my @set =@set; my $perm = $perm . splice @set,$_,1; for (0..2) { # level 2 my @set =@set; my $perm = $perm . splice @set,$_,1; for (0..1) { # level 3 my @set =@set; my $perm = $perm . splice @set,$_,1; for (0..0) { # level 4 my @set =@set; my $perm = $perm . splice @set,$_,1; say $perm; # level 5 } } } }
(shortened) output
-*- mode: compilation; default-directory: "d:/tmp/pm/" -*- Compilation started at Wed Dec 9 13:22:51 C:/Perl_524/bin\perl.exe -w d:/tmp/pm/permute.pl 1: ENTER perm='' set=(a b c d) 2: ENTER perm='a' set=(b c d) 3: ENTER perm='ab' set=(c d) 4: ENTER perm='abc' set=(d) 5: ENTER perm='abcd' set=() 5: RESULT: abcd 5: RETURN 4: RETURN 4: ENTER perm='abd' set=(c) 5: ENTER perm='abdc' set=() 5: RESULT: abdc 5: RETURN 4: RETURN 3: RETURN 3: ENTER perm='ac' set=(b d) 4: ENTER perm='acb' set=(d) 5: ENTER perm='acbd' set=() 5: RESULT: acbd 5: RETURN 4: RETURN 4: ENTER perm='acd' set=(b) 5: ENTER perm='acdb' set=() 5: RESULT: acdb 5: RETURN 4: RETURN 3: RETURN ### shortened ... ### Nested Loops abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba Compilation finished at Wed Dec 9 13:22:51
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Please help me understand this permutation sub?
by mdunnbass (Monk) on Dec 09, 2020 at 14:06 UTC |