recursion - I'm having trouble writing a recursive function in JavaScript - it doesn't seem to "fall back" to the lesser depth correctly -
var dicetoroll = [2,2]; var dicerolled = new array(); function recurse(dicetoroll, dicerolled) { roll = dicetoroll[0] dicelefttoroll = dicetoroll; dicelefttoroll.shift(); for(loop=1; loop<(roll+1); loop++) { result = dicerolled; result.push(loop); if(dicelefttoroll.length == 0) { console.log(result); result.pop(); } else { recurse(dicelefttoroll, result); } } } recurse(dicetoroll, dicerolled);
i'm trying write recursive function prints possible results of number of dice. example, dd100 (dicetoroll = [6, 10, 10, 100]
)(dicetoroll = [6, 6, 6, 6, 6]
) etc. in example have used simplest case(or 2 2-sided dice).
i expected results [1,1], [1,2], [2,1], [2,2] logs [1,1], [1,2]. same number or type of dice - deepest level of recursion works correctly.
i figure i'm missing obvious in logic of / or misunderstanding variable scope in javascript, i'm struggling head around it.
edit 1 (to make explanation of program's purpose clearer)
the programs purpose list possible values on number of dice. dice 6
implies range of values 1..6
. likewise, two-sided dice, 2
, implies range of values 1..2
. 2 two-sided dice in example (dicetoroll[2,2]
) possible values 1,1 1,2 2,1 , 2,2 - should returned.
there several issues code:
use
var
keyword in order define local variables.assigning array variable not copies content, reference same array. use
array.slice()
if want clone array.
here fixed function:
var dicetoroll = [2,2], dicerolled = []; function recurse(dicetoroll, dicerolled) { var roll = dicetoroll[0], dicelefttoroll = dicetoroll.slice(1), loop, result; for(loop=1; loop<=roll; loop++) { result = dicerolled.slice(0); result.push(loop); if(dicelefttoroll.length === 0) { console.log(result); result.pop(); } else { recurse(dicelefttoroll, result); } } } recurse(dicetoroll, dicerolled);
note
dicetoroll = dicetoroll.slice(1)
is equivalent to
dicetoroll = dicetoroll.slice(0); dicetoroll.shift();
fiddle here: http://jsbin.com/isebef/1/edit
Comments
Post a Comment