2

I am working on an assignment and I am having difficulty writing up the function to get a random number between two variables.

Basically what I want is the script to prompt you for the first number followed by the second then give me a random number in between those two.

How do I get a random whole number in between two user inputted variables? What I am doing wrong? Here's my code:

var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");

function getRndInteger(age, videogames) {
  return Math.floor(Math.random() * (videogames - age)) + age;
}
document.write(getRndInteger(age, videogames));

This question is different than the other question because mine is a random number between two variables. The other answer wouldn't work for me. Thanks again!

Jon Frank
  • 61
  • 1
  • 7

1 Answers1

2

You need to figure out which variable is smaller first, so that the number added at the end is the lower, and so that the difference (high - low) is positive. You also need to make sure that you're working with numbers - prompt returns a string, so + <string> will result in concatenation, not addition.

var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");

function getRndInteger(...args) {
  const [low, high] = [Math.min(...args), Math.max(...args)];
  return Math.floor(Math.random() * (high - low)) + low;
}
document.write(getRndInteger(age, videogames));

Note that this generates a range [low - high) - the "low" point is included, the "high" is not. (eg, from a range of 2-4, 2 is a possible result, as is 3, but 4 is not.) If you want to include high, add one to the difference:

var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");

function getRndInteger(...args) {
  const [low, high] = [Math.min(...args), Math.max(...args)];
  return Math.floor(Math.random() * (high - low + 1)) + low;
}
document.write(getRndInteger(age, videogames));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • The problem with that is what if they are someone could be 25 and game 30 hours in a month or be 30 and game 25 hours in a month, is there a way to take a random number between the two variables? one variable will be higher than the other based on user input. – Jon Frank Feb 25 '19 at 00:50
  • Yes, that's exactly what the answer does - it determines the lower and the higher, then multiplies the difference by `Math.random()` and adds the lower bound. – CertainPerformance Feb 25 '19 at 00:51
  • You rock man im gonna try it out, thank you!!! – Jon Frank Feb 25 '19 at 00:52
  • How do I do that? – Jon Frank Feb 25 '19 at 02:38
  • Do you mind helping me with one more question? I posted it in a separate post, i feel like im close but i cant figure it out – Jon Frank Feb 25 '19 at 02:42