使用javascript生成唯一的随机数 [英] Unique random number generation using javascript

查看:1048
本文介绍了使用javascript生成唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码生成0到15之间的随机数。我使用函数random()生成唯一的数字我调用这个函数

I use the following code for generating the random number from 0 to 15. I use a function random() for generating the unique number i call the function like this

cat=random();

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

I save the random number with in the array r[]. and check the newly generating number is in the array or not. If the duplicate occurs i call the random() function once again. I use alert for just check it correctly working or not

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); 
    }                   
}

但是当复制发生时,变量在函数内返回任何人都可以帮忙。

But the variable return within the function when the duplication occurs can anybody help with this.

推荐答案

我创建一个数组并使用Fisher-Yates

I'd create an array and shuffle it using 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生成唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆