我正在尝试生成两个随机数 让他们 x 和 y, 我希望 x 总是大于 y。
我该怎么做?
你是说类似的东西吗?
// 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);
如果 x 较小,只生成 2 个随机值并交换值怎么样?
let [x,y] = [Math.random(), Math.random()];
console.log(x, y);
if (x < y)
[x,y] = [y,x];
console.log(x, y);
一个班轮。
// 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);
}
/** 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}`);
首先,请参阅在特定范围内在 JavaScript 中生成随机整数,了解如何生成随机数。
r1
和r2
的值保证是不同全范围内的随机数。 Math.max()
和 Math.min()
确保两者中较高的第一,另一个第二。
如果给定的范围太小,该函数将生成不正确的数字,例如,
generateTwoNumbers(1, 1)
只会生成 x = 2 和 y = 1。处理此类输入的情况由读者自行决定。