Skip to content

Commit 10927ec

Browse files
authored
Merge pull request javascript-tutorial#255 from usernamehw/patch-9
Update solution.md
2 parents 0832633 + 13719f8 commit 10927ec

File tree

1 file changed

+9
-9
lines changed
  • 1-js/05-data-types/05-array-methods/9-shuffle

1 file changed

+9
-9
lines changed

1-js/05-data-types/05-array-methods/9-shuffle/solution.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ shuffle(arr);
1212
alert(arr);
1313
```
1414

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.
1616

1717
But because the sorting function is not meant to be used this way, not all permutations have the same probability.
1818

@@ -33,14 +33,14 @@ let count = {
3333
'312': 0
3434
};
3535

36-
for(let i = 0; i < 1000000; i++) {
36+
for (let i = 0; i < 1000000; i++) {
3737
let array = [1, 2, 3];
3838
shuffle(array);
3939
count[array.join('')]++;
4040
}
4141

4242
// show counts of all possible permutations
43-
for(let key in count) {
43+
for (let key in count) {
4444
alert(`${key}: ${count[key]}`);
4545
}
4646
```
@@ -66,8 +66,8 @@ There are other good ways to do the task. For instance, there's a great algorith
6666

6767
```js
6868
function shuffle(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
7171
[array[i], array[j]] = [array[j], array[i]]; // swap elements
7272
}
7373
}
@@ -77,8 +77,8 @@ Let's test it the same way:
7777

7878
```js run
7979
function shuffle(array) {
80-
for(let i = array.length - 1; i > 0; i--) {
81-
let j = Math.floor(Math.random() * (i+1));
80+
for (let i = array.length - 1; i > 0; i--) {
81+
let j = Math.floor(Math.random() * (i + 1));
8282
[array[i], array[j]] = [array[j], array[i]];
8383
}
8484
}
@@ -93,14 +93,14 @@ let count = {
9393
'312': 0
9494
};
9595

96-
for(let i = 0; i < 1000000; i++) {
96+
for (let i = 0; i < 1000000; i++) {
9797
let array = [1, 2, 3];
9898
shuffle(array);
9999
count[array.join('')]++;
100100
}
101101

102102
// show counts of all possible permutations
103-
for(let key in count) {
103+
for (let key in count) {
104104
alert(`${key}: ${count[key]}`);
105105
}
106106
```

0 commit comments

Comments
 (0)