生成随机数的方式

下方是使用JavaScript实现的生成任意位数的随机数,列出三种方法(含测试):

///Way1
function GetRandomNumberByRange(lowerValue = 0, upperValue = 99, includeTail = true) {
    if (includeTail) {
        return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
    } else {
        return (Math.ceil(Math.abs((Math.random() - 1))) * (upperValue - lowerValue + 1) + (lowerValue - 1));
    }
}




///Way2
function GetRandomNumberByUnitLength(unitLength = 3) {
    let result = 0;
    let strResult = "";
    let currentRandomNumber = 0;
    for (let i = 0; i < unitLength; i++) {
        // currentRandomNumber = Math.ceil(Math.abs(Math.random() - 1) * 10); // (0,10]
        currentRandomNumber = GetRandomNumberByRange(0, 9, true); // [0,9]
        if (currentRandomNumber === 0) {
            // currentRandomNumber = Math.ceil(Math.abs(Math.random() - 1)) * 10 - 1; // (0,9]
            currentRandomNumber = GetRandomNumberByRange(0, 9, false); // (0,9]
        }
        strResult += String(currentRandomNumber);
    }
    result = parseInt(strResult);
    //console.log(result);
    return result;
}




///Way3
function GetRandomNumberViaMod(unitLength = 3) {
    let arr = new Array(unitLength + 1);
    arr[0] = 0;

    for (let i = 1; i <= unitLength; i++) {
        arr[i] = Math.floor(Math.random() * Math.pow(10, i));
        arr[i] += arr[i - 1];
    }

    if (arr[unitLength] < Math.pow(10, unitLength - 1)
        || arr[unitLength] >= Math.pow(10, unitLength)) {

        //Must hold the result for new arr[unitLength]  
        arr[unitLength] = GetRandomNumberViaMod(unitLength);
    }

    return arr[unitLength];
}







//Test
let x = GetRandomNumberByRange(1000, 9999);
let y = GetRandomNumberByUnitLength(4);
let z = GetRandomNumberViaMod(4);
console.log(x);
console.log(y);
console.log(z);



//Pressure test
// for (let i = 0; i < 10; i++)console.log(GetRandomNumberViaMod(4));
// for (let i = 0; i < 1000; i++)GetRandomNumberViaMod(4);
// for (let i = 0; i < 10000; i++) {
//     if (GetRandomNumberViaMod(4) > 9999) {
//         console.log("Maximized!!!");
//     } else if (GetRandomNumberViaMod(4) < 1000) {
//         console.log("Minimized!!!");
//     }
// }




作者:艾孜尔江·艾尔斯兰
转载或使用请标明出处!

原文地址:https://www.cnblogs.com/ezhar/p/13757242.html