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
4 changes: 2 additions & 2 deletions 1-js/05-data-types/04-array/1-item-value/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The result is `4`:
O resultado é `4`:


```js run
Expand All @@ -13,5 +13,5 @@ alert( fruits.length ); // 4
*/!*
```

That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array.
Isso acontece porque arrays são objetos. Então tanto `shoppingCart` quanto `fruits` são referências para o mesmo array.

8 changes: 4 additions & 4 deletions 1-js/05-data-types/04-array/1-item-value/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ importance: 3

---

# Is array copied?
# O array é copiado?

What is this code going to show?
O que esse código vai mostrar?

```js
let fruits = ["Apples", "Pear", "Orange"];

// push a new value into the "copy"
// insere um novo valor na "cópia"
let shoppingCart = fruits;
shoppingCart.push("Banana");

// what's in fruits?
// o que tem em fruits?
alert( fruits.length ); // ?
```

18 changes: 9 additions & 9 deletions 1-js/05-data-types/04-array/10-maximal-subarray/_js.view/test.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
describe("getMaxSubSum", function() {
it("maximal subsum of [1, 2, 3] equals 6", function() {
it("subsoma máxima de [1, 2, 3] é igual a 6", function() {
assert.equal(getMaxSubSum([1, 2, 3]), 6);
});

it("maximal subsum of [-1, 2, 3, -9] equals 5", function() {
it("subsoma máxima de [-1, 2, 3, -9] é igual a 5", function() {
assert.equal(getMaxSubSum([-1, 2, 3, -9]), 5);
});

it("maximal subsum of [-1, 2, 3, -9, 11] equals 11", function() {
it("subsoma máxima de [-1, 2, 3, -9, 11] é igual a 11", function() {
assert.equal(getMaxSubSum([-1, 2, 3, -9, 11]), 11);
});

it("maximal subsum of [-2, -1, 1, 2] equals 3", function() {
it("subsoma máxima de [-2, -1, 1, 2] é igual a 3", function() {
assert.equal(getMaxSubSum([-2, -1, 1, 2]), 3);
});

it("maximal subsum of [100, -9, 2, -3, 5] equals 100", function() {
it("subsoma máxima de [100, -9, 2, -3, 5] é igual a 100", function() {
assert.equal(getMaxSubSum([100, -9, 2, -3, 5]), 100);
});

it("maximal subsum of [] equals 0", function() {
it("subsoma máxima de [] é igual a 0", function() {
assert.equal(getMaxSubSum([]), 0);
});

it("maximal subsum of [-1] equals 0", function() {
it("subsoma máxima de [-1] é igual a 0", function() {
assert.equal(getMaxSubSum([-1]), 0);
});

it("maximal subsum of [-1, -2] equals 0", function() {
it("subsoma máxima de [-1, -2] é igual a 0", function() {
assert.equal(getMaxSubSum([-1, -2]), 0);
});

it("maximal subsum of [2, -8, 5, -1, 2, -3, 2] equals 6", function() {
it("subsoma máxima de [2, -8, 5, -1, 2, -3, 2] é igual a 6", function() {
assert.equal(getMaxSubSum([2, -8, 5, -1, 2, -3, 2]), 6);
});
});
44 changes: 22 additions & 22 deletions 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
# Slow solution
# Solução lenta

We can calculate all possible subsums.
Podemos calcular todas as somas parciais possíveis.

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.

"subsums" virou "somas parciais" aqui e na linha 36, mas o test.js usa "subsoma", e a solução rápida (linha 66) usa "soma parcial" para outro conceito (partialSum, o acumulador que é zerado). O leitor pode confundir as duas ideias. Sugestão: usar "subsomas" de forma consistente.

Suggested change
Podemos calcular todas as somas parciais possíveis.
Podemos calcular todas as subsomas possíveis.


The simplest way is to take every element and calculate sums of all subarrays starting from it.
A forma mais simples é pegar cada elemento e calcular as somas de todos os subarrays a partir dele.

For instance, for `[-1, 2, 3, -9, 11]`:
Por exemplo, para `[-1, 2, 3, -9, 11]`:

```js no-beautify
// Starting from -1:
// Começando a partir de -1:
-1
-1 + 2
-1 + 2 + 3
-1 + 2 + 3 + (-9)
-1 + 2 + 3 + (-9) + 11

// Starting from 2:
// Começando a partir de 2:
2
2 + 3
2 + 3 + (-9)
2 + 3 + (-9) + 11

// Starting from 3:
// Começando a partir de 3:
3
3 + (-9)
3 + (-9) + 11

// Starting from -9
// Começando a partir de -9
-9
-9 + 11

// Starting from 11
// Começando a partir de 11
11
```

The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element.
O código, na verdade, é um laço aninhado: o laço externo percorre os elementos do array, e o interno conta as somas parciais começando pelo elemento atual.

```js run
function getMaxSubSum(arr) {
let maxSum = 0; // if we take no elements, zero will be returned
let maxSum = 0; // se não pegarmos nenhum elemento, zero será retornado

for (let i = 0; i < arr.length; i++) {
let sumFixedStart = 0;
Expand All @@ -57,25 +57,25 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
```

The solution has a time complexity of [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.
A solução tem complexidade de tempo [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). Em outras palavras, se aumentarmos o tamanho do array 2 vezes, o algoritmo vai demorar 4 vezes mais.

For big arrays (1000, 10000 or more items) such algorithms can lead to serious sluggishness.
Para arrays grandes (1000, 10000 ou mais itens), algoritmos assim podem causar uma lentidão séria.

# Fast solution
# Solução rápida

Let's walk the array and keep the current partial sum of elements in the variable `s`. If `s` becomes negative at some point, then assign `s=0`. The maximum of all such `s` will be the answer.
Vamos percorrer o array e manter a soma parcial atual dos elementos na variável `s`. Se `s` se tornar negativa em algum momento, então atribuímos `s=0`. O maior valor entre todos esses `s` será a resposta.

If the description is too vague, please see the code, it's short enough:
Se a descrição estiver vaga demais, veja o código, ele é curto o suficiente:

```js run demo
function getMaxSubSum(arr) {
let maxSum = 0;
let partialSum = 0;

for (let item of arr) { // for each item of arr
partialSum += item; // add it to partialSum
maxSum = Math.max(maxSum, partialSum); // remember the maximum
if (partialSum < 0) partialSum = 0; // zero if negative
for (let item of arr) { // para cada item de arr
partialSum += item; // adiciona ele ao partialSum
maxSum = Math.max(maxSum, partialSum); // guarda o máximo
if (partialSum < 0) partialSum = 0; // zera se for negativo
}

return maxSum;
Expand All @@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([-1, -2, -3]) ); // 0
```

The algorithm requires exactly 1 array pass, so the time complexity is O(n).
O algoritmo exige exatamente 1 passagem pelo array, então a complexidade de tempo é O(n).

You can find more detailed information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words.
Você pode encontrar informações mais detalhadas sobre o algoritmo aqui: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). Se ainda não estiver óbvio por que isso funciona, tente rastrear o algoritmo nos exemplos acima, veja como ele funciona, isso é melhor do que qualquer explicação.
18 changes: 9 additions & 9 deletions 1-js/05-data-types/04-array/10-maximal-subarray/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,29 @@ importance: 2

---

# A maximal subarray
# Um subarray máximo

The input is an array of numbers, e.g. `arr = [1, -2, 3, 4, -9, 6]`.
A entrada é um array de números, ex.: `arr = [1, -2, 3, 4, -9, 6]`.

The task is: find the contiguous subarray of `arr` with the maximal sum of items.
A tarefa é: encontrar o subarray contíguo de `arr` com a maior soma de itens.

Write the function `getMaxSubSum(arr)` that will return that sum.
Escreva a função `getMaxSubSum(arr)` que retornará essa soma.

For instance:
Por exemplo:

```js
getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighted items)
getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (a soma dos itens destacados)
getMaxSubSum([*!*2, -1, 2, 3*/!*, -9]) == 6
getMaxSubSum([-1, 2, 3, -9, *!*11*/!*]) == 11
getMaxSubSum([-2, -1, *!*1, 2*/!*]) == 3
getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100
getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all)
getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (pega todos)
```

If all items are negative, it means that we take none (the subarray is empty), so the sum is zero:
Se todos os itens forem negativos, significa que não pegamos nenhum (o subarray está vazio), então a soma é zero:

```js
getMaxSubSum([-1, -2, -3]) = 0
```

Please try to think of a fast solution: [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation) or even O(n) if you can.
Tente pensar numa solução rápida: [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation) ou até O(n), se conseguir.
16 changes: 8 additions & 8 deletions 1-js/05-data-types/04-array/2-create-array/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Array operations.
# Operações com array.

Let's try 5 array operations.
Vamos tentar 5 operações com array.

1. Create an array `styles` with items "Jazz" and "Blues".
2. Append "Rock-n-Roll" to the end.
3. Replace the value in the middle with "Classics". Your code for finding the middle value should work for any arrays with odd length.
4. Strip off the first value of the array and show it.
5. Prepend `Rap` and `Reggae` to the array.
1. Crie um array `styles` com os itens "Jazz" e "Blues".
2. Acrescente "Rock-n-Roll" ao final.
3. Substitua o valor do meio por "Classics". Seu código para encontrar o valor do meio deve funcionar para qualquer array de tamanho ímpar.
4. Remova o primeiro valor do array e mostre-o.
5. Adicione `Rap` e `Reggae` no início do array.

The array in the process:
O array durante o processo:

```js no-beautify
Jazz, Blues
Expand Down
6 changes: 3 additions & 3 deletions 1-js/05-data-types/04-array/3-call-array-this/solution.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The call `arr[2]()` is syntactically the good old `obj[method]()`, in the role of `obj` we have `arr`, and in the role of `method` we have `2`.
A chamada `arr[2]()` é, sintaticamente, o bom e velho `obj[method]()`, no papel de `obj` temos `arr`, e no papel de `method` temos `2`.

So we have a call of the function `arr[2]` as an object method. Naturally, it receives `this` referencing the object `arr` and outputs the array:
Então temos uma chamada da função `arr[2]` como um método de objeto. Naturalmente, ela recebe `this` referenciando o objeto `arr` e exibe o array:

```js run
let arr = ["a", "b"];
Expand All @@ -12,4 +12,4 @@ arr.push(function() {
arr[2](); // a,b,function(){...}
```

The array has 3 values: initially it had two, plus the function.
O array tem 3 valores: inicialmente tinha dois, mais a função.
4 changes: 2 additions & 2 deletions 1-js/05-data-types/04-array/3-call-array-this/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Calling in an array context
# Chamando no contexto de um array

What is the result? Why?
Qual é o resultado? Por quê?

```js
let arr = ["a", "b"];
Expand Down
6 changes: 3 additions & 3 deletions 1-js/05-data-types/04-array/5-array-input-sum/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Please note the subtle, but important detail of the solution. We don't convert `value` to number instantly after `prompt`, because after `value = +value` we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead.
Observe o detalhe sutil, mas importante, da solução. Não convertemos `value` para número logo depois do `prompt`, porque depois de `value = +value` não conseguiríamos mais distinguir uma string vazia (sinal de parada) do zero (número válido). Fazemos isso mais tarde, em vez disso.

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.

Redundância: "mais tarde, em vez disso".

Suggested change
Observe o detalhe sutil, mas importante, da solução. Não convertemos `value` para número logo depois do `prompt`, porque depois de `value = +value` não conseguiríamos mais distinguir uma string vazia (sinal de parada) do zero (número válido). Fazemos isso mais tarde, em vez disso.
Observe o detalhe sutil, mas importante, da solução. Não convertemos `value` para número logo depois do `prompt`, porque depois de `value = +value` não conseguiríamos mais distinguir uma string vazia (sinal de parada) do zero (número válido). Em vez disso, fazemos isso mais tarde.



```js run demo
Expand All @@ -8,9 +8,9 @@ function sumInput() {

while (true) {

let value = prompt("A number please?", 0);
let value = prompt("Um número, por favor?", 0);

// should we cancel?
// devemos cancelar?
if (value === "" || value === null || !isFinite(value)) break;

numbers.push(+value);
Expand Down
12 changes: 6 additions & 6 deletions 1-js/05-data-types/04-array/5-array-input-sum/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ importance: 4

---

# Sum input numbers
# Soma os números digitados

Write the function `sumInput()` that:
Escreva a função `sumInput()` que:

- Asks the user for values using `prompt` and stores the values in the array.
- Finishes asking when the user enters a non-numeric value, an empty string, or presses "Cancel".
- Calculates and returns the sum of array items.
- Pede valores ao usuário usando `prompt` e armazena os valores no array.
- Para de pedir quando o usuário digita um valor não numérico, uma string vazia, ou clica em "Cancelar".
- Calcula e retorna a soma dos itens do array.

P.S. A zero `0` is a valid number, please don't stop the input on zero.
P.S. Um zero `0` é um número válido, por favor não pare a entrada ao receber zero.

[demo]
Loading