首页 > 编程语言 > 详细

简易洗牌算法

时间:2020-10-01 10:33:05      阅读:37      评论:0      收藏:0      [点我收藏+]

下方是使用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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!