我想編寫一個perl程序來生成長度爲8(數字1-8以隨機順序)的非重複單位數字數組和第九個元素爲下劃線的數組。我寫了這樣的代碼。我想使用這個生成的數組進行基於數字的益智遊戲。隨機數組程序吃我的記憶
@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";
該程序分配第7個元素後,我的程序開始吃內存(10 GB)。我不明白這個原因。我用數學邏輯找出了缺失的數字(數字的總和--36(n(n + 1)/ 2))。爲什麼它吃我的記憶?或者是否有任何有效的方法來編寫相同的程序?
也許避免C風格的循環。 – flesk
我一定會在以後的課程中考慮你的建議。謝謝 –
@flesk:肯定 – Zaid