I made a JavaScript program that randomly finds a certain number out of 100000 and prints out the amount of attempts it took (using a while loop).
Now I'm learning recursive function, and I wonder if it's possible to re-make this program using recursive. I've tried quite a few times, but with no luck.
Code:
let fun30 = num => {
let attempts = 0;
let randomNumber = 0;
while (randomNumber !== num) {
randomNumber = Math.round(Math.random() * 100000);
attempts ;
}
if (randomNumber === num) {
console.log("It took " attempts " attempts");
}
}
CodePudding user response:
let fun30 = num => {
let attempts = 0;
let randomNumber = Math.round(Math.random() * 100000);;
if (randomNumber === num) {
console.log("It took " attempts " attempts");
return attempts 1;
}
else {
return 1 fun30(num);
}
}
Yes, recursion is not recommended for this code and problem as there is no assurance when the base condition will be met.
CodePudding user response:
let fun30 = num => {
if (Math.round(Math.random() * 100000) === num) {
return 1;
}
else {
return 1 fun30(num)
}
}
But this is not recommended as you will probably exceed the maximum call stack