nodejs实现的一个简单粗暴的洗牌算法

据说名字长别人不一定看得到

之前用python,自带shuffle用的还是超爽的;

去年6月份自己动手用nodejs写一个21点扑克游戏的后台时,就需要一个洗牌算法,于是简单粗暴的实现了一个。

贴出来交流下:

var Util = {};

Util.shuffle = function(pokers,times,scope) {
    times = times == undefined ? 15 : times;
    scope = scope == undefined ? 5 : scope;
    
    var index0;
    var index1;
    var len = pokers.length;
    var i = 0;
    var temp;
    var r0;
    var r1;
    while (times > 0){
        index0 = Math.floor(Math.random() * len);
        index1 = Math.floor(Math.random() * len);

        while (index0 == index1 ){
            index1 = Math.floor(Math.random() * len);
        }
        for (i = 0; i < scope; i++){
            r0 = index0 % len;
            r1 = index1 % len;
            temp = pokers[r0];
            pokers[r0] = pokers[r1];
            pokers[r1] = temp;
            index0++;
            index1++;
        }
        times--;
    }
    //console.log('shuffle complete:'+pokers.join('.'));
};

module.exports = Util;

注释不用写太多,取名好一点就可以当注释用。

原文地址:https://www.cnblogs.com/adoontheway/p/6369557.html