[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[MacPerl] 2D Permutations



Hi all,

I just finished writing a module that process all permutations in the 2nd
dimension (only the 2nd) of a 2D array. I'm new at module writing and am
worried that it's not optimized for speed or efficiency.  I've used it on my
G3/300, and it seems fine, but I'm still concerned that it's not fast enough
for the real world.  Any suggestions?

Thanks,
David

-------------------
SYNOPSIS
-------------------

 use List::Permutor2D;
    
    my @ary = ( [ "A", "B" ],
                [ "C", "D", "E" ],
                [ "F", "G", "H" ]
              );
              
    my $perm = new List::Permutor2D @ary;
    
    while(my @set = $perm->next) {
        print @set, "\n";
    }
    
    # prints ACF
    #        ACG
    #        ACH
    #        ADF
    #        ADG
    #        ADH
    #        ...
    #        etc.

------------------
PACKAGE
------------------

package List::Permutor2D;

my(@ary, @schema, $idx, $count, $currIdx, $done, $numResults);

sub new {
    my $class   = shift;
    @ary        = @_;
    @schema     = (0) x @ary;
    $idx        = $#schema;
    $numResults = &_get_num_results;
    return bless \$ary, $class;
}

sub next {
    $count++;
    my $curAry = &_get_ary;
    my $self = shift;
    my $x    = shift;
       $x    = $idx unless $x;
    &_int_next($x);
    
    return @{$curAry} unless $count == $numResults + 1;
    return ();
}

sub _int_next {
    my $mIdx = shift;
    if(@schema[$mIdx] == @{@ary->[$mIdx]} - 1) {
        @schema[$mIdx] = 0;
        &_int_next($mIdx - 1);
    } else {
        @schema[$mIdx] += 1;
    }
}    

sub _get_ary {
    my @retAry;
    for(my $i = 0; $i <= $#schema; $i++) {
        push(@retAry, @ary->[$i][@schema[$i]]);
    }
    return \@retAry;
}

sub _get_num_results {
    my $num = 1;
    for(my $i = 0; $i < @schema; $i++) {
        $num *= @{@ary->[$i]};
    }
    return $num;
}

1;


# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org