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
+22-22Lines changed: 22 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
The simple solution could be:
1
+
A solução simples pode ser:
2
2
3
3
```js run
4
4
*!*
@@ -12,18 +12,18 @@ 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
+
O código acima funciona porque `Math.random() - 0.5`é um número aleatório que pode ser positivo ou negativo, então a função de ordenação reordena os elementos aleatoriamente.
16
16
17
-
But because the sorting function is not meant to be used this way, not all permutations have the same probability.
17
+
Mas porque a função de ordenação não deve ser usada dessa maneira, nem todas as permutações têm a mesma probabilidade.
18
18
19
-
For instance, consider the code below. It runs`shuffle` 1000000 times and counts appearances of all possible results:
19
+
Por exemplo, considere o código abaixo. Ele executa`shuffle` 1000000 vezes e conta quantas foram as aparições de todos os resultados possíveis:
20
20
21
21
```js run
22
22
functionshuffle(array) {
23
23
array.sort(() =>Math.random() -0.5);
24
24
}
25
25
26
-
//counts of appearances for all possible permutations
26
+
//contagem de aparições de todos as permutações possíveis
27
27
let count = {
28
28
'123':0,
29
29
'132':0,
@@ -39,13 +39,13 @@ for (let i = 0; i < 1000000; i++) {
39
39
count[array.join('')]++;
40
40
}
41
41
42
-
//show counts of all possible permutations
42
+
//mostra a contagem de aparições de todos as permutações possíveis
43
43
for (let key in count) {
44
44
alert(`${key}: ${count[key]}`);
45
45
}
46
46
```
47
47
48
-
An example result (for V8, July 2017):
48
+
Um exemplo do resultado (for V8, July 2017):
49
49
50
50
```js
51
51
123:250706
@@ -56,30 +56,30 @@ An example result (for V8, July 2017):
56
56
321:125223
57
57
```
58
58
59
-
We can see the bias clearly: `123`and`213`appear much more often than others.
59
+
Podemos ver claramente: `123`e`213`aparece muito mais vezes do que os outros.
60
60
61
-
The result of the code may vary between JavaScript engines, but we can already see that the approach is unreliable.
61
+
O resultado do código pode variar entre as engines do JavaScript, mas já podemos ver que essa proposta não é confiável.
62
62
63
-
Why it doesn't work? Generally speaking, `sort`is a "black box": we throw an array and a comparison function into it and expect the array to be sorted. But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete implementation that differs between engines.
63
+
Por que não? Falando no geral, `sort`é uma "caixa preta": entregamos um array e uma função de comparação para ele e esperamos que o array seja ordenado. Porém, devido á aleatoriariedade total da comparação a caixa preta "enlouquece", e como exatamente ele "enlouquece" depende da implementação concreta que diferencia entre engines.
64
64
65
-
There are other good ways to do the task. For instance, there's a great algorithm called[Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). The idea is to walk the array in the reverse order and swap each element with a random one before it:
65
+
Há outras formas melhores para fazer essa atividade. Por exemplo, existe um ótimo algoritmo chamado[Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). A idéia é percorrer o array na ordem inversa e trocar cada elemento por um aleatório antes dele:
66
66
67
67
```js
68
68
functionshuffle(array) {
69
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
70
+
let j =Math.floor(Math.random() * (i +1)); // index aleatório de 0 á i
71
71
72
-
//swap elements array[i] and array[j]
73
-
//we use "destructuring assignment" syntax to achieve that
74
-
//you'll find more details about that syntax in later chapters
75
-
//same can be written as:
72
+
//troca os elementos do array[i] e do array[j]
73
+
//nós usamos a sintaxe "atribuição de desestruturação" para conseguir isso
74
+
//você vai encontrar mais detalhes sobre essa sintaxe em capítulos posteriores
75
+
//também pode ser escrito dessa forma:
76
76
// let t = array[i]; array[i] = array[j]; array[j] = t
77
77
[array[i], array[j]] = [array[j], array[i]];
78
78
}
79
79
}
80
80
```
81
81
82
-
Let's test it the same way:
82
+
Vamos testá-lo:
83
83
84
84
```js run
85
85
functionshuffle(array) {
@@ -89,7 +89,7 @@ function shuffle(array) {
89
89
}
90
90
}
91
91
92
-
//counts of appearances for all possible permutations
92
+
//contagem de aparições de todos as permutações possíveis
93
93
let count = {
94
94
'123':0,
95
95
'132':0,
@@ -105,13 +105,13 @@ for (let i = 0; i < 1000000; i++) {
105
105
count[array.join('')]++;
106
106
}
107
107
108
-
//show counts of all possible permutations
108
+
//mostra a contagem de aparições de todos as permutações possíveis
109
109
for (let key in count) {
110
110
alert(`${key}: ${count[key]}`);
111
111
}
112
112
```
113
113
114
-
The example output:
114
+
O resultado do exemplo:
115
115
116
116
```js
117
117
123:166693
@@ -122,6 +122,6 @@ The example output:
122
122
321:166316
123
123
```
124
124
125
-
Looks good now: all permutations appear with the same probability.
125
+
Parece bom agora: todas as permutações aparecem com a mesma probabilidade.
126
126
127
-
Also, performance-wise the Fisher-Yates algorithm is much better, there's no "sorting" overhead.
127
+
Além disso, em termos de performance, o algoritmo Fisher-Yates é muito melhor, não há sobrecarga de ordenação.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/05-array-methods/9-shuffle/task.md
+4-4Lines changed: 4 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,11 +2,11 @@ importance: 3
2
2
3
3
---
4
4
5
-
# Shuffle an array
5
+
# Embaralhe um array
6
6
7
-
Write the function`shuffle(array)`that shuffles (randomly reorders) elements of the array.
7
+
Escreva a função`shuffle(array)`que embaralha (reordena aleatoriamente) elementos do array.
8
8
9
-
Multiple runs of`shuffle`may lead to different orders of elements. For instance:
9
+
Múltiplas execuções de`shuffle`pode levar para diferentes ordenações dos elementos. Por exemplo:
10
10
11
11
```js
12
12
let arr = [1, 2, 3];
@@ -22,4 +22,4 @@ shuffle(arr);
22
22
// ...
23
23
```
24
24
25
-
All element orders should have an equal probability. For instance, `[1,2,3]`can be reordered as`[1,2,3]`or`[1,3,2]`or`[3,1,2]` etc, with equal probability of each case.
25
+
Todas as ordenações dos elementos deve ter uma probabilidade igual. Por exemplo, `[1,2,3]`pode ser reordenado como`[1,2,3]`ou`[1,3,2]`ou`[3,1,2]` etc, com probabilidade iguais para cada caso.
0 commit comments