JavaScript: Do I need a recursive function to solve this problem? -
in fiddle http://jsfiddle.net/5l8q8/28/, if click black button, randomly selects 1 of 2 values (red or blue) array. randomly selected value assigned ran
. in real life application, there 16 elements in array.
if pink "playagain" button, chooses random element same array want make sure it's not same 1 chosen last time.
therefore, when click playagain
, assign ran
lastran
, compare next randomly chosen value array and, if same, choose randomly again. however, way have isn't guaranteeing (upon completion of playagain
) ran
different.
i think need recursive function comment 2 in code below, keep breaking code when try create it.
can comment on 3 comments in code below?
note, i'm relative newbie, code awful...
$("#playagain").click(function(){ lastran = ran; ran = getrandom(myarray, true); if (ran === lastran) { ran = getrandom(myarray, true); //1. need return this? //2. want test ran === lastran again.. how set recursive function? } else { return; //3.is right thing here? } });
you can use while loop instead of if.
while(ran == lastran) { ran = getrandom(myarray, true); }
it'll keep trying until gets different value.
Comments
Post a Comment