-2

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?

  • 1
    Define "random" in this case. E.g. what are the min/max? Do you want decimal places? If so, how many? Etc etc – DBS Sep 23 '22 at 12:44
  • 3
    @Palladium02 or just generate two different numbers and assign the bigger one to `x` – VLAZ Sep 23 '22 at 12:48
  • @VLAZ I agree, except what happens in the rare case where the two numbers are the same? I think you first have to check to see if they are the same and, if so, generate new numbers. – Scott Marcus Sep 23 '22 at 12:57
  • thats what Math.max and Math.min are for – Lawrence Cherone Sep 23 '22 at 13:02
  • Math.random() * (max - min) + min; See: [MDN Math.random examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#examples) – Yogi Sep 23 '22 at 13:04

4 Answers4

1

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);
Ivolution
  • 11
  • 3
1

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);
phuzi
  • 12,078
  • 3
  • 26
  • 50
0

/** 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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
0

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);
}
mstephen19
  • 1,733
  • 1
  • 5
  • 20