洗牌算法-shuffle

时间:2021-03-10 13:22:24   收藏:0   阅读:0

shuffle算法-洗牌算法

算法的作用

打乱顺序

算法的实现

等概率的抽取数组中的每一个数,跟最后一个元素交换

// 使用闭包,防止变量污染
(function() {
        function shuffle() {
          // 调用形式: arr.shuffle(); 这里的this指向Array实例
            let arr = this;
            for (let i = arr.length; i >= 0; --i) {
                let randomIndex = Math.floor(Math.random() * (i + 1));
                let itemAtIndex = arr[randomIndex];
                arr[randomIndex] = arr[i];
                arr[i] = itemAtIndex;
            }
            return arr;
        }
  			// 扩展到数组的原型上去
        Array.prototype.shuffle = shuffle;
    })();

开发中的应用

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!