I have this simple code and it is working fine it is self explanatory: the user will choose a random number 10 times and based on the random number the array will be filled by fruits.
var fruit =[];
for( x=0; x<10,x++){
var r = Math.floor(Math.random() * 100 + 1);
choose(r);
}
function choose(num){
if(num <30){
fruit.push("apple");
}else if(num <70){
fruit.push("kiwi");
}else if(num< 90){
fruit.push("banana");
}else{
fruit.push("grapes");
};
}
However in the code above, requirement is not restrictive; so below the number of available fruit is limited, and even if the random number choose a fruit, i have first to check if it is available in store or not. if the fruit is not available I should fall through to the next available fruit. The code below is working fine; but I had to do it via recursion in case fruit is not available.
var apple = 2;
var kiwi = 1;
var banana = 5;
var grapes = 2;
var fruit =[];
for( x=0; x<10,x++){
var r = Math.floor(Math.random() * 100 + 1);
choose(r);
}
function choose(num){
if(num <30){
if(apple>0){
fruit.push("apple");
apple--;
}else{
num = 31;
choose(num);
};
}else if(num <70){
if(kiwi>0){
fruit.push("kiwi");
kiwi--;
}else{
num = 71;
choose(num);
};
}else if(num< 90){
if(banana>0){
fruit.push("banana");
banana--;
}else{
num = 91;
choose(num);
};
}else{
if(grapes>0){
fruit.push("grapes");
grapes--;
}else{
num = 1;
choose(num);
};
};
}
This code is working and my question is:
Since this selection of food is happening many times in the page, and it involves recursion, I am worried that this will degrade the performance.
Is there any advice in this regard? or any change suggested to the code or algorithm?
num
to31
or71
or91
or1
, you should choose a new random number. Otherwise you don't have equal random distribution. \$\endgroup\$O(n)
and fully iterative. And BTW if you want to know if a code is fast enough for your needs benchmark it. Noone knows your requirements better than you do. \$\endgroup\$