I wanted to write a perl program to generate array with non-repetitive single digit numbers of length 8(Numbers 1-8 in random order) and ninth element to be a underscore. I have written a code like this. I want to use this generated array for a number based puzzle game.
@mat = (0,0,0,0,0,0,0,0,0);
sub randgen {
$randigit = int(rand(9));
if ($randigit == 0) {
&randgen;
}
elsif ( $mat[0] == $randigit
|| $mat[1] == $randigit
|| $mat[2] == $randigit
|| $mat[3] == $randigit
|| $mat[4] == $randigit
|| $mat[5] == $randigit
|| $mat[6] == $randigit
|| $mat[7] == $randigit
|| $mat[8] == $randigit
)
{
&randgen;
}
}
&randgen;
for ( $assign = 0; $assign <= 8; $assign++) {
$mat[$assign] = $randigit;
print "@mat \n"; # To see to what extent the program has generated the array
&randgen;
}
for ($i = 0; $i <= $#mat; $i++) {
$sum = $sum + $mat[$i];
}
$miss = 36 - $sum ;
$mat[7] = $miss;
$mat[8] = "_";
print "@mat \n";
The program After assigning 7th element, my program started eating memory(10 GB). I don't understand reason for that. I've used a mathematical logic to find the missing number(sum of numbers - 36 (n(n+1)/2)). Why is it eating my memory ? Or is there any effective way of writing the same program ?