Skip to content

Commit b464660

Browse files
author
Adria Vieira
committed
shuffle task translated
1 parent dfaaada commit b464660

File tree

2 files changed

+26
-26
lines changed

2 files changed

+26
-26
lines changed

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

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The simple solution could be:
1+
A solução simples pode ser:
22

33
```js run
44
*!*
@@ -12,18 +12,18 @@ 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+
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.
1616

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

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:
2020

2121
```js run
2222
function shuffle(array) {
2323
array.sort(() => Math.random() - 0.5);
2424
}
2525

26-
// counts of appearances for all possible permutations
26+
// contagem de aparições de todos as permutações possíveis
2727
let count = {
2828
'123': 0,
2929
'132': 0,
@@ -39,13 +39,13 @@ for (let i = 0; i < 1000000; i++) {
3939
count[array.join('')]++;
4040
}
4141

42-
// show counts of all possible permutations
42+
// mostra a contagem de aparições de todos as permutações possíveis
4343
for (let key in count) {
4444
alert(`${key}: ${count[key]}`);
4545
}
4646
```
4747

48-
An example result (for V8, July 2017):
48+
Um exemplo do resultado (for V8, July 2017):
4949

5050
```js
5151
123: 250706
@@ -56,30 +56,30 @@ An example result (for V8, July 2017):
5656
321: 125223
5757
```
5858

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

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

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

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:
6666

6767
```js
6868
function shuffle(array) {
6969
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
7171

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:
7676
// let t = array[i]; array[i] = array[j]; array[j] = t
7777
[array[i], array[j]] = [array[j], array[i]];
7878
}
7979
}
8080
```
8181

82-
Let's test it the same way:
82+
Vamos testá-lo:
8383

8484
```js run
8585
function shuffle(array) {
@@ -89,7 +89,7 @@ function shuffle(array) {
8989
}
9090
}
9191

92-
// counts of appearances for all possible permutations
92+
// contagem de aparições de todos as permutações possíveis
9393
let count = {
9494
'123': 0,
9595
'132': 0,
@@ -105,13 +105,13 @@ for (let i = 0; i < 1000000; i++) {
105105
count[array.join('')]++;
106106
}
107107

108-
// show counts of all possible permutations
108+
// mostra a contagem de aparições de todos as permutações possíveis
109109
for (let key in count) {
110110
alert(`${key}: ${count[key]}`);
111111
}
112112
```
113113

114-
The example output:
114+
O resultado do exemplo:
115115

116116
```js
117117
123: 166693
@@ -122,6 +122,6 @@ The example output:
122122
321: 166316
123123
```
124124

125-
Looks good now: all permutations appear with the same probability.
125+
Parece bom agora: todas as permutações aparecem com a mesma probabilidade.
126126

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.

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 3
22

33
---
44

5-
# Shuffle an array
5+
# Embaralhe um array
66

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

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:
1010

1111
```js
1212
let arr = [1, 2, 3];
@@ -22,4 +22,4 @@ shuffle(arr);
2222
// ...
2323
```
2424

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

Comments
 (0)