0

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");
    }
}
empflow
  • 111
  • 2
  • 8
  • 2
    Using recursion is pointless here. If you want to write a recursion function, write one that calculates a number's factorial. –  Aug 14 '22 at 12:08
  • Consider testing your recursion skill writing a binary search to find a number within the range 0-999. Go to half way, check if the number is higher or lower, then go one quarter way up/down, check if higher lower, then one eighth, etc. Count the steps. – RobG Aug 14 '22 at 12:19
  • Recursions and for loop are interchangeable. Since solutions here utilize a tail recursion approach it is quite the same performance as the while loop. – IT goldman Aug 14 '22 at 14:50

2 Answers2

1
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

Haim
  • 321
  • 1
  • 10
1
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.