You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/05-data-types/05-array-methods/9-shuffle/solution.md
+9-9Lines changed: 9 additions & 9 deletions
Original file line number
Diff line number
Diff line change
@@ -12,7 +12,7 @@ shuffle(arr);
12
12
alert(arr);
13
13
```
14
14
15
-
That somewhat works, because `Math.random()-0.5` is a random number that may be positive or negative, so the sorting function reorders elements randomly.
15
+
That somewhat works, because `Math.random() - 0.5` is a random number that may be positive or negative, so the sorting function reorders elements randomly.
16
16
17
17
But because the sorting function is not meant to be used this way, not all permutations have the same probability.
18
18
@@ -33,14 +33,14 @@ let count = {
33
33
'312':0
34
34
};
35
35
36
-
for(let i =0; i <1000000; i++) {
36
+
for(let i =0; i <1000000; i++) {
37
37
let array = [1, 2, 3];
38
38
shuffle(array);
39
39
count[array.join('')]++;
40
40
}
41
41
42
42
// show counts of all possible permutations
43
-
for(let key in count) {
43
+
for(let key in count) {
44
44
alert(`${key}: ${count[key]}`);
45
45
}
46
46
```
@@ -66,8 +66,8 @@ There are other good ways to do the task. For instance, there's a great algorith
66
66
67
67
```js
68
68
functionshuffle(array) {
69
-
for(let i =array.length-1; i >0; i--) {
70
-
let j =Math.floor(Math.random() * (i+1)); // random index from 0 to i
69
+
for(let i =array.length-1; i >0; i--) {
70
+
let j =Math.floor(Math.random() * (i+1)); // random index from 0 to i
71
71
[array[i], array[j]] = [array[j], array[i]]; // swap elements
0 commit comments