Search code examples
javascriptloopsprompt

Finding arithmetic mean of numbers asked in an infinite loop


What I need to achieve are the following conditions:

  1. a script asks for a number (in a prompt) between 1 and 100 in an infinite loop
  2. if a user enters NaN, empty string or a number off the range it asks for a number again
  3. if a user presses cancel, display an alert with a number of digits entered and their arithmetic mean
  4. i can't use an array!

here's what I have, and I understand that I'm missing some key logic in here, any suggestions?

  while (true) {
    var userInput = prompt("Enter a number between 1 and 100:");
    var num = parseInt(userInput, 10);
    if (num >= 1 && num <= 100) {
      var nums = 0;
      nums += num;
      var counter = 0;
      counter++;
    } else if (userInpuft === null) {
      alert(nums / counter);
      alert(counter);
      break;
    }
  }

Solution

  • The mean of a set of numbers can be calculated incrementally, without having to save all the numbers anywhere. All you need is the previous mean and the count of numbers that have been entered.

    Consider the formula mean = total/count. If you know mean and count, you can invert the equation to total = mean * count.

    When you get a new number, the count goes up by 1, and the new number is added to the total. So the formula is mean = (mean * (count - 1) + new_number)/count.

    let count = 0;
    let mean = 0;
    while (true) {
      let input = prompt("Enter a number");
      if (input === null) {
        break;
      }
      new_number = parseFloat(input);
      if (!isNaN(new_number) && new_number >= 1 && new_number <= 100) {
        count++;
        mean = (mean * (count - 1) + new_number) / count;
        alert(`Count = ${count}, Mean = ${mean}`);
      }
    }