AstralV
AstralV

Reputation: 139

Generating random integer between two inputs Javascript

I'm trying to write a function (GetPositiveInteger) that generates a random integer between variables a and b. if a > b, it's supposed to switch the values of the two so that b=>a before generating the Number.

I don't know if I'm misunderstanding the question or what because I can't figure out where I'm meant to be converting a and b to integers and my program keeps just returning NaN. here's my code maybe someone could take a look at it?

function GetRandomInteger(a, b, c) {
  a = Number(a), b = Number(b);
  if (a > b) {
    var a = 2,
      b = 1,
      c = a;
    a = b;
    b = c;
  } else {
    var x = parseInt(Math.random() * b) + a;
  }

  return x;
}

let x;
console.log(Number(GetRandomInteger(x)));

Upvotes: 0

Views: 75

Answers (1)

Barmar
Barmar

Reputation: 782130

When a > b, you're setting them to specific numbers before swapping them, instead of swapping the original values.

The code that generates the random number shouldn't be in else, because you won't run that after swapping a and b. It should just be after the if.

You don't need the c parameter. Use a temporary variable declared inside the function when swapping.

Use Math.floor() to convert a floating point number to an integer. parseInt() is for parsing strings (it will work in this case because it first converts the float to a string, but it's better to use the more specific function).

You need to call the function with two arguments. In the example below I just hard-coded them, but you can use your function that asks the user for numbers. Just use it twice to set two variables.

function GetRandomInteger(a, b) {
  a = Number(a), b = Number(b);
  if (a > b) {
    let temp = a;
    a = b;
    b = temp;
  }
  var x = Math.floor(Math.random() * b) + a;

  return x;
}

console.log(GetRandomInteger(1, 10));
console.log(GetRandomInteger(15, 3));

Upvotes: 2

Related Questions