JavaScript implementation generates a random number and the specified range of the random array comprising a repeating number not

JavaScript is currently no established method which can achieve this simply demands, we need to write the code yourself.
There is a function in the js: Math.random () This function may be generated [0,1) is a random number.
Our simple modified look, to meet the needs. Random number Reference article link: https://www.cnblogs.com/lanleiming/p/5409216.html


A, min ≤ r ≤ max

function RandomNumBoth(Min,Max){
            var Range = Max - Min;
            var Rand = Math.random();
            var num = Min + Math.round(Rand * Range); //四舍五入
            return num;
}

二、min ≤ r < max

function RandomNum(Min, Max) {
            var Range = Max - Min;
            var Rand = Math.random();
            var num = Min + Math.floor(Rand * Range);  //舍去
            return num;
}

Generating a random array contains a number of unique

The first problem is to re-think it, Mr. into an array and then go heavy ... is not too much trouble, in fact, the beginning, we can put this issue is resolved.

    /** len生成数组的长度,min生成数最小值,max生成数的最大值 **/
    function randomArr(len,min,max){
        if((max-min)<len){ //可生成数的范围小于数组长度
            return null;
        }
        var hash = [];

        while(hash.length<len){
            var num = randomNum(min,max);
            
            if(hash.indexOf(num)==-1){
                  hash.push(num);
            }
        }
        return hash;
    }
    

Guess you like

Origin www.cnblogs.com/tudou1179006580/p/11102927.html