javascript - JS function to fill an array with unique elements thorugh generated values -
i'm trying make simple browser game using p5.js. , i've ran problem:
i have array of zombies. zombie object has method getanswer() returns number. i'm trying make function addzombie(), pushes 1 new zombie array. problem don't want repetitive answers in array. current function:
function mkex(){ var values = [] (i=1;i<11;i++){ values.push(i); } var signs = ['+','-','/','*']; var result = -1; var = 0; var b = 0; var c = 0; var sign1 = ""; var sign2 = ""; while (result<=0){ = values[math.round(math.random()*(values.length-1))]; b = values[math.round(math.random()*(values.length-1))]; c = values[math.round(math.random()*(values.length-1))]; sign1 = signs[math.round(math.random()*(signs.length-1))]; sign2 = signs[math.round(math.random()*(signs.length-1))]; switch(sign1){ case "+": switch(sign2){ case "+": result=a+b+c; break; case "-": result=a+b-c; break; case "/": if (b%c==0){ result=a+b/c; } break; case "*": result=a+b*c; break; default: break; } break; case "-": switch(sign2){ case "+": result=a-b+c; break; case "-": result=a-b-c; break; case "/": if (b%c==0){ result=a-b/c; } break; case "*": result=a-b*c; break; default: break; } break; case "/": switch(sign2){ case "+": if (a%b==0){ result=a/b+c; } break; case "-": if (a%b==0){ result=a/b-c; } break; case "/": if (a%b==0){ if (a/b%c==0){ result=a/b/c; } } break; case "*": if (a%b==0){ result=a/b*c; } break; default: break; } break; case "*": switch(sign2){ case "+": result=a*b+c; break; case "-": result=a*b-c; break; case "/": if (a*b%c==0){ result=a*b/c; } break; case "*": result=a*b*c; break; default: break; } break; default: break; } } var expr = ""+a+sign1+b+sign2+c; var ret = [expr, result]; return ret; } function addzombie(){ var expr = mkex(); if (zombies.length==0){ zombies.push(new zombie(player.getxy(),expr)); } else{ (i=0;i<zombies.length;i++){ if (zombies[i].getanswer()==expr[1]){ addzombie(); } zombies.push(new zombie(player.getxy(),expr)); } }
the mkex() function returns array containing string , answer. zombie needs player's coordinates spawn away player.
this function doesn't work, still have zombies same answers. please tell me wrong?
using set
keep track of answers make solution simpler , faster (since average search time in set
o(1)
)
let answerset = new set(); let zombies = []; function addzombie() { let expr = mkex(); let zombie = new zombie(player.getxy(),expr); while(answerset.has(zombie.getanswer())) { zombie = new zombie(player.getxy(),expr); } answerset.add(zombie.getanswer()); zombies.push(zombie); }
Comments
Post a Comment