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");
    }
}
3
  • 2
    Using recursion is pointless here. If you want to write a recursion function, write one that calculates a number's factorial. Commented Aug 14, 2022 at 12:08
  • 1
    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. Commented Aug 14, 2022 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. Commented Aug 14, 2022 at 14:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.