首页 > 解决方案 > JS中的基础级非重复随机

问题描述

我正在尝试做一个测验,我需要 5 个随机问题,为了使它起作用,我创建了随机变量(rnd-rnd5),因为我需要在两个函数中使用这些变量。我需要制作非重复变量,但下面的解决方案不起作用。如果可能的话,我需要“基本”解决方案,因为我们的老师希望我们有一个“在我们的水平”的代码。

var rnd = [Math.floor(Math.random() * 29) + 0];
var rnd2 = [Math.floor(Math.random() * 29) + 0];
while (rnd2 !== rnd){
    rnd2 = Math.floor(Math.random() * 29) + 0;
}

var rnd3 = [Math.floor(Math.random() * 29) + 0];
while (rnd3 !== rnd && rnd3 !== rnd2){
    rnd3 = Math.floor(Math.random() * 29) + 0;
}

var rnd4 = [Math.floor(Math.random() * 29) + 0];
while (rnd4 !== rnd && rnd4 !== rnd2 && rnd4 !== rnd3){
    rnd4 = Math.floor(Math.random() * 29) + 0;
}
var rnd5 = [Math.floor(Math.random() * 29) + 0];
while (rnd5 !== rnd && rnd5 !== rnd2 && rnd5 !== rnd3 && rnd5 !== rnd4){
    rnd5 = Math.floor(Math.random() * 29) + 0;
}

标签: javascriptrandom

解决方案


你有几个问题:

  1. 您正在生成一个具有单个成员的数组,该成员是一个随机数。数组总是等于其他数组和任何其他值而不是它们自己。看起来好像你想要一个普通的变量,所以你只需要删除[]包围Math.floor调用。

  2. 您还可以向后检查 - 如果当前数字不等于旧数字,则您正在生成新数字。这意味着您正在生成直到两者相同。你只需要做相反的检查===

  3. 您正在使用 AND 进行检查&&,您需要在其中检查使用OR来捕获是否匹配了之前的任何数字。

这导致工作代码:

var rnd = Math.floor(Math.random() * 29) + 0;
var rnd2 = Math.floor(Math.random() * 29) + 0;
while (rnd2 === rnd){
    rnd2 = Math.floor(Math.random() * 29) + 0;
}

var rnd3 = Math.floor(Math.random() * 29) + 0;
while (rnd3 === rnd || rnd3 === rnd2){
    rnd3 = Math.floor(Math.random() * 29) + 0;
}

var rnd4 = Math.floor(Math.random() * 29) + 0;
while (rnd4 === rnd || rnd4 === rnd2 || rnd4 === rnd3){
    rnd4 = Math.floor(Math.random() * 29) + 0;
}
var rnd5 = Math.floor(Math.random() * 29) + 0;
while (rnd5 === rnd || rnd5 === rnd2 || rnd5 === rnd3 || rnd5 === rnd4){
    rnd5 = Math.floor(Math.random() * 29) + 0;
}

console.log(rnd, rnd2, rnd3, rnd4, rnd5)

话虽如此,如果您首先生成随机数,然后将它们混杂并选择您需要的任意数量,则可以更轻松地生成随机非重复数。


推荐阅读