Judy
Judy

Reputation: 53

Perl recursion causing "use of uninitialized value" error

I am new to perl, and can't seem to find answers about this anywhere. I narrowed down the problem to a recursive function. If I comment that out, then it works just fine without errors. I have:

use strict;
use warnings;

 sub GeneratePermutations{
    my($n, $nMax, $i, $ArrLength, @Arr) = @_;

    if($n == 0){
    foreach($i..$ArrLength-1){
        $Arr[$i] = 0;
        ++$i;
    }

    my @qArr = ();
    my $rVal = 1; 
    for(my $p = 0; $p < @Arr; $p++){

        $rVal *= fac($Arr[$p]);

        for(my $q = 0; $q < $ArrLength; $q++){

        my $qCount = 0; 
        for(my $j = 0; $j < $ArrLength; $j++){ 

            if($Arr[$j] eq $q){
            ++$qCount;
            }


        }
        $qArr[$i] = $qCount;
        }
    }
    my $qVal = 1;
    for(my $qNum = 0; $qNum < @qArr; $qNum++){
        $qVal *= fac($qArr[$qNum]);
    }
    my $maxDistVal = 0;
    $maxDistVal = (1/($ArrLength**$ArrLength))*(fac($ArrLength)/$rVal)*(fac($ArrLength)/$qVal);

    if($maxDistVal > $distribution){
        $distribution = $maxDistVal;
    }
    #prints out distributions for all permutations (comment out previous if-statement)
    print "Dist: " . $distribution . "<br /><br />";
    #return 1;
    }
    my $resultCnt = 0;
    for(my $cnt = MinVal($nMax, $n); $cnt > 0; $cnt--){
    $Arr[$i] = $cnt;
    ++$resultCnt; 
    GeneratePermutations(int($n-$cnt), $cnt, $i+1, $ArrLength, @Arr);
    }

    #return $resultCnt;
    return $distribution;

}

What am I missing?

Upvotes: 0

Views: 816

Answers (3)

Judy
Judy

Reputation: 53

I started to comment out parts of my code and found that if I remove this portion, then the warnings disappear:

for(my $qNum = 0; $qNum < @qArr; $qNum++){
    $qVal *= fac($qArr[$qNum]);
}

Upvotes: 0

gtjason2000
gtjason2000

Reputation: 201

When You declare $distribution it will probably have to be outside of the subroutine as you need it to persist throughout the recursion.

Upvotes: 0

craig65535
craig65535

Reputation: 3581

If I had to guess I would say this is the problem: $qArr[$i] = $qCount;

Because you're only writing one element in @qArr repeatedly, and then later on reading elements 0 through $#qArr.

Did you mean $qArr[$p] = $qCount;? Or $qArr[$q] = $qCount;?

Upvotes: 1

Related Questions