-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshuffle-benchmark.js
89 lines (73 loc) · 1.72 KB
/
shuffle-benchmark.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// prettier-ignore
let cards = [
'3c', '3s', '3h', '3d',
'4c', '4s', '4h', '4d',
'5c', '5s', '5h', '5d',
'6c', '6s', '6h', '6d',
'7c', '7s', '7h', '7d',
'8c', '8s', '8h', '8d',
'9c', '9s', '9h', '9d',
'Tc', 'Ts', 'Th', 'Td',
'Jc', 'Js', 'Jh', 'Jd',
'Qc', 'Qs', 'Qh', 'Qd',
'Kc', 'Ks', 'Kh', 'Kd',
'Ac', 'As', 'Ah', 'Ad',
'2c', '2s', '2h', '2d',
]
function shuffle(array) {
var m = array.length,
t,
i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function shuffle2(array) {
var copy = [],
n = array.length,
i;
// While there remain elements to shuffle…
while (n) {
// Pick a remaining element…
i = Math.floor(Math.random() * array.length);
// If not already shuffled, move it to the new array.
if (i in array) {
copy.push(array[i]);
delete array[i];
n--;
}
}
return copy;
}
function shuffle3(array) {
var copy = [],
n = array.length,
i;
// While there remain elements to shuffle…
while (n) {
// Pick a remaining element…
i = Math.floor(Math.random() * n--);
// And move it to the new array.
copy.push(array.splice(i, 1)[0]);
}
return copy;
}
console.time("shuffle1");
cards = shuffle(cards);
console.timeEnd("shuffle1");
console.log(cards.length);
console.time("shuffle2");
cards = shuffle2(cards);
console.timeEnd("shuffle2");
console.log(cards.length);
console.time("shuffle3");
cards = shuffle3(cards);
console.timeEnd("shuffle3");
console.log(cards.length);