Skip to content

Commit

Permalink
Create 洗牌算法--shuffle.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Rain120 authored Apr 23, 2019
1 parent 1bfedc6 commit 406e040
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions 洗牌算法--shuffle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// 详见[shuffle](https://bost.ocks.org/mike/shuffle/)

function shuffle(arr) {
var n = arr.length, random;
while(0 != n){
random = (Math.random() * n--) >>> 0;
// 1
t = array[random];
array[n] = array[random];
array[random] = t;
// 2
[arr[n], arr[random]] = [arr[random], arr[n]];
}
return arr;
}

// sort方法
function shuffle(arr) {
return arr.sort(() => {
return 0.5 - Math.random();
});
}

// test
shuffle([1, 2, 3, 4, 5]);

0 comments on commit 406e040

Please sign in to comment.