Im trying to generate two random numbers let them x and y, and i want x to be always greater than y.
how can i do that?
Im trying to generate two random numbers let them x and y, and i want x to be always greater than y.
how can i do that?
You mean something like that?
// get random number between min and max
function random(min, max) {
return Math.floor(min + Math.random() * (max - min));
}
const y = random(0, 10);
const x = random(y + 1, 10);
console.log('x', x);
console.log('y', y);
How about just generating 2 random values and swapping the values if x is smaller?
let [x,y] = [Math.random(), Math.random()];
console.log(x, y);
if (x < y)
[x,y] = [y,x];
console.log(x, y);
/** random integer between min (inclusive) and max (inclusive) */
const random = (min, max) =>
Math.floor(Math.random() * (max-min+1)) + min;
const generateTwoNumbers = (min, max) => {
let r1 = random(min, max-1);
let r2 = random(min, max-1);
if (r2 >= r1)
r2 += 1;
return [Math.max(r1, r2), Math.min(r1, r2)];
}
const [x, y] = generateTwoNumbers(1, 10);
console.log(`x: ${x} y: ${y}`);
First, see Generating random whole numbers in JavaScript in a specific range for how random number generation can be done.
The values r1
and r2
are guaranteed to be different random numbers in the full range. Math.max()
and Math.min()
ensure that the higher of the two is first, the other second.
The function will generate incorrect numbers if the range given is too small, e.g., generateTwoNumbers(1, 1)
will only produce x = 2 and y = 1. Handling the case of such input is left at the discretion of the reader.
One liner.
// Create a tuple of two random numbers, then sort them.
const randomNumbers = () => [...Array(2)].map(() => Math.random()).sort((a, b) => (a > b ? -1 : 1));
// test
for (const _ of Array(50).keys()) {
const [x, y] = randomNumbers();
console.log(x > y);
}