Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions 1-js/05-data-types/02-number/1-sum-interface/solution.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@


```js run demo
let a = +prompt("The first number?", "");
let b = +prompt("The second number?", "");
let a = +prompt("O primeiro número?", "");
let b = +prompt("O segundo número?", "");

alert( a + b );
```

Note the unary plus `+` before `prompt`. It immediately converts the value to a number.
Observe o mais unário `+` antes de `prompt`. Ele converte o valor para um número imediatamente.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"mais unário" (aqui e nas linhas 193 e 388 do article.md) não bate com o termo do capítulo de operadores (1-js/02-first-steps/08-operators/article.md:128,132: "+ unário" / "positivo unário"). Vale padronizar para que o leitor reconheça o mesmo conceito.


Otherwise, `a` and `b` would be string their sum would be their concatenation, that is: `"1" + "2" = "12"`.
Caso contrário, `a` e `b` seriam strings e a soma delas seria a concatenação, ou seja: `"1" + "2" = "12"`.
6 changes: 3 additions & 3 deletions 1-js/05-data-types/02-number/1-sum-interface/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 5

---

# Sum numbers from the visitor
# Some os números do visitante

Create a script that prompts the visitor to enter two numbers and then shows their sum.
Crie um script que peça ao visitante para digitar dois números e depois mostre a soma deles.

[demo]

P.S. There is a gotcha with types.
P.S. Tem uma pegadinha relacionada a tipos.
18 changes: 9 additions & 9 deletions 1-js/05-data-types/02-number/2-why-rounded-down/solution.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
Internally the decimal fraction `6.35` is an endless binary. As always in such cases, it is stored with a precision loss.
Internamente, a fração decimal `6.35` é um binário infinito. Como sempre acontece nesses casos, ela é armazenada com perda de precisão.

Let's see:
Vamos ver:

```js run
alert( 6.35.toFixed(20) ); // 6.34999999999999964473
```

The precision loss can cause both increase and decrease of a number. In this particular case the number becomes a tiny bit less, that's why it rounded down.
A perda de precisão pode fazer um número tanto aumentar quanto diminuir. Nesse caso específico, o número fica um pouquinho menor, por isso ele foi arredondado para baixo.

And what's for `1.35`?
E quanto ao `1.35`?

```js run
alert( 1.35.toFixed(20) ); // 1.35000000000000008882
```

Here the precision loss made the number a little bit greater, so it rounded up.
Aqui a perda de precisão fez o número ficar um pouquinho maior, então ele foi arredondado para cima.

**How can we fix the problem with `6.35` if we want it to be rounded the right way?**
**Como podemos corrigir o problema com `6.35` se quisermos que ele seja arredondado da forma correta?**

We should bring it closer to an integer prior to rounding:
Devemos aproximá-lo de um número inteiro antes de arredondar:

```js run
alert( (6.35 * 10).toFixed(20) ); // 63.50000000000000000000
```

Note that `63.5` has no precision loss at all. That's because the decimal part `0.5` is actually `1/2`. Fractions divided by powers of `2` are exactly represented in the binary system, now we can round it:
Observe que `63.5` não tem nenhuma perda de precisão. Isso acontece porque a parte decimal `0.5` é, na verdade, `1/2`. Frações divididas por potências de `2` são representadas com exatidão no sistema binário, então agora podemos arredondar:


```js run
alert( Math.round(6.35 * 10) / 10 ); // 6.35 -> 63.5 -> 64(rounded) -> 6.4
alert( Math.round(6.35 * 10) / 10 ); // 6.35 -> 63.5 -> 64(arredondado) -> 6.4
```

10 changes: 5 additions & 5 deletions 1-js/05-data-types/02-number/2-why-rounded-down/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ importance: 4

---

# Why 6.35.toFixed(1) == 6.3?
# Por que 6.35.toFixed(1) == 6.3?

According to the documentation `Math.round` and `toFixed` both round to the nearest number: `0..4` lead down while `5..9` lead up.
De acordo com a documentação, tanto `Math.round` quanto `toFixed` arredondam para o número mais próximo: `0..4` arredondam para baixo, enquanto `5..9` arredondam para cima.

For instance:
Por exemplo:

```js run
alert( 1.35.toFixed(1) ); // 1.4
```

In the similar example below, why is `6.35` rounded to `6.3`, not `6.4`?
No exemplo parecido abaixo, por que `6.35` é arredondado para `6.3`, e não para `6.4`?

```js run
alert( 6.35.toFixed(1) ); // 6.3
```

How to round `6.35` the right way?
Como arredondar `6.35` da forma correta?

Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ function readNumber() {
let num;

do {
num = prompt("Enter a number please?", 0);
num = prompt("Digite um número, por favor?", 0);
} while ( !isFinite(num) );

if (num === null || num === '') return null;

return +num;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,29 @@ afterEach(function() {

describe("readNumber", function() {

it("if a number, returns it", function() {
it("se for um número, retorna ele", function() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"retorna ele" (aqui e na linha 16) usa o pronome reto como objeto, o que é coloquial e foge da norma. Sugiro "retorna o número" / "retorna 0" (ou "retorna-o").

prompt.returns("123");
assert.strictEqual(readNumber(), 123);
});

it("if 0, returns it", function() {
it("se for 0, retorna ele", function() {
prompt.returns("0");
assert.strictEqual(readNumber(), 0);
});

it("continues the loop until meets a number", function() {
prompt.onCall(0).returns("not a number");
prompt.onCall(1).returns("not a number again");
it("continua o laço até encontrar um número", function() {
prompt.onCall(0).returns("não é um número");
prompt.onCall(1).returns("não é um número de novo");
prompt.onCall(2).returns("1");
assert.strictEqual(readNumber(), 1);
});

it("if an empty line, returns null", function() {
it("se for uma linha vazia, retorna null", function() {
prompt.returns("");
assert.isNull(readNumber());
});

it("if cancel, returns null", function() {
it("se for cancelado, retorna null", function() {
prompt.returns(null);
assert.isNull(readNumber());
});
Expand Down
10 changes: 5 additions & 5 deletions 1-js/05-data-types/02-number/3-repeat-until-number/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ function readNumber() {
let num;

do {
num = prompt("Enter a number please?", 0);
num = prompt("Digite um número, por favor?", 0);
} while ( !isFinite(num) );

if (num === null || num === '') return null;

return +num;
}

alert(`Read: ${readNumber()}`);
alert(`Lido: ${readNumber()}`);
```

The solution is a little bit more intricate that it could be because we need to handle `null`/empty lines.
A solução é um pouco mais complexa do que poderia ser porque precisamos tratar os casos de `null`/linhas vazias.

So we actually accept the input until it is a "regular number". Both `null` (cancel) and empty line also fit that condition, because in numeric form they are `0`.
Então, na verdade, aceitamos a entrada até que ela seja um "número normal". Tanto `null` (cancelar) quanto a linha vazia também se encaixam nessa condição, porque, na forma numérica, eles são `0`.

After we stopped, we need to treat `null` and empty line specially (return `null`), because converting them to a number would return `0`.
Depois de parar, precisamos tratar `null` e a linha vazia de forma especial (retornando `null`), porque convertê-los para um número retornaria `0`.

8 changes: 4 additions & 4 deletions 1-js/05-data-types/02-number/3-repeat-until-number/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Repeat until the input is a number
# Repita até a entrada ser um número

Create a function `readNumber` which prompts for a number until the visitor enters a valid numeric value.
Crie uma função `readNumber` que peça um número repetidamente até o visitante digitar um valor numérico válido.

The resulting value must be returned as a number.
O valor resultante deve ser retornado como um número.

The visitor can also stop the process by entering an empty line or pressing "CANCEL". In that case, the function should return `null`.
O visitante também pode interromper o processo digitando uma linha vazia ou clicando em "CANCELAR". Nesse caso, a função deve retornar `null`.

[demo]

10 changes: 5 additions & 5 deletions 1-js/05-data-types/02-number/4-endless-loop-error/solution.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
That's because `i` would never equal `10`.
Isso acontece porque `i` nunca vai ser exatamente igual a `10`.

Run it to see the *real* values of `i`:
Rode o código para ver os valores *reais* de `i`:

```js run
let i = 0;
Expand All @@ -10,8 +10,8 @@ while (i < 11) {
}
```

None of them is exactly `10`.
Nenhum deles é exatamente `10`.

Such things happen because of the precision losses when adding fractions like `0.2`.
Esse tipo de coisa acontece por causa da perda de precisão ao somar frações como `0.2`.

Conclusion: evade equality checks when working with decimal fractions.
Conclusão: evite verificações de igualdade ao trabalhar com frações decimais.
4 changes: 2 additions & 2 deletions 1-js/05-data-types/02-number/4-endless-loop-error/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 4

---

# An occasional infinite loop
# Um laço infinito ocasional

This loop is infinite. It never ends. Why?
Este laço é infinito. Ele nunca termina. Por quê?

```js
let i = 0;
Expand Down
10 changes: 5 additions & 5 deletions 1-js/05-data-types/02-number/8-random-min-max/solution.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
We need to "map" all values from the interval 0..1 into values from `min` to `max`.
Precisamos "mapear" todos os valores do intervalo 0..1 para valores de `min` a `max`.

That can be done in two stages:
Isso pode ser feito em duas etapas:

1. If we multiply a random number from 0..1 by `max-min`, then the interval of possible values increases `0..1` to `0..max-min`.
2. Now if we add `min`, the possible interval becomes from `min` to `max`.
1. Se multiplicarmos um número aleatório de 0..1 por `max-min`, o intervalo de valores possíveis aumenta de `0..1` para `0..max-min`.
2. Agora, se somarmos `min`, o intervalo possível passa a ser de `min` a `max`.

The function:
A função:

```js run
function random(min, max) {
Expand Down
8 changes: 4 additions & 4 deletions 1-js/05-data-types/02-number/8-random-min-max/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 2

---

# A random number from min to max
# Um número aleatório de min a max

The built-in function `Math.random()` creates a random value from `0` to `1` (not including `1`).
A função nativa `Math.random()` cria um valor aleatório de `0` a `1` (sem incluir o `1`).

Write the function `random(min, max)` to generate a random floating-point number from `min` to `max` (not including `max`).
Escreva a função `random(min, max)` para gerar um número aleatório de ponto flutuante de `min` a `max` (sem incluir `max`).

Examples of its work:
Exemplos de funcionamento:

```js
alert( random(1, 5) ); // 1.2345623452
Expand Down
38 changes: 19 additions & 19 deletions 1-js/05-data-types/02-number/9-random-int-min-max/solution.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# The simple but wrong solution
# A solução simples, mas errada

The simplest, but wrong solution would be to generate a value from `min` to `max` and round it:
A solução mais simples, porém errada, seria gerar um valor de `min` a `max` e arredondá-lo:

```js run
function randomInteger(min, max) {
Expand All @@ -11,28 +11,28 @@ function randomInteger(min, max) {
alert( randomInteger(1, 3) );
```

The function works, but it is incorrect. The probability to get edge values `min` and `max` is two times less than any other.
A função funciona, mas está incorreta. A probabilidade de obter os valores extremos `min` e `max` é metade da probabilidade de obter qualquer outro valor.

If you run the example above many times, you would easily see that `2` appears the most often.
Se você rodar o exemplo acima muitas vezes, vai perceber facilmente que o `2` aparece com mais frequência.

That happens because `Math.round()` gets random numbers from the interval `1..3` and rounds them as follows:
Isso acontece porque `Math.round()` pega números aleatórios do intervalo `1..3` e os arredonda da seguinte forma:

```js no-beautify
values from 1 ... to 1.4999999999 become 1
values from 1.5 ... to 2.4999999999 become 2
values from 2.5 ... to 2.9999999999 become 3
valores de 1 ... até 1.4999999999 viram 1
valores de 1.5 ... até 2.4999999999 viram 2
valores de 2.5 ... até 2.9999999999 viram 3
```

Now we can clearly see that `1` gets twice less values than `2`. And the same with `3`.
Agora podemos ver claramente que `1` recebe metade dos valores que `2` recebe. E o mesmo vale para `3`.

# The correct solution
# A solução correta

There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from `0.5 to 3.5`, thus adding the required probabilities to the edges:
Existem muitas soluções corretas para essa tarefa. Uma delas é ajustar os limites do intervalo. Para garantir intervalos iguais, podemos gerar valores de `0.5 a 3.5`, adicionando assim as probabilidades necessárias às extremidades:

```js run
*!*
function randomInteger(min, max) {
// now rand is from (min-0.5) to (max+0.5)
// agora rand vai de (min-0.5) a (max+0.5)
let rand = min - 0.5 + Math.random() * (max - min + 1);
return Math.round(rand);
}
Expand All @@ -41,12 +41,12 @@ function randomInteger(min, max) {
alert( randomInteger(1, 3) );
```

An alternative way could be to use `Math.floor` for a random number from `min` to `max+1`:
Uma forma alternativa seria usar `Math.floor` para um número aleatório de `min` a `max+1`:

```js run
*!*
function randomInteger(min, max) {
// here rand is from min to (max+1)
// aqui rand vai de min a (max+1)
let rand = min + Math.random() * (max + 1 - min);
return Math.floor(rand);
}
Expand All @@ -55,12 +55,12 @@ function randomInteger(min, max) {
alert( randomInteger(1, 3) );
```

Now all intervals are mapped this way:
Agora todos os intervalos são mapeados desta forma:

```js no-beautify
values from 1 ... to 1.9999999999 become 1
values from 2 ... to 2.9999999999 become 2
values from 3 ... to 3.9999999999 become 3
valores de 1 ... até 1.9999999999 viram 1
valores de 2 ... até 2.9999999999 viram 2
valores de 3 ... até 3.9999999999 viram 3
```

All intervals have the same length, making the final distribution uniform.
Todos os intervalos têm o mesmo tamanho, o que torna a distribuição final uniforme.
10 changes: 5 additions & 5 deletions 1-js/05-data-types/02-number/9-random-int-min-max/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ importance: 2

---

# A random integer from min to max
# Um inteiro aleatório de min a max

Create a function `randomInteger(min, max)` that generates a random *integer* number from `min` to `max` including both `min` and `max` as possible values.
Crie uma função `randomInteger(min, max)` que gere um número *inteiro* aleatório de `min` a `max`, incluindo tanto `min` quanto `max` como valores possíveis.

Any number from the interval `min..max` must appear with the same probability.
Qualquer número do intervalo `min..max` deve aparecer com a mesma probabilidade.


Examples of its work:
Exemplos de funcionamento:

```js
alert( randomInteger(1, 5) ); // 1
alert( randomInteger(1, 5) ); // 3
alert( randomInteger(1, 5) ); // 5
```

You can use the solution of the [previous task](info:task/random-min-max) as the base.
Você pode usar a solução da [tarefa anterior](info:task/random-min-max) como base.
Loading