in reply to Iterating over an array variable times

To extend your algorithm to make the number of loops arbitrary, use Algorithm::Loops's NestedLoops.
use strict; use warnings; use Algorithm::Loops qw( NestedLoops ); my @arr = qw( A B C D E F ); my $N = 2; my $i = NestedLoops([ [ 0 .. @arr ], ( sub { [ $_ .. @arr ] } ) x ($N-1) ]); while (my (@positions) = $i->()) { my @tmp = @arr; splice(@tmp, $_, 0, 'N') for reverse @positions; print(join(',', @tmp), "\n"); }

Or without inserting elements in the middle of an array (which should help with long arrays):

while (my (@positions) = $i->()) { my @tmp; my $cur = 0; for my $pos (@positions) { push @tmp, @arr[$cur..$pos-1]; $cur = $pos; push @tmp, 'N'; } push @tmp, @arr[$cur..$#arr]; print(join(',', @tmp), "\n"); }

Or a version that uses no extra memory.

while (my (@positions) = $i->()) { my $sep = ''; my $cur = 0; for my $pos (@positions) { print($sep); $sep = ', '; print($arr[$cur++], $sep) while $cur < $pos; print('N'); } print($sep, $arr[$cur++]) while $cur < @arr; print("\n"); }

Replies are listed 'Best First'.
Re^2: Iterating over an array variable times
by gingaloon (Acolyte) on Aug 05, 2008 at 18:22 UTC
    Thanks Jethro and Ikegami.
    These do what I need.  I shall now read through what each bit of code is doing.
    
    thanks again