麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > JavaScript > 正文

JavaScript隨機打亂數組順序之隨機洗牌算法

2019-11-20 09:20:02
字體:
來源:轉載
供稿:網友

假如有一個數組是這樣子:

var arr1 = ["a", "b", "c", "d"];

如何隨機打亂數組順序,也即洗牌。

有一個比較廣為傳播的簡單隨機算法:

function RandomSort (a,b){ return (0.5 - Math.random()); }

實際證明上面這個并不完全隨機。

隨便一搜網上太多這種東西了,看一下stackoverflow上的一個高分回答,答案出自github上。

knuth-shuffle
The Fisher-Yates (aka Knuth) shuffle for Browser and Node.JS

下面一起看看上面說的這個算法,代碼如下:

/*jshint -W054 */(function (exports) {'use strict';// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-arrayfunction shuffle(array) {var currentIndex = array.length, temporaryValue, randomIndex;// While there remain elements to shuffle...while (0 !== currentIndex) {// Pick a remaining element...randomIndex = Math.floor(Math.random() * currentIndex);currentIndex -= 1;// And swap it with the current element.temporaryValue = array[currentIndex];array[currentIndex] = array[randomIndex];array[randomIndex] = temporaryValue;}return array;}exports.knuthShuffle = shuffle;}('undefined' !== typeof exports && exports || 'undefined' !== typeof window && window || global));

作者推薦使用瀏覽器寫法:

(function () {'use strict';var a = [2,11,37,42], b;// The shuffle modifies the original array// calling a.slice(0) creates a copy, which is assigned to bb = window.knuthShuffle(a.slice(0));console.log(b);}());

Nodejs:

npm install -S knuth-shuffle(function () {'use strict';var shuffle = require('knuth-shuffle').knuthShuffle, a = [2,11,37,42], b;// The shuffle modifies the original array// calling a.slice(0) creates a copy, which is assigned to bb = shuffle(a.slice(0));console.log(b);}());

還有其它從這個算法中變形去的,比如下面這個for循環的。其它的就不說了。

/*** Randomize array element order in-place.* Using Durstenfeld shuffle algorithm.*/function shuffleArray(array) {for (var i = array.length - 1; i > 0; i--) {var j = Math.floor(Math.random() * (i + 1));var temp = array[i];array[i] = array[j];array[j] = temp;}return array;}

使用ES2015(ES6)

Array.prototype.shuffle = function() {let m = this.length, i;while (m) {i = (Math.random() * m--) >>> 0;[this[m], this[i]] = [this[i], this[m]]}return this;}

使用:

[1, 2, 3, 4, 5, 6, 7].shuffle();

發現中文搜索隨機算法一大堆,但究竟是不是完全隨機,效率和兼容性都有待考究,建議后面如果有需要用到隨機打亂數組元素,可以用上面這個。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 日本在线视频一区二区三区 | 99这里精品 | 国产黄色录像片 | 久久免费视频一区 | 国产精品99久久免费观看 | 日韩精品免费一区二区三区 | 黄色免费入口 | 国产亚色 | av成人免费 | 97久久日一线二线三线 | 国产精品99久久久久久久 | 国产精品久久久久久婷婷天堂 | 亚洲成人欧美在线 | 久久久久久中文字幕 | 亚洲国产精品久久久久久久久久 | 精品国产91久久久久久久妲己 | 国产老师做www爽爽爽视频 | 久久久久免费精品 | 国产精品成人一区二区三区电影毛片 | 欧美成人免费tv在线播放 | 精品三区视频 | 国产精品.com | arabxxxxvideos| 日本黄色免费观看视频 | 久国产| 日本免费不卡一区二区 | 激情宗合网 | 日韩视频一区二区三区在线观看 | 久草在线手机观看 | 日本一级黄色大片 | 国产一级一区二区三区 | 亚洲第一页综合 | 成人激情视频网站 | 蜜桃视频在线播放 | 精精国产xxxx视频在线野外 | 羞羞电影在线观看 | 黄色网址在线免费 | 欧美特一级 | 97超级碰碰人国产在线观看 | 黄色成人小视频 | av电影在线播放 |