gpt4 book ai didi

javascript - 使用 JavaScript 生成独特的随机数

转载 作者:行者123 更新时间:2023-11-28 12:04:34 26 4
gpt4 key购买 nike

我使用以下代码生成从 0 到 15 的随机数。我使用函数 random() 生成唯一的数字,我这样调用该函数

cat=random();

我将随机数保存在数组 r[] 中。并检查新生成的数字是否在数组中。如果重复发生,我再次调用 random() 函数。我使用警报只是为了检查它是否正常工作

function random(){
var ran,max=0,min=0;
max=r.length;
alert(max);
if (max>15)
alert("no more space");
ran=Math.floor(Math.random() * 15) + 0;
for (i=0;i<max;i++)
if (ran==r[i])
min++;
if (min>0){
alert("calling");
random(); //return in here
}else{
i=parseInt(max);
r[i]=ran;
return(ran);
alert(ran);
}
}

但是当重复发生时函数内的变量返回任何人都可以帮忙解决这个问题。

最佳答案

我创建一个数组并使用Fisher-Yates对其进行洗牌.

function shuffle(arr) {
var shuffled = arr.slice(0), i = arr.length, temp, index;
while (i--) {
index = Math.floor(i * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled;
}

// Create the array
var i = 16, arr = [];
while (i--) arr[i] = i;

// Shuffle it
arr = shuffle(arr);

// Array is now the numbers 0-15 in a random order
console.log(arr);

关于javascript - 使用 JavaScript 生成独特的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11368986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com