You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中生成不同随机数:如何让rand、rand1、rand2、rand3互不相等?

How to Generate 4 Unique Random Numbers (0-3)

The problem with your original code is that each random number is generated independently—so duplicates are pretty likely. To make sure rand, rand1, rand2, and rand3 are all distinct (no repeats whatsoever), here are two simple, reliable approaches:

Method 1: Shuffle the Full Set of Values

Since we need every unique value from 0 to 3 (that's exactly 4 numbers), we can create an array of these values, shuffle it, and then assign each element to your variables. This method guarantees no duplicates and is clean for small ranges like this.

We'll use the Fisher-Yates shuffle, a standard algorithm for unbiased shuffling:

// Start with all possible values (0-3)
const numbers = [0, 1, 2, 3];

// Fisher-Yates shuffle to randomize the array
for (let i = numbers.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
}

// Assign the shuffled values to your variables
const rand = numbers[0];
const rand1 = numbers[1];
const rand2 = numbers[2];
const rand3 = numbers[3];

Method 2: Generate and Check for Duplicates

If you'd rather generate each number one by one, you can use loops to keep generating values until you get one that hasn't been used yet:

// Generate first number normally
let rand = Math.floor(Math.random() * 4);

// Generate rand1: keep trying until it's not equal to rand
let rand1;
do {
  rand1 = Math.floor(Math.random() * 4);
} while (rand1 === rand);

// Generate rand2: keep trying until it's not equal to rand or rand1
let rand2;
do {
  rand2 = Math.floor(Math.random() * 4);
} while (rand2 === rand || rand2 === rand1);

// Generate rand3: keep trying until it's not equal to the other three
let rand3;
do {
  rand3 = Math.floor(Math.random() * 4);
} while (rand3 === rand || rand3 === rand1 || rand3 === rand2);

Both methods will ensure all four variables have unique values between 0 and 3. The shuffle method is more efficient and concise, especially since we know we need every value in the range.

内容的提问来源于stack exchange,提问作者Nima Keshavarzian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:27:27