如何在不超出調用堆棧大小的情況下處理遞歸調用?硬幣算法優化
這個問題在這裏回答了Maximum call stack size exceeded error,但對我沒有幫助。這可能對別人有幫助。
算法提示是一點點漫長的,但對於那些你被確定:coin algorithm
我的代碼可能不會試圖滿足所有要求,但不管我想什麼,我有一些投入。
var gameSetup = {
coins: [2,333,4,11,99,20,10],
minOdds: 1,
maxOdds: 100000
}
function game(gs) {
this.minOdds = gs.minOdds;
this.maxOdds = gs.maxOdds;
var coinArray = gs.coins;
var coinArrayLength = coinArray.length;
var indicesToSplice = [];
var gameResults = {
turns: 0,
score: 0
}
var gameFunctions = {
getTurns: function() {
return gameResults.turns;
},
setTurns: function() {
++gameResults.turns;
},
setScore: function(lcv,rcv) {
var score = lcv * rcv;
gameResults.score += score;
},
getScore: function() {
return gameResults.score;
},
generateFlips: function() {
return generateFlips.getRandomNumbersInclusive();
}
}
var generateFlips = (function() {
var flips = [];
return {
getRandomNumbersInclusive: function() {
flips = [];
for(i=0; i < coinArrayLength; i ++){
var currentFlip = Math.floor(Math.random() * (maxOdds - minOdds + 1)) + minOdds;
flips.splice(0,0,currentFlip);
}
return flips;
}
}
})();
(function takeTurn(coinArrayLength) {
var flips = gameFunctions.generateFlips();
flips.forEach(function(i, index) {
if(i == maxOdds) {
var leftOfIndex = flips[index-1];
var rightOfIndex = flips[index +1];
if(typeof leftOfIndex === 'undefined' || typeof rightOfIndex === 'undefined') {
} else {
indicesToSplice.splice(0,0,index);
var leftCoinValue = coinArray[index-1];
var rightCoinValue = coinArray[index+1];
gameFunctions.setScore(leftCoinValue,rightCoinValue);
}
}
});
if(indicesToSplice.length > 0) {
indicesToSplice.forEach(function(i){
coinArray.splice(i,1);
coinArrayLength = coinArray.length;
});
}
indicesToSplice = [];
gameFunctions.setTurns();
if(coinArrayLength > 2) {
takeTurn(coinArrayLength);
} else {
return;
}
})(coinArrayLength);
}
game(gameSetup);
你必須閱讀[問] – Amit
如果代碼工作,這可能會更好的問在http://codereview.stackexchange.com/ – Andy
@然後最大調用堆棧大小超過。節點拋出一個範圍錯誤。 –