Parham has asked for the wisdom of the Perl Monks concerning the following question:
Fellow monks, i require your assistance in understanding this permutation program. The commented line shows what the function is doing while making the permutations:#!/usr/bin/perl use strict; permute("1 2 3 4",""); sub permute { my $old = @_[0]; my $new = @_[1]; my @old = split(/ /,$old); my @new = split(/ /,$new); print "old = @old | new = @new\n"; #helpful in seeing what's going o +n unless (@old) { print "@new\n"; } else { my $i; foreach $i (0..$#old) { my @new1 = @new; my @old1 = @old; unshift(@new1,splice(@old1,$i,1)); my $new1 = join(' ',@new1); my $old1 = join(' ',@old1); permute($old1,$new1); } } }
old = 1 2 3 4 | new = old = 2 3 4 | new = 1 old = 3 4 | new = 2 1 old = 4 | new = 3 2 1 old = | new = 4 3 2 1 4 3 2 1 old = 3 | new = 4 2 1 old = | new = 3 4 2 1 3 4 2 1 old = 2 4 | new = 3 1 old = 4 | new = 2 3 1 old = | new = 4 2 3 1 4 2 3 1 ... too long to continuei understand everything up to the first loop, but after that i start losing how the "old" array picks up info from the "new" array (seems to be working backwards?). I'm not having a perl problem, but rather a theory problem with how perl actually makes this work. If someone could give me a short step-by-step guide to what perl does with the array, i'd be most grateful. Rather than using the subroutine blindly, i'd like to get a little bit of information on how it's able to work. All help appreciated, and thanks in advance.
|
---|
Replies are listed 'Best First'. | |
---|---|
(jeffa) Re: permutation understanding
by jeffa (Bishop) on May 25, 2002 at 09:02 UTC | |
by Anonymous Monk on May 25, 2002 at 16:03 UTC | |
by greywolf (Priest) on May 25, 2002 at 18:36 UTC | |
by Anonymous Monk on May 25, 2002 at 18:55 UTC | |
by theguvnor (Chaplain) on May 25, 2002 at 21:36 UTC | |
by Anonymous Monk on May 25, 2002 at 22:07 UTC | |
Re: permutation understanding
by Parham (Friar) on May 27, 2002 at 20:55 UTC |