chore(i18n,curriculum): update translations (#43089)

This commit is contained in:
camperbot
2021-08-02 23:05:44 +09:00
committed by GitHub
parent 3350cb4522
commit 6b82f3831c
123 changed files with 1300 additions and 1301 deletions

View File

@ -17,15 +17,15 @@ dashedName: override-styles-in-subsequent-css
創建一個 `blue-text` class將元素的顏色設置爲藍色。 將它放在 `pink-text` class 下面。
創建一個字體顏色爲 `blue``blue-text` class並確保它在 `pink-text` 下方聲明
`blue-text` class 應用於 `h1` 元素,看看它和該元素上的 `pink-text` class 哪一個會優先顯示
HTML 同時應用多個 class 屬性需以空格來間隔,例子如下:
多個 class 屬性應用於一個 HTML 元素,需以空格來間隔這些屬性,例如:
```html
class="class1 class2"
```
**注意:**HTML 元素裏應用的 class 的先後順序無關緊要。
**注意:** HTML 元素裏應用的 class 的先後順序無關緊要。
但是,在 `<style>` 標籤裏面聲明的 `class` 順序十分重要,之後的聲明會覆蓋之前的聲明。 第二個聲明的優先級始終高於第一個聲明。 由於 `.blue-text` 是在後面聲明的,所以它的樣式會覆蓋 `.pink-text` 裏的樣式。

View File

@ -47,7 +47,7 @@ assert(
);
```
新建的`p` 元素應包含 `kitty ipsum text` 的前面幾個詞。
你的 `p` 元素應包含 `kitty ipsum` 文本的前面幾個詞。
```js
assert.isTrue(/Purr\s+jump\s+eat/gi.test($('p').text()));

View File

@ -51,7 +51,7 @@ assert($('footer').length == 1);
assert($('a').eq(0).attr('href') == '#footer');
```
`a` 的內容文本應爲 `Jump to Bottom`
`a` 標籤不應有 `target` 屬性
```js
assert(

View File

@ -8,24 +8,28 @@ dashedName: reuse-patterns-using-capture-groups
# --description--
一些你所搜尋的匹配模式會在字符串中出現多次。 手動重複該正則表達式顯得不夠簡潔。 當字符串中出現多個重複子字符串時,有一種更好的方式來編寫模式。
可以使用捕獲組(<dfn>capture groups</dfn>)搜尋重複的子字符串。 括號 `(``)` 可以用來匹配重複的子字符串。 把需要重複匹配的模式放在括號中即可。
要指定重複字符串將出現的位置,可以使用反斜槓(`\`)後接一個數字。 這個數字從 1 開始,隨着你使用的每個捕獲組的增加而增加。 這裏有一個示例,`\1` 可以匹配第一個組。
下面的示例展示的是匹配被空格隔開的兩個相同單詞:
當你想要匹配一個像下面這樣多次出現的單詞,
```js
let repeatStr = "regex regex";
let repeatRegex = /(\w+)\s\1/;
repeatRegex.test(repeatStr);
repeatStr.match(repeatRegex);
let repeatStr = "row row row your boat";
```
`test` 調用將返回 `true``match` 調用將返回 `["regex regex", "regex"]`
你可以使用 `/row row row/`。但如果你不知道重複的特定單詞,怎麼辦? <dfn>捕獲組</dfn> 可以用於找到重複的子字符串
捕獲組是通過把要捕獲的正則表達式放在括號中來構建的。 在這個例子裏, 目標是捕獲一個包含字母數字字符的詞,所以捕獲組是將 `\w+` 放在括號中:`/(\w+)/`
分組匹配的子字符串被保存到一個臨時的“變量”, 可以使用同一正則表達式和反斜線及捕獲組的編號來訪問它(例如:`\1`)。 捕獲組按其開頭括號的位置自動編號(從左到右),從 1 開始。
下面的示例是匹配被空格隔開的兩個相同單詞:
```js
let repeatRegex = /(\w+) \1 \1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row", "row"]
```
在字符串上調用 `.match()` 方法將返回一個數組,其中包含它最終匹配到的子字符串及其捕獲組。
在字符串上調用 `.match()` 方法將返回一個數組,其中包含它最終匹配到的字符串及其捕獲組。
# --instructions--

View File

@ -11,7 +11,7 @@ dashedName: target-html-elements-with-selectors-using-jquery
# --description--
現在已經有了 `document ready function`
現在我們有一個 `document ready` 函數
首先,完成第一個 jQuery 語句。 所有的 jQuery 函數都以 `$` 開頭這個符號通常被稱爲美元符號dollar sign operator或 bling。

View File

@ -17,15 +17,15 @@ dashedName: override-styles-in-subsequent-css
创建一个 `blue-text` class将元素的颜色设置为蓝色。 将它放在 `pink-text` class 下面。
创建一个字体颜色为 `blue``blue-text` class并确保它在 `pink-text` 下方声明
`blue-text` class 应用于 `h1` 元素,看看它和该元素上的 `pink-text` class 哪一个会优先显示
HTML 同时应用多个 class 属性需以空格来间隔,例子如下:
多个 class 属性应用于一个 HTML 元素,需以空格来间隔这些属性,例如:
```html
class="class1 class2"
```
**注意:**HTML 元素里应用的 class 的先后顺序无关紧要。
**注意:** HTML 元素里应用的 class 的先后顺序无关紧要。
但是,在 `<style>` 标签里面声明的 `class` 顺序十分重要,之后的声明会覆盖之前的声明。 第二个声明的优先级始终高于第一个声明。 由于 `.blue-text` 是在后面声明的,所以它的样式会覆盖 `.pink-text` 里的样式。

View File

@ -47,7 +47,7 @@ assert(
);
```
新建的`p` 元素应包含 `kitty ipsum text` 的前面几个词。
你的 `p` 元素应包含 `kitty ipsum` 文本的前面几个词。
```js
assert.isTrue(/Purr\s+jump\s+eat/gi.test($('p').text()));

View File

@ -51,7 +51,7 @@ assert($('footer').length == 1);
assert($('a').eq(0).attr('href') == '#footer');
```
`a` 的内容文本应为 `Jump to Bottom`
`a` 标签不应有 `target` 属性
```js
assert(

View File

@ -8,24 +8,28 @@ dashedName: reuse-patterns-using-capture-groups
# --description--
一些你所搜寻的匹配模式会在字符串中出现多次。 手动重复该正则表达式显得不够简洁。 当字符串中出现多个重复子字符串时,有一种更好的方式来编写模式。
可以使用捕获组(<dfn>capture groups</dfn>)搜寻重复的子字符串。 括号 `(``)` 可以用来匹配重复的子字符串。 把需要重复匹配的模式放在括号中即可。
要指定重复字符串将出现的位置,可以使用反斜杠(`\`)后接一个数字。 这个数字从 1 开始,随着你使用的每个捕获组的增加而增加。 这里有一个示例,`\1` 可以匹配第一个组。
下面的示例展示的是匹配被空格隔开的两个相同单词:
当你想要匹配一个像下面这样多次出现的单词,
```js
let repeatStr = "regex regex";
let repeatRegex = /(\w+)\s\1/;
repeatRegex.test(repeatStr);
repeatStr.match(repeatRegex);
let repeatStr = "row row row your boat";
```
`test` 调用将返回 `true``match` 调用将返回 `["regex regex", "regex"]`
你可以使用 `/row row row/`。但如果你不知道重复的特定单词,怎么办? <dfn>捕获组</dfn> 可以用于找到重复的子字符串
捕获组是通过把要捕获的正则表达式放在括号中来构建的。 在这个例子里, 目标是捕获一个包含字母数字字符的词,所以捕获组是将 `\w+` 放在括号中:`/(\w+)/`
分组匹配的子字符串被保存到一个临时的“变量”, 可以使用同一正则表达式和反斜线及捕获组的编号来访问它(例如:`\1`)。 捕获组按其开头括号的位置自动编号(从左到右),从 1 开始。
下面的示例是匹配被空格隔开的两个相同单词:
```js
let repeatRegex = /(\w+) \1 \1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row", "row"]
```
在字符串上调用 `.match()` 方法将返回一个数组,其中包含它最终匹配到的子字符串及其捕获组。
在字符串上调用 `.match()` 方法将返回一个数组,其中包含它最终匹配到的字符串及其捕获组。
# --instructions--

View File

@ -11,7 +11,7 @@ dashedName: target-html-elements-with-selectors-using-jquery
# --description--
现在已经有了 `document ready function`
现在我们有一个 `document ready` 函数
首先,完成第一个 jQuery 语句。 所有的 jQuery 函数都以 `$` 开头这个符号通常被称为美元符号dollar sign operator或 bling。

View File

@ -1,6 +1,6 @@
---
id: 587d825a367417b2b2512c87
title: Create a Doubly Linked List
title: Creare una lista doppiamente concatenata
challengeType: 1
forumTopicId: 301626
dashedName: create-a-doubly-linked-list
@ -8,19 +8,19 @@ dashedName: create-a-doubly-linked-list
# --description--
All of the linked lists we've created so far are singly linked lists. Here, we'll create a <dfn>doubly linked list</dfn>. As the name implies, nodes in a doubly linked list have references to the next and previous node in the list.
Tutte le liste concatenate che abbiamo creato finora sono liste semplicemente concatenate. Qui, creeremo una lista <dfn>doppiamente concatenata</dfn>. Come suggerisce il nome, i nodi in una lista doppiamente concatenata hanno dei riferimenti ai nodi successivo e precedente nella lista.
This allows us to traverse the list in both directions but it also requires more memory to be used because every node must contain an additional reference to the previous node in the list.
Questo ci permette di attraversare la lista in entrambe le direzioni, ma richiede anche più memoria perché ogni nodo deve contenere un riferimento aggiuntivo al nodo precedente nella lista.
# --instructions--
We've provided a `Node` object and started our `DoublyLinkedList`. Let's add two methods to our doubly linked list called `add` and `remove`. The `add` method should add the given element to the list while the `remove` method should remove all occurrences of a given element in the list.
Abbiamo fornito un oggetto `Node` e abbiamo avviato il nostro `DoublyLinkedList`. Aggiungiamo due metodi alla nostra lista doppiamente concatenata chiamati `add` e `remove`. Il metodo `add` dovrebbe aggiungere l'elemento dato alla lista mentre il metodo `remove` dovrebbe rimuovere tutte le occorrenze di un dato elemento nella lista.
Be careful to handle any possible edge cases when writing these methods, such as deletions for the first or last element. Also, removing any item on an empty list should return `null`.
Fai attenzione a gestire eventuali casi limite durante la scrittura di questi metodi, come le cancellazioni per il primo o l'ultimo elemento. Inoltre, la rimozione di qualsiasi elemento in una lista vuota dovrebbe restituire `null`.
# --hints--
The DoublyLinkedList data structure should exist.
La struttura di dati DoublyLinkedList dovrebbe esistere.
```js
assert(
@ -34,7 +34,7 @@ assert(
);
```
The DoublyLinkedList should have a method called add.
La lista DoublyLinkedList dovrebbe avere un metodo chiamato add.
```js
assert(
@ -51,7 +51,7 @@ assert(
);
```
The DoublyLinkedList should have a method called remove.
La lista DoublyLinkedList dovrebbe avere un metodo chiamato remove.
```js
assert(
@ -68,7 +68,7 @@ assert(
);
```
Removing an item from an empty list should return null.
Rimuovere un elemento da una lista vuota dovrebbe restituire null.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
The add method should add items to the list.
Il metodo add dovrebbe aggiungere elementi all'elenco.
```js
assert(
@ -99,7 +99,7 @@ assert(
);
```
Each node should keep track of the previous node.
Ogni nodo dovrebbe tenere traccia del nodo precedente.
```js
assert(
@ -116,7 +116,7 @@ assert(
);
```
The first item should be removable from the list.
Il primo elemento dovrebbe essere rimovibile dall'elenco.
```js
assert(
@ -134,7 +134,7 @@ assert(
);
```
The last item should be removable from the list.
L'ultimo elemento dovrebbe essere rimovibile dall'elenco.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c74
title: Create a Priority Queue Class
title: Creare una classe Coda di Priorità
challengeType: 1
forumTopicId: 301630
dashedName: create-a-priority-queue-class
@ -8,27 +8,27 @@ dashedName: create-a-priority-queue-class
# --description--
In this challenge you will be creating a Priority Queue. A Priority Queue is a special type of Queue in which items may have additional information which specifies their priority. This could be simply represented with an integer. Item priority will override placement order in determining the sequence items are dequeued. If an item with a higher priority is enqueued after items with lower priority, the higher priority item will be dequeued before all the others.
In questa sfida creerai una Coda di Priorità. Una Coda Priorità è un tipo speciale di Coda in cui gli oggetti possono avere informazioni aggiuntive che ne specificano la priorità. Questa potrebbe essere semplicemente rappresentata con un numero intero. La priorità degli elementi sovrascriverà l'ordine di posizionamento nel determinare la sequenza di elementi rimossi dalla coda. Se un elemento con una priorità più alta viene accodato dopo gli elementi con priorità più bassa, l'elemento con priorità più alta sarà rimosso dalla coda prima di tutti gli altri.
For instance, lets imagine we have a priority queue with three items:
Per esempio, immaginiamo di avere una coda di priorità con tre elementi:
```js
[['kitten', 2], ['dog', 2], ['rabbit', 2]]
```
Here the second value (an integer) represents item priority. If we enqueue `['human', 1]` with a priority of `1` (assuming lower priorities are given precedence) it would then be the first item to be dequeued. The collection would look like this:
Qui il secondo valore (un intero) rappresenta la priorità dell'elemento. Se accodi `['human', 1]` con una priorità di `1` (ipotizzando che le priorità più basse abbiano la precedenza) esso sarebbe il primo elemento ad essere rimosso dalla coda. La collezione assomiglierà a questa:
```js
[['human', 1], ['kitten', 2], ['dog', 2], ['rabbit', 2]]
```
Weve started writing a `PriorityQueue` in the code editor. You will need to add an `enqueue` method for adding items with a priority, a `dequeue` method for removing and returning items, a `size` method to return the number of items in the queue, a `front` method to return the element at the front of the queue, and finally an `isEmpty` method that will return `true` if the queue is empty or `false` if it is not.
Abbiamo iniziato a scrivere una `PriorityQueue` nell'editor di codice. Dovrai aggiungere un metodo `enqueue` per aggiungere elementi con una priorità, un metodo `dequeue` per rimuovere e restituire gli oggetti, un metodo `size` per restituire il numero di elementi nella coda, un metodo `front` per restituire l'elemento nella parte anteriore della coda, e infine un metodo `isEmpty` che restituirà `true` se la coda è vuota o `false` se non lo è.
The `enqueue` should accept items with the format shown above (`['human', 1]`) where `1` represents the priority. `dequeue` and `front` should return only the item's name, not its priority.
Il metodo `enqueue` dovrebbe accettare gli elementi con il formato mostrato sopra (`['human', 1]`) dove `1` rappresenta la priorità. `dequeue` e `front` dovrebbe restituire solo il nome dell'elemento, non la sua priorità.
# --hints--
Your `PriorityQueue` class should have a `enqueue` method.
La tua classe `PriorityQueue` dovrebbe avere un metodo `enqueue`.
```js
assert(
@ -39,7 +39,7 @@ assert(
);
```
Your `PriorityQueue` class should have a `dequeue` method.
La tua classe `PriorityQueue` dovrebbe avere un metodo `dequeue`.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
Your `PriorityQueue` class should have a `size` method.
La tua classe `PriorityQueue` dovrebbe avere un metodo `size`.
```js
assert(
@ -61,7 +61,7 @@ assert(
);
```
Your `PriorityQueue` class should have a `front` method.
La tua classe `PriorityQueue` dovrebbe avere un metodo `front`.
```js
assert(
@ -72,7 +72,7 @@ assert(
);
```
Your `PriorityQueue` class should have an `isEmpty` method.
La tua classe `PriorityQueue` dovrebbe avere un metodo `isEmpty`.
```js
assert(
@ -83,7 +83,7 @@ assert(
);
```
Your `PriorityQueue` class should correctly keep track of the current number of items using the `size` method as items are enqueued and dequeued.
La tua classe `PriorityQueue` dovrebbe tenere correttamente traccia del numero attuale di elementi utilizzando il metodo `size` mentre gli elementi vengono accodati e rimossi.
```js
assert(
@ -102,7 +102,7 @@ assert(
);
```
The `front` method should return the correct item at the front of the queue as items are enqueued and dequeued.
Il metodo `front` dovrebbe restituire l'elemento corretto nella parte anteriore della coda mentre gli elementi vengono accodati e rimossi.
```js
assert(
@ -129,7 +129,7 @@ assert(
);
```
The `isEmpty` method should return `true` when the queue is empty.
Il metodo `isEmpty` dovrebbe restituire `true` quando la coda è vuota.
```js
assert(
@ -145,7 +145,7 @@ assert(
);
```
The priority queue should return items with a higher priority before items with a lower priority and return items in first-in-first-out order otherwise.
La coda di priorità dovrebbe restituire gli elementi con una priorità più alta prima degli elementi con una priorità più bassa e restituire gli elementi nell'ordine first-in-first-out altrimenti.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8256367417b2b2512c79
title: Incidence Matrix
title: Matrice di incidenza
challengeType: 1
forumTopicId: 301644
dashedName: incidence-matrix
@ -8,21 +8,21 @@ dashedName: incidence-matrix
# --description--
Yet another way to represent a graph is to put it in an <dfn>incidence matrix.</dfn>
Un altro modo per rappresentare un grafico è quello di metterlo in una <dfn>matrice di incidenza.</dfn>
An <dfn>incidence matrix</dfn> is a two-dimensional (2D) array. Generally speaking, an incidence matrix relates two different classes of objects between its two dimensions. This kind of matrix is similar to an adjacency matrix. However, the rows and columns mean something else here.
Una <dfn>matrice di incidenza</dfn> è un array bidimensionale (2D). In generale, una matrice di incidenza collega due classi diverse di oggetti tramite le sue due dimensioni. Questo tipo di matrice è simile a una matrice di adiacenza. Tuttavia, le righe e le colonne qui hanno un altro significato.
In graphs, we have edges and nodes. These will be our "two different classes of objects". This matrix will have the rows be the nodes and columns be the edges. This means that we can have an uneven number of rows and columns.
Nei grafi, abbiamo archi e nodi. Queste saranno le nostre "due classi diverse di oggetti". In questa matrice le righe saranno i nodi e colonne saranno gli archi. Ciò significa che possiamo avere un numero diverso di righe e colonne.
Each column will represent a unique edge. Also, each edge connects two nodes. To show that there is an edge between two nodes, you will put a 1 in the two rows of a particular column. Below is a 3 node graph with one edge between node 1 and node 3.
Ogni colonna rappresenterà un arco unico. Inoltre, ogni arco collegherà due nodi. Per mostrare che c'è un arco tra due nodi, si metterà un 1 nelle due righe di una particolare colonna. Di seguito è riportato un grafo a 3 nodi con un arco tra il nodo 1 e il nodo 3.
<blockquote> 1<br> ---<br>1 | 1<br>2 | 0<br>3 | 1</blockquote>
Here is an example of an `incidence matrix` with 4 edges and 4 nodes. Remember, the columns are the edges and rows are the nodes themselves.
Ecco un esempio di una `incidence matrix` con 4 archi e 4 nodi. Ricorda, le colonne sono gli archi e le righe sono i nodi.
<blockquote> 1 2 3 4<br> --------<br>1 | 0 1 1 1<br>2 | 1 1 0 0<br>3 | 1 0 0 1<br>4 | 0 0 1 0</blockquote>
Below is a JavaScript implementation of the same thing.
Di seguito è riportata un'implementazione JavaScript della stessa cosa.
```js
var incMat = [
@ -33,7 +33,7 @@ var incMat = [
];
```
To make a directed graph, use `-1` for an edge leaving a particular node and `1` for an edge entering a node.
Per creare un grafo diretto, usa `-1` per un arco che lascia un particolare nodo e `1` per un arco che entra in un nodo.
```js
var incMatDirected = [
@ -44,17 +44,17 @@ var incMatDirected = [
];
```
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (`0` or `1`). You can have different weights depending on your application. A different weight is represented as numbers greater than 1.
I grafi possono anche avere dei <dfn>pesi</dfn> sui loro archi. Finora, abbiamo visto archi <dfn>non ponderati</dfn> dove la sola presenza e assenza degli archi è binaria (`0` o `1`). Puoi avere pesi diversi a seconda della tua applicazione. Un peso diverso è rappresentato con un numero maggiore di 1.
# --instructions--
Create an incidence matrix of an undirected graph with five nodes and four edges. This matrix should be in a multi-dimensional array.
Crea una matrice di incidenza di un grafo non diretto con cinque nodi e quattro archi. Questa matrice dovrebbe essere in un array multidimensionale.
These five nodes have the following relationships. The first edge is between the first and second node. The second edge is between the second and third node. The third edge is between the third and fifth node. The fourth edge is between the fourth and second node. All edge weights are one and the edge order matters.
Questi cinque nodi hanno le seguenti relazioni. Il primo arco è tra il primo e il secondo nodo. Il secondo arco è tra il secondo e il terzo nodo. Il terzo arco è tra il terzo e il quinto nodo. Il quarto arco è tra il quarto e il secondo nodo. Tutti i pesi degli archi sono uno e l'ordine dell'arco conta.
# --hints--
`incMatUndirected` should only contain five nodes.
`incMatUndirected` dovrebbe contenere solo cinque nodi.
```js
assert(
@ -69,25 +69,25 @@ assert(
);
```
There should be a first edge between the first and second node.
Dovrebbe esserci un primo arco tra il primo e il secondo nodo.
```js
assert(incMatUndirected[0][0] === 1 && incMatUndirected[1][0] === 1);
```
There should be a second edge between the second and third node.
Dovrebbe esserci un secondo arco tra il secondo e il terzo nodo.
```js
assert(incMatUndirected[1][1] === 1 && incMatUndirected[2][1] === 1);
```
There should be a third edge between the third and fifth node.
Dovrebbe esserci un terzo arco tra il terzo e il quinto nodo.
```js
assert(incMatUndirected[2][2] === 1 && incMatUndirected[4][2] === 1);
```
There should be a fourth edge between the second and fourth node.
Dovrebbe esserci un quarto arco tra il secondo e il quarto nodo.
```js
assert(incMatUndirected[1][3] === 1 && incMatUndirected[3][3] === 1);

View File

@ -1,6 +1,6 @@
---
id: 587d8253367417b2b2512c6d
title: Perform an Intersection on Two Sets of Data
title: Eseguire un'intersezione tra due insiemi di dati
challengeType: 1
forumTopicId: 301709
dashedName: perform-an-intersection-on-two-sets-of-data
@ -8,13 +8,13 @@ dashedName: perform-an-intersection-on-two-sets-of-data
# --description--
In this exercise we are going to perform an intersection on 2 sets of data. We will create a method on our `Set` data structure called `intersection`. An intersection of sets represents all values that are common to two or more sets. This method should take another `Set` as an argument and return the `intersection` of the two sets.
In questo esercizio ci accingiamo a eseguire un intersezione su 2 set di dati. Creeremo un metodo nella nostra struttura dati `Set` chiamato `intersection`. Un'intersezione di insiemi rappresenta tutti i valori che sono comuni a due o più insiemi. Questo metodo dovrebbe prendere un altro `Set` come argomento e restituire l' `intersection` dei due set.
For example, if `setA = ['a','b','c']` and `setB = ['a','b','d','e']`, then the intersection of setA and setB is: `setA.intersection(setB) = ['a', 'b']`.
Per esempio, se `setA = ['a','b','c']` e `setB = ['a','b','d','e']`, allora l'intersezione di setA e setB è: `setA.intersection(setB) = ['a', 'b']`.
# --hints--
Your `Set` class should have a `intersection` method.
La tua classe `Set` dovrebbe avere un metodo `intersection`.
```js
assert(
@ -25,7 +25,7 @@ assert(
);
```
The proper collection should be returned.
Dovrebbe essere restituita la collezione corretta.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5900f3711000cf542c50fe84
title: 'Problem 5: Smallest multiple'
title: 'Problema 5: il più piccolo multiplo'
challengeType: 5
forumTopicId: 302160
dashedName: problem-5-smallest-multiple
@ -8,43 +8,43 @@ dashedName: problem-5-smallest-multiple
# --description--
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
2520 è il numero più piccolo divisibile per ciascuno dei numeri da 1 a 10 senza resto.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to `n`?
Qual è il numero positivo più piccolo che sia uniformemente divisibile per tutti i numeri da 1 a `n`?
# --hints--
`smallestMult(5)` should return a number.
`smallestMult(5)` dovrebbe restituire un numero.
```js
assert(typeof smallestMult(5) === 'number');
```
`smallestMult(5)` should return 60.
`smallestMult(5)` dovrebbe restituire 60.
```js
assert.strictEqual(smallestMult(5), 60);
```
`smallestMult(7)` should return 420.
`smallestMult(7)` dovrebbe restituire 420.
```js
assert.strictEqual(smallestMult(7), 420);
```
`smallestMult(10)` should return 2520.
`smallestMult(10)` dovrebbe restituire 2520.
```js
assert.strictEqual(smallestMult(10), 2520);
```
`smallestMult(13)` should return 360360.
`smallestMult(13)` dovrebbe restituire 360360.
```js
assert.strictEqual(smallestMult(13), 360360);
```
`smallestMult(20)` should return 232792560.
`smallestMult(20)` dovrebbe restituire 232792560.
```js
assert.strictEqual(smallestMult(20), 232792560);

View File

@ -1,6 +1,6 @@
---
id: 5a4b7fcdb66f799f199e11db
title: Build a Pong Game
title: Costruisci un gioco Pong
challengeType: 3
forumTopicId: 302353
dashedName: build-a-pong-game
@ -8,23 +8,23 @@ dashedName: build-a-pong-game
# --description--
**Objective:** Build a [CodePen.io](https://codepen.io) app that is functionally similar to this: <https://codepen.io/satyamdev/full/pdMmBp>.
**Obiettivo:** Costruisci un'app [CodePen.io](https://codepen.io) funzionalmente simile a questa: <https://codepen.io/satyamdev/full/pdMmBp>.
**Rule #1:** Don't look at the example project's code. Figure it out for yourself.
**Regola #1:** Non guardare il codice del progetto di esempio. Arrivaci per conto tuo.
**Rule #2:** Fulfill the below [user stories](https://en.wikipedia.org/wiki/User_story). Use whichever libraries or APIs you need. Give it your own personal style.
**Regola #2:** Soddisfa le seguenti [user story](https://en.wikipedia.org/wiki/User_story). Utilizza le librerie o le API di cui hai bisogno. Usa il tuo stile personale.
**User Story:** I can control a paddle.
**User Story:** Posso controllare una paletta.
**User Story:** The computer can control the other paddle.
**User Story:** Il computer può controllare l'altra paletta.
**User Story:** The computer's paddle is unbeatable. It should never miss the ball.
**User Story:** La paletta del computer non può essere battuta. Non deve mai mancare la palla.
**User Story:** The game keeps track of the player and computer's score.
**User Story:** Il gioco tiene traccia dei punteggi del giocatore e del computer.
When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button.
Quando hai finito, includi un link al tuo progetto su CodePen e clicca sul pulsante "Ho completato questa sfida".
You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409).
Puoi ottenere un feedback sul tuo progetto condividendolo sul forum [freeCodeCamp](https://forum.freecodecamp.org/c/project-feedback/409).
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: bd7108d8c242eddfaeb5bd13
title: Map Data Across the Globe
title: Mappa i dati in tutto il globo
challengeType: 3
forumTopicId: 302365
dashedName: map-data-across-the-globe
@ -8,21 +8,21 @@ dashedName: map-data-across-the-globe
# --description--
**Objective:** Build a [CodePen.io](https://codepen.io) app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/mVEJag>.
**Obiettivo:** Costruisci un'app [CodePen.io](https://codepen.io) funzionalmente simile a questa: <https://codepen.io/freeCodeCamp/full/mVEJag>.
Fulfill the following [user stories](https://en.wikipedia.org/wiki/User_story). Use whichever libraries or APIs you need. Give it your own personal style.
Soddisfa le seguenti [user story](https://en.wikipedia.org/wiki/User_story). Utilizza le librerie o le API di cui hai bisogno. Usa il tuo stile personale.
**User Story:** I can see where all Meteorites landed on a world map.
**User Story:** Posso vedere dove sono atterrate tutte le meteoriti su una mappa del mondo.
**User Story:** I can tell the relative size of the meteorite, just by looking at the way it's represented on the map.
**User Story:** Posso capire la dimensione relativa del meteorite, semplicemente vedendo come è rappresentato sulla mappa.
**User Story:** I can mouse over the meteorite's data point for additional data.
**User Story:** Posso passare sul punto dato del meteorire per ulteriori informazioni.
**Hint:** Here's a dataset you can use to build this: <https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json>
**Suggerimento:** Ecco un set di dati che puoi usare per costruirlo: <https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json>
When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button.
Quando hai finito, includi un link al tuo progetto su CodePen e clicca sul pulsante "Ho completato questa sfida".
You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409).
Puoi ottenere un feedback sul tuo progetto condividendolo sul forum [freeCodeCamp](https://forum.freecodecamp.org/c/project-feedback/409).
# --solutions--

View File

@ -29,13 +29,13 @@ O elemento `form` precisa ter um elemento `button` dentro dele.
assert($('form').children('button').length > 0);
```
O botão enviar deve ter o atributo `type` definido como `submit`.
O botão de envio deve ter o atributo `type` definido como `submit`.
```js
assert($('button').attr('type') === 'submit');
```
O botão enviar deve ter apenas o texto `Submit`.
O botão de envio deve ter apenas o texto `Submit`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: a3f503de51cf954ede28891d
title: Find the Symmetric Difference
title: Encontrar a diferença simétrica
challengeType: 5
forumTopicId: 301611
dashedName: find-the-symmetric-difference
@ -8,77 +8,77 @@ dashedName: find-the-symmetric-difference
# --description--
The mathematical term <dfn>symmetric difference</dfn> (`△` or `⊕`) of two sets is the set of elements which are in either of the two sets but not in both. For example, for sets `A = {1, 2, 3}` and `B = {2, 3, 4}`, `A △ B = {1, 4}`.
O termo matemático <dfn>diferença simétrica</dfn> (`△` ou `⊕`) de dois conjuntos é o conjunto de elementos que estão em um dos dois conjuntos, mas não em ambos. Por exemplo, para os conjuntos `A = {1, 2, 3}` e `B = {2, 3, 4}`, `A △ B = {1, 4}`.
Symmetric difference is a binary operation, which means it operates on only two elements. So to evaluate an expression involving symmetric differences among *three* elements (`A △ B △ C`), you must complete one operation at a time. Thus, for sets `A` and `B` above, and `C = {2, 3}`, `A △ B △ C = (A △ B) △ C = {1, 4} △ {2, 3} = {1, 2, 3, 4}`.
A diferença simétrica é uma operação binária, o que significa que opera em apenas dois elementos. Assim, para avaliar uma expressão que envolva diferenças simétricas entre *três* elementos (`A △ B △ C`), você deve completar uma operação por vez. Portanto, para os conjuntos `A` e `B` acima, e `C = {2, 3}`, `A △ B △ C = (A △ B) △ C = {1, 4} △ {2, 3} = {1, 2, 3, 4}`.
# --instructions--
Create a function that takes two or more arrays and returns an array of their symmetric difference. The returned array must contain only unique values (*no duplicates*).
Crie uma função que receba dois ou mais arrays e retorne um array de sua diferença simétrica. O array retornado deve conter apenas valores únicos (*sem duplicatas*).
# --hints--
`sym([1, 2, 3], [5, 2, 1, 4])` should return `[3, 4, 5]`.
`sym([1, 2, 3], [5, 2, 1, 4])` deve retornar `[3, 4, 5]`.
```js
assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4]), [3, 4, 5]);
```
`sym([1, 2, 3], [5, 2, 1, 4])` should contain only three elements.
`sym([1, 2, 3], [5, 2, 1, 4])` deve conter apenas três elementos.
```js
assert.equal(sym([1, 2, 3], [5, 2, 1, 4]).length, 3);
```
`sym([1, 2, 3, 3], [5, 2, 1, 4])` should return `[3, 4, 5]`.
`sym([1, 2, 3, 3], [5, 2, 1, 4])` deve retornar `[3, 4, 5]`.
```js
assert.sameMembers(sym([1, 2, 3, 3], [5, 2, 1, 4]), [3, 4, 5]);
```
`sym([1, 2, 3, 3], [5, 2, 1, 4])` should contain only three elements.
`sym([1, 2, 3, 3], [5, 2, 1, 4])` deve conter apenas três elementos.
```js
assert.equal(sym([1, 2, 3, 3], [5, 2, 1, 4]).length, 3);
```
`sym([1, 2, 3], [5, 2, 1, 4, 5])` should return `[3, 4, 5]`.
`sym([1, 2, 3], [5, 2, 1, 4, 5])` deve retornar `[3, 4, 5]`.
```js
assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5]);
```
`sym([1, 2, 3], [5, 2, 1, 4, 5])` should contain only three elements.
`sym([1, 2, 3], [5, 2, 1, 4, 5])` deve conter apenas três elementos.
```js
assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3);
```
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` should return `[1, 4, 5]`
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` deve retornar `[1, 4, 5]`
```js
assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5]);
```
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` should contain only three elements.
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` deve conter apenas três elementos.
```js
assert.equal(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]).length, 3);
```
`sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])` should return `[1, 4, 5]`.
`sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])` deve retornar `[1, 4, 5]`.
```js
assert.sameMembers(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]), [1, 4, 5]);
```
`sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])` should contain only three elements.
`sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])` deve conter apenas três elementos.
```js
assert.equal(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]).length, 3);
```
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])` should return `[2, 3, 4, 6, 7]`.
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])` deve retornar `[2, 3, 4, 6, 7]`.
```js
assert.sameMembers(
@ -87,7 +87,7 @@ assert.sameMembers(
);
```
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])` should contain only five elements.
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])` deve conter apenas cinco elementos.
```js
assert.equal(
@ -96,7 +96,7 @@ assert.equal(
);
```
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])` should return `[1, 2, 4, 5, 6, 7, 8, 9]`.
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])` deve retornar `[1, 2, 4, 5, 6, 7, 8, 9]`.
```js
assert.sameMembers(
@ -112,7 +112,7 @@ assert.sameMembers(
);
```
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])` should contain only eight elements.
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])` deve conter apenas oito elementos.
```js
assert.equal(

View File

@ -1,6 +1,6 @@
---
id: 8d5123c8c441eddfaeb5bdef
title: Implement Bubble Sort
title: Implementar o Bubble Sort
challengeType: 1
forumTopicId: 301612
dashedName: implement-bubble-sort
@ -8,23 +8,23 @@ dashedName: implement-bubble-sort
# --description--
This is the first of several challenges on sorting algorithms. Given an array of unsorted items, we want to be able to return a sorted array. We will see several different methods to do this and learn some tradeoffs between these different approaches. While most modern languages have built-in sorting methods for operations like this, it is still important to understand some of the common basic approaches and learn how they can be implemented.
Este é o primeiro de vários desafios sobre algoritmos de ordenação. Dado um array de itens não ordenados, queremos poder retornar um array ordenado. Veremos vários métodos diferentes para fazer isso e aprenderemos algumas escolhas que precisam ser feitas na hora de usar estas abordagens diferentes. Embora as linguagens mais modernas tenham métodos de ordenação incorporados para operações como esta, continua importante entender algumas das abordagens básicas comuns e aprender como podem ser implementadas.
Here we will see bubble sort. The bubble sort method starts at the beginning of an unsorted array and 'bubbles up' unsorted values towards the end, iterating through the array until it is completely sorted. It does this by comparing adjacent items and swapping them if they are out of order. The method continues looping through the array until no swaps occur at which point the array is sorted.
Aqui, veremos o Bubble Sort. O método do Bubble Sort começa no início de um array não classificado e lança valores não classificados para o fim, iterando através do array até que esteja completamente ordenado. Ele faz isso comparando os itens adjacentes e trocando-os de lugar se eles estiverem fora de ordem. O método continua se repetindo por todo o array até que não ocorram mais trocas, momento em que o array estará ordenado.
This method requires multiple iterations through the array and for average and worst cases has quadratic time complexity. While simple, it is usually impractical in most situations.
Este método requer múltiplas iterações através do array e, em média e nos piores casos, tem complexidade de tempo quadrática. Embora seja simples, ele não é muito prático na maioria das situações.
**Instructions:** Write a function `bubbleSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**Instruções:** escreva uma função `bubbleSort` que receba um array de inteiros como entrada e retorne um array de inteiros ordenado do menor para o maior.
# --hints--
`bubbleSort` should be a function.
`bubbleSort` deve ser uma função.
```js
assert(typeof bubbleSort == 'function');
```
`bubbleSort` should return a sorted array (least to greatest).
`bubbleSort` deve retornar um array ordenado (do menor para o maior elemento).
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
`bubbleSort` should return an array that is unchanged except for order.
`bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` deve retornar um array inalterado, exceto por sua ordenação.
```js
assert.sameMembers(
@ -79,7 +79,7 @@ assert.sameMembers(
);
```
`bubbleSort` should not use the built-in `.sort()` method.
`bubbleSort` não deve usar o método `.sort()` integrado.
```js
assert(isBuiltInSortUsed());
@ -113,8 +113,6 @@ function bubbleSort(array) {
return array;
// Only change code above this line
}
bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c86
title: Implement Insertion Sort
title: Implementar o Insertion Sort
challengeType: 1
forumTopicId: 301613
dashedName: implement-insertion-sort
@ -8,19 +8,19 @@ dashedName: implement-insertion-sort
# --description--
The next sorting method we'll look at is insertion sort. This method works by building up a sorted array at the beginning of the list. It begins the sorted array with the first element. Then it inspects the next element and swaps it backwards into the sorted array until it is in sorted position. It continues iterating through the list and swapping new items backwards into the sorted portion until it reaches the end. This algorithm has quadratic time complexity in the average and worst cases.
O próximo método de ordenação que analisaremos é o Insertion Sort. Este método funciona criando um array classificado no início da lista. Ele inicia o array ordenado com o primeiro elemento. Depois, ele inspeciona o próximo elemento e o lança para trás no array ordenado até ficar em posição ordenada. Ele continua iterando pela lista e trocando novos itens para trás na porção ordenada até chegar ao final. Este algoritmo apresenta complexidade de tempo quadrática em média e nos piores casos.
**Instructions:** Write a function `insertionSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**Instruções:** escreva uma função `insertionSort` que receba um array de inteiros como entrada e retorne um array de inteiros ordenado do menor para o maior.
# --hints--
`insertionSort` should be a function.
`insertionSort` deve ser uma função.
```js
assert(typeof insertionSort == 'function');
```
`insertionSort` should return a sorted array (least to greatest).
`insertionSort` deve retornar um array ordenado (do menor para o maior elemento).
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`insertionSort` should return an array that is unchanged except for order.
`insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` deve retornar um array inalterado, exceto por sua ordenação.
```js
assert.sameMembers(
@ -75,7 +75,7 @@ assert.sameMembers(
);
```
`insertionSort` should not use the built-in `.sort()` method.
`insertionSort` não deve usar o método `.sort()` integrado.
```js
assert(isBuiltInSortUsed());
@ -109,8 +109,6 @@ function insertionSort(array) {
return array;
// Only change code above this line
}
insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d825c367417b2b2512c8f
title: Implement Merge Sort
title: Implementar o Merge Sort
challengeType: 1
forumTopicId: 301614
dashedName: implement-merge-sort
@ -8,27 +8,27 @@ dashedName: implement-merge-sort
# --description--
Another common intermediate sorting algorithm is merge sort. Like quick sort, merge sort also uses a divide-and-conquer, recursive methodology to sort an array. It takes advantage of the fact that it is relatively easy to sort two arrays as long as each is sorted in the first place. But we'll start with only one array as input, so how do we get to two sorted arrays from that? Well, we can recursively divide the original input in two until we reach the base case of an array with one item. A single-item array is naturally sorted, so then we can start combining. This combination will unwind the recursive calls that split the original array, eventually producing a final sorted array of all the elements. The steps of merge sort, then, are:
Outro algoritmo de ordenação intermediária comum é o Merge Sort. Assim como ocorre com o Quick Sort, o Merge Sort também usa uma metodologia de dividir e conquistar e recursiva para ordenar um array. Ele leva vantagem pelo fato de ser relativamente fácil ordenar dois arrays desde que cada um esteja ordenado, para começar. Começaremos com apenas um array como entrada. Então, como podemos obter dois arrays ordenados a partir disso? Bem, podemos dividir recursivamente a entrada original em duas até chegarmos ao caso de base de um array com um único item. Um array de item único está naturalmente ordenado. Então, podemos começar a combinar. Esta combinação revelará as chamadas recursivas que dividem o array original, no fim produzindo um array de todos os elementos. As etapas do Merge Sort são, portanto:
**1)** Recursively split the input array in half until a sub-array with only one element is produced.
**1)** Dividir recursivamente o array de entrada ao meio até ser produzido um subarray com apenas um elemento.
**2)** Merge each sorted sub-array together to produce the final sorted array.
**2)** Combinar e unir cada subarray ordenado para produzir o array com a ordenação final.
Merge sort is an efficient sorting method, with time complexity of *O(nlog(n))*. This algorithm is popular because it is performant and relatively easy to implement.
O Merge Sort é um método eficiente de ordenação, com complexidade de tempo de *O(nlog(n))*. Este algoritmo é popular porque tem boa performance e é relativamente fácil de implementar.
As an aside, this will be the last sorting algorithm we cover here. However, later in the section on tree data structures we will describe heap sort, another efficient sorting method that requires a binary heap in its implementation.
Este será o último algoritmo de ordenação do qual trataremos aqui. No entanto, mais tarde, na seção sobre estruturas de dados em árvore, descreveremos o Heap Sort, outro método de classificação eficiente que requer uma pilha binária (binary heap) em sua implementação.
**Instructions:** Write a function `mergeSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest. A good way to implement this is to write one function, for instance `merge`, which is responsible for merging two sorted arrays, and another function, for instance `mergeSort`, which is responsible for the recursion that produces single-item arrays to feed into merge. Good luck!
**Instruções:** escreva uma função `mergeSort` que receba um array de inteiros como entrada e retorne um array de inteiros ordenado do menor para o maior. Uma boa maneira de implementá-la é escrever uma função, por exemplo `merge`, que seja responsável por mesclar dois arrays ordenados, e outra função, por exemplo, `mergeSort`, que seja responsável pela recursão que produz arrays de um único item para alimentar a função merge. Boa sorte!
# --hints--
`mergeSort` should be a function.
`mergeSort` deve ser uma função.
```js
assert(typeof mergeSort == 'function');
```
`mergeSort` should return a sorted array (least to greatest).
`mergeSort` deve retornar um array ordenado (do menor para o maior elemento).
```js
assert(
@ -56,7 +56,7 @@ assert(
);
```
`mergeSort` should return an array that is unchanged except for order.
`mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` deve retornar um array inalterado, exceto por sua ordenação.
```js
assert.sameMembers(
@ -83,7 +83,7 @@ assert.sameMembers(
);
```
`mergeSort` should not use the built-in `.sort()` method.
`mergeSort` não deve usar o método `.sort()` integrado.
```js
assert(isBuiltInSortUsed());
@ -117,8 +117,6 @@ function mergeSort(array) {
return array;
// Only change code above this line
}
mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c85
title: Implement Selection Sort
title: Implementar o Selection Sort
challengeType: 1
forumTopicId: 301616
dashedName: implement-selection-sort
@ -8,19 +8,19 @@ dashedName: implement-selection-sort
# --description--
Here we will implement selection sort. Selection sort works by selecting the minimum value in a list and swapping it with the first value in the list. It then starts at the second position, selects the smallest value in the remaining list, and swaps it with the second element. It continues iterating through the list and swapping elements until it reaches the end of the list. Now the list is sorted. Selection sort has quadratic time complexity in all cases.
Aqui, implementaremos o Selection Sort. O Selection Sort funciona a partir da seleção do valor mínimo em uma lista e trocando-o de posição com o primeiro valor na lista. Ele, então, começa da segunda posição, seleciona o menor valor da lista restante e troca-o pelo segundo elemento. Ele continua iterando através da lista e trocando elementos até chegar ao final da lista. Agora, a lista estará ordenada. O Selection Sort tem complexidade de tempo quadrática em todos os casos.
**Instructions**: Write a function `selectionSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**Instruções:** escreva uma função `selectionSort` que receba um array de inteiros como entrada e retorne um array de inteiros ordenado do menor para o maior.
# --hints--
`selectionSort` should be a function.
`selectionSort` deve ser uma função.
```js
assert(typeof selectionSort == 'function');
```
`selectionSort` should return a sorted array (least to greatest).
`selectionSort` deve retornar um array ordenado (do menor para o maior elemento).
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`selectionSort` should return an array that is unchanged except for order.
`selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` deve retornar um array inalterado, exceto por sua ordenação.
```js
assert.sameMembers(
@ -75,7 +75,7 @@ assert.sameMembers(
);
```
`selectionSort` should not use the built-in `.sort()` method.
`selectionSort` não deve usar o método `.sort()` integrado.
```js
assert(isBuiltInSortUsed());
@ -109,9 +109,6 @@ function selectionSort(array) {
return array;
// Only change code above this line
}
selectionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: a56138aff60341a09ed6c480
title: Inventory Update
title: Atualização de inventário
challengeType: 5
forumTopicId: 16019
dashedName: inventory-update
@ -8,11 +8,11 @@ dashedName: inventory-update
# --description--
Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in `arr1`). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.
Compare e atualize o inventário armazenado em um array 2D contrastando-o com um segundo array 2D de uma nova entrega. Atualize as quantidades atuais de itens do inventário (em `arr1`). Se um item não puder ser encontrado, adicione o novo item e sua quantidade no array do inventário. O array do inventário retornado deve estar em ordem alfabética por item.
# --hints--
The function `updateInventory` should return an array.
A função `updateInventory` deve retornar um array.
```js
assert.isArray(
@ -33,7 +33,7 @@ assert.isArray(
);
```
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` should return an array with a length of 6.
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` deve retornar um array de tamanho 6.
```js
assert.equal(
@ -55,7 +55,7 @@ assert.equal(
);
```
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` should return `[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]`.
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` deve retornar `[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]`.
```js
assert.deepEqual(
@ -84,7 +84,7 @@ assert.deepEqual(
);
```
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])` should return `[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]`.
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])` deve retornar `[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]`.
```js
assert.deepEqual(
@ -106,7 +106,7 @@ assert.deepEqual(
);
```
`updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` should return `[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]`.
`updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` deve retornar `[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]`.
```js
assert.deepEqual(
@ -128,7 +128,7 @@ assert.deepEqual(
);
```
`updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])` should return `[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]`.
`updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])` deve retornar `[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]`.
```js
assert.deepEqual(

View File

@ -1,6 +1,6 @@
---
id: a7bf700cd123b9a54eef01d5
title: No Repeats Please
title: Sem repetir
challengeType: 5
forumTopicId: 16037
dashedName: no-repeats-please
@ -8,67 +8,67 @@ dashedName: no-repeats-please
# --description--
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.
Retorne o número de permutações totais da string fornecida que não tenham letras consecutivas repetidas. Pense que todos os caracteres na cadeia fornecida sejam exclusivos.
For example, `aab` should return 2 because it has 6 total permutations (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), but only 2 of them (`aba` and `aba`) don't have the same letter (in this case `a`) repeating.
Por exemplo, `aab` deve retornar 2, porque tem um total de 6 permutações (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), mas apenas 2 delas (`aba` e `aba`) não têm a mesma letra (neste caso, `a`) se repetindo.
# --hints--
`permAlone("aab")` should return a number.
`permAlone("aab")` deve retornar um número.
```js
assert.isNumber(permAlone('aab'));
```
`permAlone("aab")` should return 2.
`permAlone("aab")` deve retornar 2.
```js
assert.strictEqual(permAlone('aab'), 2);
```
`permAlone("aaa")` should return 0.
`permAlone("aaa")` deve retornar 0.
```js
assert.strictEqual(permAlone('aaa'), 0);
```
`permAlone("aabb")` should return 8.
`permAlone("aabb")` deve retornar 8.
```js
assert.strictEqual(permAlone('aabb'), 8);
```
`permAlone("abcdefa")` should return 3600.
`permAlone("abcdefa")` deve retornar 3600.
```js
assert.strictEqual(permAlone('abcdefa'), 3600);
```
`permAlone("abfdefa")` should return 2640.
`permAlone("abfdefa")` deve retornar 2640.
```js
assert.strictEqual(permAlone('abfdefa'), 2640);
```
`permAlone("zzzzzzzz")` should return 0.
`permAlone("zzzzzzzz")` deve retornar 0.
```js
assert.strictEqual(permAlone('zzzzzzzz'), 0);
```
`permAlone("a")` should return 1.
`permAlone("a")` deve retornar 1.
```js
assert.strictEqual(permAlone('a'), 1);
```
`permAlone("aaab")` should return 0.
`permAlone("aaab")` deve retornar 0.
```js
assert.strictEqual(permAlone('aaab'), 0);
```
`permAlone("aaabb")` should return 12.
`permAlone("aaabb")` deve retornar 12.
```js
assert.strictEqual(permAlone('aaabb'), 12);

View File

@ -1,6 +1,6 @@
---
id: a3f503de51cfab748ff001aa
title: Pairwise
title: De par em par
challengeType: 5
forumTopicId: 301617
dashedName: pairwise
@ -8,57 +8,57 @@ dashedName: pairwise
# --description--
Given an array `arr`, find element pairs whose sum equal the second argument `arg` and return the sum of their indices.
Dado um array `arr`, encontre pares de elementos cuja soma seja igual ao segundo argumento `arg` e retorne a soma de seus índices.
You may use multiple pairs that have the same numeric elements but different indices. Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another element. For instance, `pairwise([1, 1, 2], 3)` creates a pair `[2, 1]` using the 1 at index 0 rather than the 1 at index 1, because 0+2 &lt; 1+2.
Você pode usar vários pares que tenham os mesmos elementos numéricos, mas com índices diferentes. Cada par deve utilizar os menores índices disponíveis. Quando um elemento tiver sido usado, ele não pode ser reutilizado para fazer par com outro elemento. Por exemplo, `pairwise([1, 1, 2], 3)` cria um par `[2, 1]` usando o 1 no índice 0 ao invés do 1 no índice 1, porque 0+2 &lt; 1+2.
For example `pairwise([7, 9, 11, 13, 15], 20)` returns `6`. The pairs that sum to 20 are `[7, 13]` and `[9, 11]`. We can then write out the array with their indices and values.
Um outro exemplo: `pairwise([7, 9, 11, 13, 15], 20)` retorna `6`. Os pares que somam 20 são `[7, 13]` e `[9, 11]`. Em seguida, podemos escrever o array com seus índices e valores.
<div style='margin-left: 2em;'>
| Index | 0 | 1 | 2 | 3 | 4 |
| Índice | 0 | 1 | 2 | 3 | 4 |
| ----- | - | - | -- | -- | -- |
| Value | 7 | 9 | 11 | 13 | 15 |
| Valor | 7 | 9 | 11 | 13 | 15 |
</div>
Below we'll take their corresponding indices and add them.
Abaixo, pegaremos os respectivos índices e os somaremos.
<div style='margin-left: 2em;'>
7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Return `6`
7 + 13 = 20 → Índices 0 + 3 = 3
9 + 11 = 20 → Índices 1 + 2 = 3
3 + 3 = 6 → Retorna `6`
</div>
# --hints--
`pairwise([1, 4, 2, 3, 0, 5], 7)` should return 11.
`pairwise([1, 4, 2, 3, 0, 5], 7)` deve retornar 11.
```js
assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11);
```
`pairwise([1, 3, 2, 4], 4)` should return 1.
`pairwise([1, 3, 2, 4], 4)` deve retornar 1.
```js
assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1);
```
`pairwise([1, 1, 1], 2)` should return 1.
`pairwise([1, 1, 1], 2)` deve retornar 1.
```js
assert.deepEqual(pairwise([1, 1, 1], 2), 1);
```
`pairwise([0, 0, 0, 0, 1, 1], 1)` should return 10.
`pairwise([0, 0, 0, 0, 1, 1], 1)` deve retornar 10.
```js
assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10);
```
`pairwise([], 100)` should return 0.
`pairwise([], 100)` deve retornar 0.
```js
assert.deepEqual(pairwise([], 100), 0);

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7b
title: Add a New Element to a Binary Search Tree
title: Adicionar um novo elemento a uma árvore binária de busca
challengeType: 1
forumTopicId: 301618
dashedName: add-a-new-element-to-a-binary-search-tree
@ -8,27 +8,27 @@ dashedName: add-a-new-element-to-a-binary-search-tree
# --description--
This series of challenges will introduce the tree data structure. Trees are an important and versatile data structure in computer science. Of course, their name comes from the fact that when visualized they look much like the trees we are familiar with in the natural world. A tree data structure begins with one node, typically referred to as the root, and from here branches out to additional nodes, each of which may have more child nodes, and so on and so forth. The data structure is usually visualized with the root node at the top; you can think of it as a natural tree flipped upside down.
Esta série de desafios vai introduzir a estrutura de dados de árvore. As árvores são uma estrutura de dados importante e versátil na ciência da computação. É claro que o seu nome vem do fato de, quando visualizada, se assemelhar muito a uma árvore, com a qual estamos familiarizados no mundo natural. Uma estrutura de dados de árvore começa com um nó, normalmente referido como nó raiz (ou root). Deste nó surgem ramificações para os nós adicionais, cada um dos quais pode ter mais nós filhos, e assim por diante. A estrutura de dados geralmente é visualizada com o nó raiz na parte superior. Imagine-a como se fosse uma árvore natural, mas de cabeça para baixo.
First, let's describe some common terminology we will encounter with trees. The root node is the top of the tree. Data points in the tree are called nodes. Nodes with branches leading to other nodes are referred to as the parent of the node the branch leads to (the child). Other more complicated familial terms apply as you might expect. A subtree refers to all the descendants of a particular node, branches may be referred to as edges, and leaf nodes are nodes at the end of the tree that have no children. Finally, note that trees are inherently recursive data structures. That is, any children of a node are parents of their own subtree, and so on. The recursive nature of trees is important to understand when designing algorithms for common tree operations.
Primeiro, vamos descrever a terminologia comum que encontraremos ao falar de árvores. O nó raiz é o topo da árvore. Os pontos de dados na árvore são chamados de nós. Nós com ramificações (branches) que levam a outros nós são referidos como o pai dos nós para os quais as ramificações levam (os filhos). São aplicados outros termos familiares mais complicados, como você poderia esperar. Uma subárvore se refere a todos os descendentes de um nó específico. Ramificações podem ser chamadas de ramos, e os nós folhas são nós no final da árvore que não têm filhos. Por fim, observe que as árvores são estruturas de dados inerentemente recursivas. Ou seja, os filhos de um nó são pais de sua própria subárvore, e assim por diante. É importante entender a natureza recursiva das árvores ao projetar algoritmos para operações comuns com árvores.
To begin, we will discuss a particular type of a tree, the binary tree. In fact, we will actually discuss a particular binary tree, a binary search tree. Let's describe what this means. While the tree data structure can have any number of branches at a single node, a binary tree can only have two branches for every node. Furthermore, a binary search tree is ordered with respect to the child subtrees, such that the value of each node in the left subtree is less than or equal to the value of the parent node, and the value of each node in the right subtree is greater than or equal to the value of the parent node. It's very helpful to visualize this relationship in order to understand it better:
Para começar, vamos discutir um tipo específico de árvore, a árvore binária. De fato, discutiremos uma árvore binária específica, a árvore binária de busca. Vamos descrever o que isso significa. Enquanto a estrutura de dados de árvore pode ter qualquer número de ramificações em um único nó, em uma árvore binária só é possível ter dois ramos para cada nó. Além disso, uma árvore binária de busca é ordenada em relação às subárvores filhas para que o valor de cada nó na subárvore esquerda seja menor ou igual ao valor do nó pai, e que o valor de cada nó na subárvore direita seja maior ou igual ao valor do nó pai. É uma boa ideia visualizar este relacionamento para entender melhor:
<div style='width: 100%; display: flex; justify-content: center; align-items: center;'><img style='width: 100%; max-width: 350px; background-color: var(--gray-05);' src='https://user-images.githubusercontent.com/18563015/32136009-1e665d98-bbd6-11e7-9133-63184f9f9182.png'></div>
Now this ordered relationship is very easy to see. Note that every value to the left of 8, the root node, is less than 8, and every value to the right is greater than 8. Also notice that this relationship applies to each of the subtrees as well. For example, the first left child is a subtree. 3 is the parent node, and it has exactly two child nodes — by the rules governing binary search trees, we know without even looking that the left child of this node (and any of its children) will be less than 3, and the right child (and any of its children) will be greater than 3 (but also less than the structure's root value), and so on.
Esta relação ordenada é muito fácil de ver. Observe que todo valor à esquerda de 8, o nó raiz, é menor que 8, enquanto todo valor à direita é maior que 8. Perceba que esta relação também se aplica a cada uma das subárvores. Por exemplo, o primeiro filho da esquerda é uma subárvore. 3 é o nó pai e tem exatamente dois nós filhos — pelas regras que regem árvores de pesquisa binária, nós sabemos sem precisarmos ver que o filho à esquerda deste nó (e qualquer um de seus filhos) será menor que 3, e que o filho à direita (e qualquer um de seus filhos) será maior do que 3 (mas também menor do que o valor raiz da estrutura) e assim por diante.
Binary search trees are very common and useful data structures because they provide logarithmic time in the average case for several common operations such as lookup, insertion, and deletion.
Árvores de busca binárias são estruturas de dados muito comuns e úteis, pois fornecem tempo logarítmico em média para várias operações comuns como pesquisa, inserção e exclusão.
# --instructions--
We'll start simple. We've defined the skeleton of a binary search tree structure here in addition to a function to create nodes for our tree. Observe that each node may have a left and right value. These will be assigned child subtrees if they exist. In our binary search tree, you will create a method to add new values to our binary search tree. The method should be called `add` and it should accept an integer value to add to the tree. Take care to maintain the invariant of a binary search tree: the value in each left child should be less than or equal to the parent value, and the value in each right child should be greater than or equal to the parent value. Here, let's make it so our tree cannot hold duplicate values. If we try to add a value that already exists, the method should return `null`. Otherwise, if the addition is successful, `undefined` should be returned.
Nós começaremos com algo simples. Definimos o esqueleto de uma estrutura de pesquisa binária aqui, além de uma função para criar nós para nossa árvore. Observe que cada nó pode ter um valor à esquerda e outro à direita. Serão atribuídos a eles subárvores filhas, se existirem. Você criará um método para adicionar novos valores à nossa árvore binária de busca. O método deve ser chamado de `add` e deve aceitar um valor inteiro a ser adicionado à árvore. Tome cuidado para não alterar o que não pode ser alterado em uma árvore binária de busca: o valor em cada filho à esquerda deve ser menor ou igual ao valor original, e o valor em cada filho à direita deve ser maior ou igual ao valor do pai. Aqui, vamos fazer com que nossa árvore não possa ter valores duplicados. Se tentarmos adicionar um valor que já existe, o método deve retornar `null`. Caso contrário, se a adição for bem-sucedida, deve ser retornado `undefined`.
**Hint:** trees are naturally recursive data structures!
**Dica:** árvores são estruturas de dados recursivas!
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The binary search tree should have a method called `add`.
A árvore binária de busca deve ter um método chamado `add`.
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
The add method should add elements according to the binary search tree rules.
O método add deve adicionar elementos de acordo com as regras da árvore binária de busca.
```js
assert(
@ -87,7 +87,7 @@ assert(
);
```
Adding an element that already exists should return `null`.
Adicionar um elemento que já existe deve retornar `null`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8252367417b2b2512c67
title: Add Elements at a Specific Index in a Linked List
title: Adicionar elementos em um índice específico em uma lista encadeada
challengeType: 1
forumTopicId: 301619
dashedName: add-elements-at-a-specific-index-in-a-linked-list
@ -8,15 +8,15 @@ dashedName: add-elements-at-a-specific-index-in-a-linked-list
# --description--
Let's create a addAt(index,element) method that adds an element at a given index. Just like how we remove elements at a given index, we need to keep track of the currentIndex as we traverse the linked list. When the currentIndex matches the given index, we would need to reassign the previous node's next property to reference the new added node. And the new node should reference the next node in the currentIndex. Returning to the conga line example, a new person wants to join the line, but he wants to join in the middle. You are in the middle of the line, so you take your hands off of the person ahead of you. The new person walks over and puts his hands on the person you once had hands on, and you now have your hands on the new person.
Vamos criar um método addAt(índice, elemento) que adiciona um elemento em um determinado índice. Da mesma forma como removemos os elementos em um determinado índice, precisamos saber qual é o currentIndex enquanto percorremos a lista encadeada. Quando o currentIndex corresponde ao índice dado, precisaremos reatribuir a propriedade next do nó anterior para fazer referência ao novo nó adicionado. E o novo nó deve fazer referência ao próximo nó de currentIndex. Retornando ao exemplo da fila de dançarinos de conga, uma nova pessoa quer se juntar à fila, mas ela quer entrar no meio dela. Você está no meio da fila. Então, tira as mãos da pessoa à sua frente. A nova pessoa entra na fila, coloca as mãos na pessoa que estava à sua frente e você coloca suas mãos nessa pessoa nova.
# --instructions--
Create an `addAt(index,element)` method that adds an element at a given index. Return false if an element could not be added. **Note:** Remember to check if the given index is a negative or is longer than the length of the linked list.
Crie um método `addAt(index,element)` que adiciona um elemento em um determinado índice. Retorne false se um elemento não puder ser adicionado. **Observação:** lembre-se de verificar se o índice dado é negativo ou é maior que o tamanho da lista encadeada.
# --hints--
Your `addAt` method should reassign `head` to the new node when the given index is 0.
O método `addAt` deve reatribuir `head` com o novo nó quando o índice dado for 0.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
Your `addAt` method should increase the length of the linked list by one for each new node added to the linked list.
O método `addAt` deve aumentar o tamanho da lista encadeada em um para cada novo nó adicionado à lista encadeada.
```js
assert(
@ -44,7 +44,7 @@ assert(
);
```
Your `addAt` method should return `false` if a node was unable to be added.
O método `addAt` deve retornar `false` se um nó não puder ser adicionado.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8256367417b2b2512c77
title: Adjacency List
title: Lista de adjacência
challengeType: 1
forumTopicId: 301620
dashedName: adjacency-list
@ -8,11 +8,11 @@ dashedName: adjacency-list
# --description--
Graphs can be represented in different ways. Here we describe one way, which is called an <dfn>adjacency list</dfn>. An adjacency list is essentially a bulleted list where the left side is the node and the right side lists all the other nodes it's connected to. Below is a representation of an adjacency list.
Grafos podem ser representados de maneiras diferentes. Aqui, descrevemos uma das maneiras, chamada de <dfn>lista de adjacência</dfn>. Uma lista de adjacência é essencialmente uma lista de pontos onde o lado esquerdo é o nó e o lado direito lista todos os outros nós aos quais ele está conectado. Abaixo vemos uma representação de uma lista de adjacência.
<blockquote>Node1: Node2, Node3<br>Node2: Node1<br>Node3: Node1</blockquote>
Above is an undirected graph because `Node1` is connected to `Node2` and `Node3`, and that information is consistent with the connections `Node2` and `Node3` show. An adjacency list for a directed graph would mean each row of the list shows direction. If the above was directed, then `Node2: Node1` would mean there the directed edge is pointing from `Node2` towards `Node1`. We can represent the undirected graph above as an adjacency list by putting it within a JavaScript object.
Acima vemos um grafo não direcionado porque `Node1` está conectado a `Node2` e `Node3`. Essa informação é consistente com as conexões mostradas em `Node2` e `Node3`. Uma lista de adjacência para um grafo direcionado significaria que cada linha da lista mostra para qual sentido ela vai. Se o comando acima fosse direcionado, `Node2: Node1` significaria que a aresta direcionada está apontando de `Node2` para `Node1`. Podemos representar o grafo não direcionado acima como uma lista de adjacência colocando-a dentro de um objeto JavaScript.
```js
var undirectedG = {
@ -22,7 +22,7 @@ var undirectedG = {
};
```
This can also be more simply represented as an array where the nodes just have numbers rather than string labels.
Isso também pode ser representado de maneira mais simples como um array onde os nós só têm números em vez de etiquetas de string.
```js
var undirectedGArr = [
@ -34,17 +34,17 @@ var undirectedGArr = [
# --instructions--
Create a social network as an undirected graph with 4 nodes/people named `James`, `Jill`, `Jenny`, and `Jeff`. There are edges/relationships between James and Jeff, Jill and Jenny, and Jeff and Jenny.
Crie uma rede social como um grafo não direcionado com 4 nós/pessoas, chamadas `James`, `Jill`, `Jenny` e `Jeff`. Existem arestas/relações entre James e Jeff, Jill e Jenny, e Jeff e Jenny.
# --hints--
`undirectedAdjList` should only contain four nodes.
`undirectedAdjList` deve conter apenas quatro nós.
```js
assert(Object.keys(undirectedAdjList).length === 4);
```
There should be an edge between `Jeff` and `James`.
Deve haver uma aresta entre `Jeff` e `James`.
```js
assert(
@ -53,16 +53,16 @@ assert(
);
```
There should be an edge between `Jill` and `Jenny`.
Deve haver uma aresta entre `Jill` e `Jenny`.
```js
assert(
undirectedAdjList.Jill.indexOf('Jenny') !== -1 &&
undirectedAdjList.Jill.indexOf('Jenny') !== -1
undirectedAdjList.Jenny.indexOf('Jill') !== -1
);
```
There should be an edge between `Jeff` and `Jenny`.
Deve haver uma aresta entre `Jeff` e `Jenny`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8256367417b2b2512c78
title: Adjacency Matrix
title: Matriz de adjacência
challengeType: 1
forumTopicId: 301621
dashedName: adjacency-matrix
@ -8,9 +8,9 @@ dashedName: adjacency-matrix
# --description--
Another way to represent a graph is to put it in an <dfn>adjacency matrix</dfn>. An <dfn>adjacency matrix</dfn> is a two-dimensional (2D) array where each nested array has the same number of elements as the outer array. In other words, it is a matrix or grid of numbers, where the numbers represent the edges.
Outra forma de representar um grafo é colocá-lo em uma <dfn>matriz de adjacência</dfn>. Um <dfn>matriz de adjacência</dfn> é um array bidimensional (2D) onde cada array aninhado tem o mesmo número de elementos que o array externo. Em outras palavras, é uma matriz ou grade de números, em que os números representam as arestas.
**Note**: The numbers to the top and left of the matrix are just labels for the nodes. Inside the matrix, ones mean there exists an edge between the vertices (nodes) representing the row and column. Finally, zeros mean there is no edge or relationship.
**Observação**: os números na parte superior e à esquerda da matriz são apenas etiquetas para os nós. Dentro da matriz, os 1s significam que existe uma aresta entre os vértices (nós) representando a linha e a coluna. Por fim, os zeros significam que não há aresta nem relação.
<pre>
1 2 3
@ -20,7 +20,7 @@ Another way to represent a graph is to put it in an <dfn>adjacency matrix</dfn>.
3 | 1 0 0
</pre>
Above is a very simple, undirected graph where you have three nodes, where the first node is connected to the second and third node. Below is a JavaScript implementation of the same thing.
Acima vemos um grafo muito simples e não direcionado onde você tem três nós, onde o primeiro nó está conectado ao segundo e ao terceiro nó. Abaixo, vemos uma implementação em JavaScript da mesma coisa.
```js
var adjMat = [
@ -30,7 +30,7 @@ var adjMat = [
];
```
Unlike an adjacency list, each "row" of the matrix has to have the same number of elements as nodes in the graph. Here we have a three by three matrix, which means we have three nodes in our graph. A directed graph would look similar. Below is a graph where the first node has an edge pointing toward the second node, and then the second node has an edge pointing to the third node.
Diferente do que ocorre em uma lista de adjacência, cada "linha" da matriz deve ter o mesmo número de elementos que os nós do grafo. Aqui temos uma matriz três por três, o que significa que temos três nós no nosso gráfico. Um grafo direcionado teria a mesma aparência. Abaixo, vemos um grafo onde o primeiro nó tem uma aresta apontando para o segundo nó e o segundo nó tem uma aresta apontando para o terceiro nó.
```js
var adjMatDirected = [
@ -40,15 +40,15 @@ var adjMatDirected = [
];
```
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (`0` or `1`). You can have different weights depending on your application.
Grafos também podem ter <dfn>pesos</dfn> nas arestas. Até agora, tivemos arestas <dfn>sem peso</dfn>, onde apenas a presença e a falta de aresta é binária (`0` ou `1`). Você pode ter pesos diferentes, dependendo da aplicação.
# --instructions--
Create an adjacency matrix of an undirected graph with five nodes. This matrix should be in a multi-dimensional array. These five nodes have relationships between the first and fourth node, the first and third node, the third and fifth node, and the fourth and fifth node. All edge weights are one.
Crie uma matriz de adjacência de um grafo não direcionado com cinco nós. Esta matriz deve estar em um array multidimensional. Estes cinco nós têm relações entre o primeiro e o quarto nó, entre o primeiro e o terceiro nó, entre o terceiro e o quinto nó, e entre o quarto e o quinto nó. O peso de todas as arestas é um.
# --hints--
`undirectedAdjList` should only contain five nodes.
`undirectedAdjList` deve conter apenas cinco nós.
```js
assert(
@ -63,25 +63,25 @@ assert(
);
```
There should be an edge between the first and fourth node.
Deve haver uma aresta entre o primeiro e o quarto nó.
```js
assert(adjMatUndirected[0][3] === 1 && adjMatUndirected[3][0] === 1);
```
There should be an edge between the first and third node.
Deve haver uma aresta entre o primeiro e o terceiro nó.
```js
assert(adjMatUndirected[0][2] === 1 && adjMatUndirected[2][0] === 1);
```
There should be an edge between the third and fifth node.
Deve haver uma aresta entre o terceiro e o quinto nó.
```js
assert(adjMatUndirected[2][4] === 1 && adjMatUndirected[4][2] === 1);
```
There should be an edge between the fourth and fifth node.
Deve haver uma aresta entre o quarto e o quinto nó.
```js
assert(adjMatUndirected[3][4] === 1 && adjMatUndirected[4][3] === 1);

View File

@ -1,6 +1,6 @@
---
id: 587d825c367417b2b2512c90
title: Breadth-First Search
title: Busca em largura
challengeType: 1
forumTopicId: 301622
dashedName: breadth-first-search
@ -8,31 +8,31 @@ dashedName: breadth-first-search
# --description--
So far, we've learned different ways of creating representations of graphs. What now? One natural question to have is what are the distances between any two nodes in the graph? Enter <dfn>graph traversal algorithms</dfn>.
Até agora, aprendemos diferentes maneiras de criar representações de grafos. E agora? Uma pergunta que é natural fazer é: qual é a distância entre dois nós de um grafo? Aqui entram os <dfn>algoritmos de travessia de grafos</dfn>.
<dfn>Traversal algorithms</dfn> are algorithms to traverse or visit nodes in a graph. One type of traversal algorithm is the breadth-first search algorithm.
<dfn>Algoritmos de travessia</dfn> são algoritmos que percorrem ou visitem nós em um gráfico. Um tipo de algoritmo de travessia é o algoritmo de busca em largura.
This algorithm starts at one node and visits all its neighbors that are one edge away. It then goes on to visit each of their neighbors and so on until all nodes have been reached.
Este algoritmo começa em um nó e visita todos os seus vizinhos que estão a uma aresta de distância. Em seguida, ele visita cada um dos vizinhos desses nós e assim por diante, até que todos os nós tenham sido visitados.
An important data structure that will help implement the breadth-first search algorithm is the queue. This is an array where you can add elements to one end and remove elements from the other end. This is also known as a <dfn>FIFO</dfn> or <dfn>First-In-First-Out</dfn> data structure.
Uma estrutura de dados importante que ajudará a implementar o algoritmo de busca em largura é a fila. Este é um array onde você pode adicionar elementos a uma das extremidades e remover elementos da outra extremidade. Isto também é conhecido como uma estrutura de dados <dfn>FIFO</dfn> ou <dfn>First-In-First-Out</dfn> (ou seja, o primeiro a entrar é o primeiro a sair).
Visually, this is what the algorithm is doing. ![Breadth first search algorithm moving through a tree](https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966)
Visualmente, é isso que o algoritmo está fazendo. ![Algoritmo de busca por largura percorrendo uma árvore](https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966)
The grey shading represents a node getting added into the queue and the black shading represents a node getting removed from the queue. See how every time a node gets removed from the queue (node turns black), all their neighbors get added into the queue (node turns grey).
A sombra cinza representa um nó que está sendo adicionado à fila e a sombra preta representa um nó que está sendo removido da fila. Veja como a cada vez que um nó é removido da fila (quando se torna preto), todos os seus vizinhos são adicionados à fila (se tornam cinza).
To implement this algorithm, you'll need to input a graph structure and a node you want to start at.
Para implementar este algoritmo, você precisará inserir uma estrutura de grafo e o nó em que deseja começar.
First, you'll want to be aware of the distances from, or number of edges away from, the start node. You'll want to start all your distances with some large number, like `Infinity`. This prevents counting issues for when a node may not be reachable from your start node. Next, you'll want to go from the start node to its neighbors. These neighbors are one edge away and at this point you should add one unit of distance to the distances you're keeping track of.
Primeiro, você vai querer saber as distâncias do nó inicial, ou o número de arestas de afastamento. Você vai querer começar todas as distâncias com algum número grande, como o `Infinity`. Isto evita problemas de contagem quando um nó não estiver acessível a partir do nó inicial. Em seguida, você vai querer percorrer do ponto inicial até os vizinhos dele. Estes vizinhos estão a uma aresta de distância e, neste ponto, você deve adicionar uma unidade de distância às distâncias que você está acompanhando.
# --instructions--
Write a function `bfs()` that takes an adjacency matrix graph (a two-dimensional array) and a node label root as parameters. The node label will just be the integer value of the node between `0` and `n - 1`, where `n` is the total number of nodes in the graph.
Escreva uma função `bfs()` que recebe um grafo de matriz de adjacência (um array bidimensional) e um nó com a etiqueta de raiz (root) como parâmetros. A etiqueta do nó será apenas o valor inteiro do nó entre `0` e `n - 1`, onde `n` é o número total de nós no grafo.
Your function will output a JavaScript object key-value pairs with the node and its distance from the root. If the node could not be reached, it should have a distance of `Infinity`.
A função retornará um par chave-valor em JavaScript com o nó e a sua distância do nó raiz. Se o nó não puder ser alcançado, a distância deve ser `Infinity`.
# --hints--
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` with a start node of `1` should return `{0: 1, 1: 0, 2: 1, 3: 2}`
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` com o nó inicial `1` deve retornar `{0: 1, 1: 0, 2: 1, 3: 2}`
```js
assert(
@ -49,7 +49,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` with a start node of `1` should return `{0: 1, 1: 0, 2: 1, 3: Infinity}`
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` com o nó inicial `1` deve retornar `{0: 1, 1: 0, 2: 1, 3: Infinity}`
```js
assert(
@ -66,7 +66,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` with a start node of `0` should return `{0: 0, 1: 1, 2: 2, 3: 3}`
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` com o nó inicial `0` deve retornar `{0: 0, 1: 1, 2: 2, 3: 3}`
```js
assert(
@ -83,7 +83,7 @@ assert(
);
```
The input graph `[[0, 1], [1, 0]]` with a start node of `0` should return `{0: 0, 1: 1}`
O gráfico de entrada `[[0, 1], [1, 0]]` com um nó inicial de `0` deve retornar `{0: 0, 1: 1}`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7c
title: Check if an Element is Present in a Binary Search Tree
title: Verificar se um elemento está presente em uma árvore binária de busca
challengeType: 1
forumTopicId: 301623
dashedName: check-if-an-element-is-present-in-a-binary-search-tree
@ -8,15 +8,15 @@ dashedName: check-if-an-element-is-present-in-a-binary-search-tree
# --description--
Now that we have a general sense of what a binary search tree is let's talk about it in a little more detail. Binary search trees provide logarithmic time for the common operations of lookup, insertion, and deletion in the average case, and linear time in the worst case. Why is this? Each of those basic operations requires us to find an item in the tree (or in the case of insertion to find where it should go) and because of the tree structure at each parent node we are branching left or right and effectively excluding half the size of the remaining tree. This makes the search proportional to the logarithm of the number of nodes in the tree, which creates logarithmic time for these operations in the average case. Ok, but what about the worst case? Well, consider constructing a tree from the following values, adding them left to right: `10`, `12`, `17`, `25`. Following our rules for a binary search tree, we will add `12` to the right of `10`, `17` to the right of this, and `25` to the right of this. Now our tree resembles a linked list and traversing it to find `25` would require us to traverse all the items in linear fashion. Hence, linear time in the worst case. The problem here is that the tree is unbalanced. We'll look a little more into what this means in the following challenges.
Agora que temos uma ideia geral do que é uma árvore binária de busca, vamos conversar sobre ela de maneira um pouco mais detalhada. Árvores de pesquisa binária fornecem tempo logarítmico para operações comuns de pesquisa, inserção e exclusão em média e tempo linear no pior dos casos. Por quê? Cada uma dessas operações básicas exige que encontremos um item na árvore (ou, no caso da inserção, encontrar onde ele deve ir). Por causa da estrutura das árvores, em cada nó pai, estamos ramificando à esquerda ou à direita e excluindo efetivamente metade do tamanho da árvore restante. Isto torna a busca proporcional ao logaritmo do número de nós na árvore, o que cria tempo logarítmico para estas operações em média. Certo, mas e no pior dos casos? Bem, considere a construção de uma árvore a partir dos seguintes valores, adicionando-os da esquerda para a direita: `10`, `12`, `17`, `25`. Seguindo nossas regras para uma árvore binária de busca, vamos adicionar `12` à direita de `10`, `17` à direita deste e `25` à direita deste. Agora, nossa árvore se parece com uma lista encadeada. Atravessá-la para encontrar `25` nos obrigaria a atravessar todos os itens de forma linear. Assim, o tempo seria linear no pior dos casos. O problema aqui é que a árvore é desbalanceada. Vamos examinar um pouco melhor o que isso significa nos próximos desafios.
# --instructions--
In this challenge, we will create a utility for our tree. Write a method `isPresent` which takes an integer value as input and returns a boolean value for the presence or absence of that value in the binary search tree.
Neste desafio, criaremos um utilitário para a nossa árvore. Escreva um método `isPresent`, que recebe um valor inteiro como entrada e retorna um valor booleano para a presença ou ausência desse valor na árvore binária de busca.
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
The binary search tree should have a method called `isPresent`.
A árvore binária de busca deve ter um método chamado `isPresent`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
The `isPresent` method should correctly check for the presence or absence of elements added to the tree.
O método `isPresent` deve verificar corretamente se há a presença ou a ausência de elementos adicionados à árvore.
```js
assert(
@ -74,7 +74,7 @@ assert(
);
```
`isPresent` should handle cases where the tree is empty.
`isPresent` deve tratar de casos onde a árvore está vazia.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5cc0c1b32479e176caf3b422
title: Check if Tree is Binary Search Tree
title: Verificar se a árvore é uma árvore binária de busca
challengeType: 1
forumTopicId: 301624
dashedName: check-if-tree-is-binary-search-tree
@ -8,17 +8,17 @@ dashedName: check-if-tree-is-binary-search-tree
# --description--
Since you already know what a binary search tree is, this challenge will establish how it is you can tell that a tree is a binary search tree or not.
Como você já sabe o que é uma árvore binária de busca, este desafio vai estabelecer como você pode dizer que uma árvore é uma árvore binária de busca ou não.
The main distinction of a binary search tree is that the nodes are ordered in an organized fashion. Nodes have at most 2 child nodes (placed to the right and/or left) based on if the child node's value is greater than or equal to (right) or less than (left) the parent node.
A principal distinção está no fato de que uma árvore binária de busca tem os nós ordenados de maneira organizada. Os nós têm no máximo 2 nós filhos (colocados à direita e/ou à esquerda) com base no valor do nó filho ser maior ou igual a (à direita) ou menor que (à esquerda) o valor do nó pai.
# --instructions--
In this challenge, you will create a utility for your tree. Write a JavaScript method `isBinarySearchTree` which takes a tree as an input and returns a boolean value for whether the tree is a binary search tree or not. Use recursion whenever possible.
Neste desafio, você criará um utilitário para a árvore. Escreva um método `isBinarySearchTree` em JavaScript que receba uma árvore como entrada e retorne um valor booleano para saber se a árvore é ou não uma árvore binária de busca. Use recursão sempre que possível.
# --hints--
Your Binary Search Tree should return true when checked with `isBinarySearchTree()`.
A árvore binária de busca deve retornar true quando verificada com `isBinarySearchTree()`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c75
title: Create a Circular Queue
title: Criar uma fila circular
challengeType: 1
forumTopicId: 301625
dashedName: create-a-circular-queue
@ -8,9 +8,9 @@ dashedName: create-a-circular-queue
# --description--
In this challenge you will be creating a Circular Queue. A circular queue is a queue that writes to the end of a collection then begins overwriting itself at the beginning of the collection. This type of data structure is useful in certain situations. For example, a circular queue can be used for streaming media. Once the queue is full, new media data will overwrite old data.
Neste desafio, você criará uma fila circular. Uma fila circular é uma fila escreve até o final de uma coleção e que, então, começa a se sobrescrever no início da coleção. Este tipo de estrutura de dados é útil em certas situações. Por exemplo, uma fila circular pode ser usada para streaming de mídia. Quando a fila está cheia, os novos dados de mídia vão sobrescrever os dados antigos.
A good way to illustrate this concept is with an array of length `5`:
Uma boa maneira de ilustrar esse conceito é com um array de tamanho `5`:
```js
[null, null, null, null, null]
@ -18,7 +18,7 @@ A good way to illustrate this concept is with an array of length `5`:
^Write @ 0
```
Here the read and write are both at position `0`. Now the queue gets 3 new records `a`, `b`, and `c`. Our queue now looks like:
Aqui, a leitura e a escrita estão ambos na posição `0`. Agora, a fila recebe 3 novos registros `a`, `b`, e `c`. Nossa fila agora se parece assim:
```js
[a, b, c, null, null]
@ -26,7 +26,7 @@ Here the read and write are both at position `0`. Now the queue gets 3 new recor
^Write @ 3
```
As the read head reads, it can remove values or keep them:
Como a cabeça de leitura lê, pode remover valores ou mantê-los:
```js
[null, null, null, null, null]
@ -34,7 +34,7 @@ As the read head reads, it can remove values or keep them:
^Write @ 3
```
Now we write the values `d`, `e`, and `f` to the queue. Once the write reaches the end of the array it loops back to the beginning:
Agora, gravamos os valores `d`, `e` e `f` na fila. Quando a gravação atinge o fim do array, ela retorna ao início:
```js
[f, null, null, d, e]
@ -42,21 +42,21 @@ Now we write the values `d`, `e`, and `f` to the queue. Once the write reaches t
^Write @ 1
```
This approach requires a constant amount of memory but allows files of a much larger size to be processed.
Esta abordagem requer uma quantidade constante de memória, mas permite que arquivos de um tamanho muito maior sejam processados.
# --instructions--
In this challenge we will implement a circular queue. The circular queue should provide `enqueue` and `dequeue` methods which allow you to read from and write to the queue. The class itself should also accept an integer argument which you can use to specify the size of the queue when created. We've written the starting version of this class for you in the code editor.
Neste desafio, você criará uma fila circular. A fila circular deve fornecer os métodos `enqueue` e `dequeue`, que permitem que você leia e grave na fila. A classe também deve aceitar um argumento inteiro que você pode usar para especificar o tamanho da fila quando criada. Gravamos a versão inicial desta classe para você no editor de código.
When you enqueue items to the queue, the write pointer should advance forward and loop back to the beginning once it reaches the end of the queue. The `enqueue` method should return the item you enqueued if it is successful; otherwise it will return `null`.
Quando você incluir itens na fila, o ponteiro de gravação deve avançar para frente e retornar para o início assim que chegar ao final da fila. O método `enqueue` deve retornar o item que você colocou na fila se for bem-sucedido. Caso contrário, ele retornará `null`.
Likewise, the read pointer should advance forward as you dequeue items. When you dequeue an item, that item should be returned. If you cannot dequeue an item, you should return `null`.
Da mesma forma, o ponteiro de leitura deve avançar enquanto você remove os itens da fila. Quando você remove um item, o item deve ser retornado. Se você não puder remover um item da fila, você deve retornar `null`.
The write pointer should not be allowed to move past the read pointer (our class won't let you overwrite data you haven't read yet) and the read pointer should not be able to advance past data you have written.
Não deve ser permitido ao ponteiro de gravação passar pelo ponteiro de leitura (nossa classe não permitirá que você substitua dados que ainda não leu). Além disso, o ponteiro de leitura não deve ser capaz de avançar passando por dados que você gravou.
# --hints--
The `enqueue` method should add items to the circular queue.
O método `enqueue` deve adicionar itens à fila circular.
```js
assert(
@ -71,7 +71,7 @@ assert(
);
```
You should not enqueue items past the read pointer.
Você não deve enfileirar itens além do ponteiro de leitura.
```js
assert(
@ -89,7 +89,7 @@ assert(
);
```
The `dequeue` method should dequeue items from the queue.
O método `dequeue` deve remover os itens da fila.
```js
assert(
@ -105,7 +105,7 @@ assert(
);
```
After an item is dequeued, its position in the queue should be reset to `null`.
Depois que um item for removido da fila, sua posição na fila deve ser redefinida para `null`.
```js
assert(
@ -122,7 +122,7 @@ assert(
);
```
Trying to dequeue past the write pointer should return `null` and does not advance the write pointer.
Tentando remover da fila além do ponteiro de gravação deve retornar `null` e não avançará esse ponteiro.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825a367417b2b2512c87
title: Create a Doubly Linked List
title: Criar uma lista duplamente encadeada
challengeType: 1
forumTopicId: 301626
dashedName: create-a-doubly-linked-list
@ -8,19 +8,19 @@ dashedName: create-a-doubly-linked-list
# --description--
All of the linked lists we've created so far are singly linked lists. Here, we'll create a <dfn>doubly linked list</dfn>. As the name implies, nodes in a doubly linked list have references to the next and previous node in the list.
Todas as listas que criamos até agora são listas encadeadas com apenas uma direção. Aqui, criaremos uma <dfn>lista duplamente encadeada</dfn>. Como o nome sugere, os nós de uma lista duplamente encadeada têm referências para o próximo nó e para o nó anterior na lista.
This allows us to traverse the list in both directions but it also requires more memory to be used because every node must contain an additional reference to the previous node in the list.
Isto nos permite atravessar a lista em ambas as direções, mas também requer que mais memória seja usada, pois cada nó deve conter uma referência adicional ao nó anterior na lista.
# --instructions--
We've provided a `Node` object and started our `DoublyLinkedList`. Let's add two methods to our doubly linked list called `add` and `remove`. The `add` method should add the given element to the list while the `remove` method should remove all occurrences of a given element in the list.
Fornecemos um objeto `Node` e começamos nossa `DoublyLinkedList`. Vamos adicionar dois métodos à nossa lista de duplamente encadeada chamados `add` e `remove`. O método `add` deve adicionar o elemento dado à lista, enquanto o método `remove` deve remover todas as ocorrências de um determinado elemento na lista.
Be careful to handle any possible edge cases when writing these methods, such as deletions for the first or last element. Also, removing any item on an empty list should return `null`.
Tenha cuidado ao lidar com possíveis casos nas extremidades da lista ao escrever estes métodos, tais como exclusões do primeiro ou do último elemento. Além disso, remover qualquer item em uma lista vazia deve retornar `null`.
# --hints--
The DoublyLinkedList data structure should exist.
A estrutura de dados DoublyLinkedList deve existir.
```js
assert(
@ -34,7 +34,7 @@ assert(
);
```
The DoublyLinkedList should have a method called add.
A DoublyLinkedList deve ter um método chamado add.
```js
assert(
@ -51,7 +51,7 @@ assert(
);
```
The DoublyLinkedList should have a method called remove.
A DoublyLinkedList deve ter um método chamado remove.
```js
assert(
@ -68,7 +68,7 @@ assert(
);
```
Removing an item from an empty list should return null.
Remover qualquer item em uma lista vazia deve retornar null.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
The add method should add items to the list.
O método add deve adicionar itens à lista.
```js
assert(
@ -99,7 +99,7 @@ assert(
);
```
Each node should keep track of the previous node.
Cada nó deve manter um registro do nó anterior.
```js
assert(
@ -116,7 +116,7 @@ assert(
);
```
The first item should be removable from the list.
O primeiro item deve poder ser removido da lista.
```js
assert(
@ -134,7 +134,7 @@ assert(
);
```
The last item should be removable from the list.
O último item deve poder ser removido da lista.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8e
title: Create a Hash Table
title: Criar uma tabela hash
challengeType: 1
forumTopicId: 301627
dashedName: create-a-hash-table
@ -8,23 +8,23 @@ dashedName: create-a-hash-table
# --description--
In this challenge we will learn about hash tables. A Hash table is used to implement associative arrays, or mappings of key-value pairs, like the objects and Maps we have just been studying. A JavaScript object could be implemented as a hash table, for instance (its actual implementation will depend on the environment it's running in). The way a hash table works is that it takes a key input and hashes this key in a deterministic way to some numerical value. This numerical value is then used as the actual key the associated value is stored by. Then, if you try to access the same key again, the hashing function will process the key, return the same numerical result, which will then be used to look up the associated value. This provides very efficient O(1) lookup time on average.
Neste desafio, aprenderemos sobre tabelas hash. Uma tabela hash é usada para implementar arrays associativos ou mapeamentos de pares chave-valor, como os objetos e mapas que temos estudado. Um objeto JavaScript pode ser implementado como uma tabela hash, por exemplo (a implementação de fato dependerá do ambiente em que estiver rodando). O modo como uma tabela hash funciona é recebendo uma entrada de chave e fazendo o hash dessa chave de modo determinístico para algum valor numérico. Este valor numérico é então usado como a chave real através da qual o valor associado é armazenado. Depois, se você tentar acessar a mesma chave novamente, a função de hashing processará a chave, retorna o mesmo resultado numérico e ele será usado para procurar o valor associado. Isto proporciona um tempo de pesquisa O(1) muito eficiente, em média.
Hash tables can be implemented as arrays with hash functions producing array indices within a specified range. In this method, the choice of the array size is important, as is the hashing function. For instance, what if the hashing function produces the same value for two different keys? This is called a collision. One way to handle collisions is to just store both key-value pairs at that index. Then, upon lookup of either, you would have to iterate through the bucket of items to find the key you are looking for. A good hashing function will minimize collisions to maintain efficient search time.
As tabelas hash podem ser implementadas como arrays com funções de hash produzindo índices de array dentro de um intervalo especificado. Nesse método, a escolha do tamanho do array é importante, assim como a função de hashing. Por exemplo, o que aconteceria se a função de hashing produzisse o mesmo valor para duas chaves diferentes? A isso chamamos de colisão. Uma maneira de lidar com colisões é apenas armazenar os dois pares chave-valor naquele índice. Então, ao consultar qualquer um, você teria que iterar através do grupo de itens para encontrar a chave que está procurando. Uma boa função de hashing minimizará colisões para manter o tempo de busca eficiente.
Here, we won't be concerned with the details of hashing or hash table implementation, we will just try to get a general sense of how they work.
Aqui, não nos preocuparemos com os detalhes da implementação do hashing e das tabelas hash. Tentaremos apenas ter uma noção geral de como funcionam.
# --instructions--
Let's create the basic functionality of a hash table. We've created a naive hashing function for you to use. You can pass a string value to the function `hash` and it will return a hashed value you can use as a key for storage. Store items based on this hashed value in the `this.collection` object. Create these three methods: `add`, `remove`, and `lookup`. The first should accept a key value pair to add to the hash table. The second should remove a key-value pair when passed a key. The third should accept a key and return the associated value or `null` if the key is not present.
Vamos criar a funcionalidade básica de uma tabela hash. Criamos uma função de hashing simples para sua utilização. Você pode passar um valor de string para a função `hash` e ele retornará um valor de hash que você pode usar como chave para o armazenamento. Armazene itens baseados neste valor de hash no objeto `this.collection`. Crie esses três métodos: `add`, `remove` e `lookup`. O primeiro deve aceitar um par de chave-valor para adicionar à tabela hash. O segundo deve remover um par de chave-valor quando recebe uma chave. O terceiro deve aceitar uma chave e retornar o valor associado ou `null` se a chave não estiver presente.
Be sure to write your code to account for collisions!
Não se esqueça de escrever seu código para levar em conta as colisões!
**Note:** The `remove` method tests won't pass until the `add` and `lookup` methods are correctly implemented.
**Observação:** os testes do método `remove` não passarão até que os métodos `add` e `lookup` sejam corretamente implementados.
# --hints--
The HashTable data structure should exist.
A estrutura de dados HashTable deve existir.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
The HashTable should have an add method.
A HashTable deve ter um método add.
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
The HashTable should have a lookup method.
A HashTable deve ter um método lookup.
```js
assert(
@ -66,7 +66,7 @@ assert(
);
```
The HashTable should have a remove method.
A HashTable deve ter um método remove.
```js
assert(
@ -80,7 +80,7 @@ assert(
);
```
The add method should add key value pairs and the lookup method should return the values associated with a given key.
O método add deve adicionar pares chave-valor e o método lookup deve retornar os valores associados a uma determinada chave.
```js
assert(
@ -95,7 +95,7 @@ assert(
);
```
The remove method should accept a key as input and should remove the associated key value pair.
O método remove deve aceitar uma chave como entrada e deve remover o par chave-valor associado.
```js
assert(
@ -113,7 +113,7 @@ assert(
);
```
The remove method should only remove the correct key value pair.
O método remove só deve remover o par chave-valor correto.
```js
assert(
@ -139,7 +139,7 @@ assert(
);
```
Items should be added using the hash function.
Os itens devem ser adicionados usando a função de hash.
```js
assert(
@ -157,7 +157,7 @@ assert(
);
```
The hash table should handle collisions.
A tabela hash deve tratar de colisões.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c62
title: Create a Linked List Class
title: Criar uma classe de lista encadeada
challengeType: 1
forumTopicId: 301628
dashedName: create-a-linked-list-class
@ -8,25 +8,25 @@ dashedName: create-a-linked-list-class
# --description--
Let's create a `linked list` class. Every linked list should start out with a few basic properties: a `head` (the first item in your list) and a `length` (number of items in your list). Sometimes you'll see implementations of linked lists that incorporate a `tail` for the last element of the list, but for now we'll just stick with these two. Whenever we add an element to the linked list, our `length` property should be incremented by one.
Vamos criar uma classe `linked list`. Cada lista encadeada deve começar com algumas propriedades básicas: uma `head` (o primeiro item da lista) e um `length` (o número de itens na lista). Às vezes, você verá implementações de listas encadeadas que incorporam uma `tail` para o último elemento da lista, mas, por enquanto, vamos nos manter com estes dois. Sempre que adicionarmos um elemento à lista encadeada, a propriedade `length` deve ser incrementada em mais uma.
We'll want to have a way to add items to our linked list, so the first method we'll want to create is the `add` method.
Queremos ter uma maneira de adicionar itens à nossa lista encadeada, então o primeiro método que devemos criar é o método `add`.
If our list is empty, adding an element to our linked list is straightforward enough: we just wrap that element in a `Node` class, and we assign that node to the `head` of our linked list.
Se a lista estiver vazia, adicionar um elemento nela é bastante direto: apenas encapsulamos esse elemento em uma classe `Node` e atribuímos esse nó à `head` de nossa lista encadeada.
But what if our list already has one or more members? How do we add an element to the list? Recall that each node in a linked list has a `next` property. To add a node to the list, find the last node in the list, and point that last node's `next` property at our new node. (Hint: you know you've reached the end of a linked list when a node's `next` property is `null`.)
Mas e se a lista já tiver um ou mais membros? Como adicionamos um elemento à lista? Lembre-se de que cada nó de uma lista encadeada tem uma propriedade `next`. Para adicionar um nó à lista, encontre o último nó na lista e aponte esse último nó para a propriedade `next` do novo nó. (Dica: você sabe que chegou ao final de uma lista vinculada quando a propriedade `next` de um nó é `null`.)
# --instructions--
Write an add method that assigns the first node you push to the linked list to the `head`; after that, whenever adding a node, every node should be referenced by the previous node's `next` property.
Escreva um método add que atribui `head` ao primeiro nó que você insere na lista encadeada. Depois disso, sempre que adicionar um nó, cada nó deve ser referenciado pela propriedade `next` do nó anterior.
Note
Observação
Your list's `length` should increase by one every time an element is added to the linked list.
A propriedade `length` da lista encadeada deve aumentar de um em um sempre que um elemento for adicionado a ela.
# --hints--
Your `LinkedList` class should have a `add` method.
A classe `LinkedList` deve ter o método `add`.
```js
assert(
@ -37,7 +37,7 @@ assert(
);
```
Your `LinkedList` class should assign `head` to the first node added.
A classe `LinkedList` deve atribuir `head` ao primeiro nó adicionado.
```js
assert(
@ -49,7 +49,7 @@ assert(
);
```
The previous `node` in your `LinkedList` class should have reference to the newest node created.
O `node` anterior na sua classe `LinkedList` deve ter referência ao nó criado mais recentemente.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
The `size` of your `LinkedList` class should equal the amount of nodes in the linked list.
O `size` da sua classe `LinkedList` deve ser igual à quantidade de nós da lista encadeada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 8d5823c8c441eddfaeb5bdef
title: Create a Map Data Structure
title: Criar uma estrutura de dados de mapa
challengeType: 1
forumTopicId: 301629
dashedName: create-a-map-data-structure
@ -8,25 +8,25 @@ dashedName: create-a-map-data-structure
# --description--
The next few challenges will cover maps and hash tables. Maps are data structures that store key-value pairs. In JavaScript, these are available to us as objects. Maps provide rapid lookup of stored items based on key values and are very common and useful data structures.
Os próximos desafios tratarão de mapas e tabelas hash. Mapas são estruturas de dados que armazenam pares chave-valor. Em JavaScript, essas estruturas estão disponíveis para nós como objetos. Mapas fornecem uma busca rápida de itens armazenados com base em valores chave e são estruturas de dados muito comuns e úteis.
# --instructions--
Let's get some practice creating our own map. Because JavaScript objects provide a much more efficient map structure than anything we could write here, this is intended primarily as a learning exercise. However, JavaScript objects only provide us with certain operations. What if we wanted to define custom operations? Use the `Map` object provided here as a wrapper around a JavaScript `object`. Create the following methods and operations on the Map object:
Vamos praticar um pouco criando nosso próprio mapa. Como objetos JavaScript fornecem uma estrutura de mapa muito mais eficiente do que qualquer outra que pudéssemos escrever aqui, o objetivo aqui é, principalmente, um exercício de aprendizagem. No entanto, objetos JavaScript nos fornecem apenas algumas operações. E se quiséssemos definir operações personalizadas? Use o objeto `Map` fornecido aqui para envolver o `object` de JavaScript. Criar os seguintes métodos e operações no objeto Map:
<ul>
<li><code>add</code> accepts a <code>key, value</code> pair to add to the map.</li>
<li><code>remove</code> accepts a key and removes the associated <code>key, value</code> pair</li>
<li><code>get</code> accepts a <code>key</code> and returns the stored <code>value</code></li>
<li><code>has</code> accepts a <code>key</code> and returns <dfn>true</dfn> if the key exists or <dfn>false</dfn> if it doesn't.</li>
<li><code>values</code> returns an array of all the values in the map</li>
<li><code>size</code> returns the number of items in the map</li>
<li><code>clear</code> empties the map</li>
<li><code>add</code> aceita um par <code>key, value</code> para adicioná-lo ao mapa.</li>
<li><code>remove</code> aceita uma chave e remove o par <code>key, value</code> associado</li>
<li><code>get</code> aceita uma <code>key</code> e retorna o <code>value</code> armazenado</li>
<li><code>has</code> aceita uma <code>key</code> e retorna <dfn>true</dfn>, se a chave existir no mapa, ou <dfn>false</dfn>, se ela não existir.</li>
<li><code>values</code> retorna um array de todos os valores no mapa</li>
<li><code>size</code> retorna o número de itens no mapa</li>
<li><code>clear</code> esvazia o mapa</li>
</ul>
# --hints--
The Map data structure should exist.
A estrutura de dados Map deve existir.
```js
assert(
@ -40,7 +40,7 @@ assert(
);
```
The Map object should have the following methods: add, remove, get, has, values, clear, and size.
O objeto Map deve ter os seguintes métodos: add, remove, get, has, values, clear e size.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
The add method should add items to the map.
O método add deve adicionar itens ao mapa.
```js
assert(
@ -79,7 +79,7 @@ assert(
);
```
The has method should return true for added items and false for absent items.
O método has deve retornar true para itens adicionados e false para itens ausentes.
```js
assert(
@ -94,7 +94,7 @@ assert(
);
```
The get method should accept keys as input and should return the associated values.
O método get deve aceitar chaves como entrada e deve retornar os valores associados.
```js
assert(
@ -109,7 +109,7 @@ assert(
);
```
The values method should return all the values stored in the map as strings in an array.
O método values deve retornar todos os valores armazenados no mapa como strings em um array.
```js
assert(
@ -131,7 +131,7 @@ assert(
);
```
The clear method should empty the map and the size method should return the number of items present in the map.
O método clear deve esvaziar o mapa e o método size deve retornar o número de itens presentes no mapa.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c74
title: Create a Priority Queue Class
title: Criar uma classe de fila de prioridade
challengeType: 1
forumTopicId: 301630
dashedName: create-a-priority-queue-class
@ -8,27 +8,27 @@ dashedName: create-a-priority-queue-class
# --description--
In this challenge you will be creating a Priority Queue. A Priority Queue is a special type of Queue in which items may have additional information which specifies their priority. This could be simply represented with an integer. Item priority will override placement order in determining the sequence items are dequeued. If an item with a higher priority is enqueued after items with lower priority, the higher priority item will be dequeued before all the others.
Neste desafio, você criará uma fila de prioridade. Uma fila de prioridade é um tipo especial de fila, na qual os itens podem ter informações adicionais que especificam a sua prioridade. Isto poderia ser representado simplesmente por um número inteiro. A prioridade do item substituirá a ordem de colocação ao determinar a sequência na qual os itens saem da fila. Se um item com maior prioridade for colocado na fila após itens com menor prioridade, o item de maior prioridade será removido da fila antes de todos os outros.
For instance, lets imagine we have a priority queue with three items:
Por exemplo, vamos imaginar que temos uma fila de prioridade com três itens:
```js
[['kitten', 2], ['dog', 2], ['rabbit', 2]]
```
Here the second value (an integer) represents item priority. If we enqueue `['human', 1]` with a priority of `1` (assuming lower priorities are given precedence) it would then be the first item to be dequeued. The collection would look like this:
Aqui o segundo valor (um inteiro) representa a prioridade do item. Se enfileirarmos `['human', 1]` com prioridade de `1` (assumindo que prioridades inferiores tenham precedência), ele seria então o primeiro item a ser colocado em fila. A coleção ficaria assim:
```js
[['human', 1], ['kitten', 2], ['dog', 2], ['rabbit', 2]]
```
Weve started writing a `PriorityQueue` in the code editor. You will need to add an `enqueue` method for adding items with a priority, a `dequeue` method for removing and returning items, a `size` method to return the number of items in the queue, a `front` method to return the element at the front of the queue, and finally an `isEmpty` method that will return `true` if the queue is empty or `false` if it is not.
Começamos a escrever uma `PriorityQueue` no editor de código. Você precisará adicionar um método `enqueue` para adicionar itens com uma prioridade, um método `dequeue` para remover e retornar itens, um método `size` para retornar o número de itens na fila, um método `front` para retornar o elemento na frente da fila, e, finalmente, um método `isEmpty` que retornará `true` se a fila estiver vazia ou `false` se não estiver.
The `enqueue` should accept items with the format shown above (`['human', 1]`) where `1` represents the priority. `dequeue` and `front` should return only the item's name, not its priority.
O método `enqueue` deve aceitar itens com o formato mostrado acima (`['human', 1]`), onde `1` representa a prioridade. `dequeue` e `front` devem retornar apenas o nome do item, não sua prioridade.
# --hints--
Your `PriorityQueue` class should have a `enqueue` method.
A classe `PriorityQueue` deve ter o método `enqueue`.
```js
assert(
@ -39,7 +39,7 @@ assert(
);
```
Your `PriorityQueue` class should have a `dequeue` method.
A classe `PriorityQueue` deve ter o método `dequeue`.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
Your `PriorityQueue` class should have a `size` method.
A classe `PriorityQueue` deve ter o método `size`.
```js
assert(
@ -61,7 +61,7 @@ assert(
);
```
Your `PriorityQueue` class should have a `front` method.
A classe `PriorityQueue` deve ter o método `front`.
```js
assert(
@ -72,7 +72,7 @@ assert(
);
```
Your `PriorityQueue` class should have an `isEmpty` method.
A classe `PriorityQueue` deve ter o método `isEmpty`.
```js
assert(
@ -83,7 +83,7 @@ assert(
);
```
Your `PriorityQueue` class should correctly keep track of the current number of items using the `size` method as items are enqueued and dequeued.
A classe `PriorityQueue` deve acompanhar corretamente o número atual dos itens usando o método `size` à medida que os itens são colocados na fila e removidos dela.
```js
assert(
@ -102,7 +102,7 @@ assert(
);
```
The `front` method should return the correct item at the front of the queue as items are enqueued and dequeued.
O método `front` deve retornar o item correto na frente da fila à medida que os itens são colocados e retirados da fila.
```js
assert(
@ -129,7 +129,7 @@ assert(
);
```
The `isEmpty` method should return `true` when the queue is empty.
O método `isEmpty` deve retornar `true` quando a fila estiver vazia.
```js
assert(
@ -145,7 +145,7 @@ assert(
);
```
The priority queue should return items with a higher priority before items with a lower priority and return items in first-in-first-out order otherwise.
A fila de prioridade deve retornar os itens com uma prioridade maior antes dos itens com prioridade menor e retornar os itens na ordem First-in-First-out (o primeiro a entrar é o primeiro a sair) em todos os outros casos.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8250367417b2b2512c60
title: Create a Queue Class
title: Criar uma classe de fila
challengeType: 1
forumTopicId: 301631
dashedName: create-a-queue-class
@ -8,19 +8,19 @@ dashedName: create-a-queue-class
# --description--
Like stacks, queues are a collection of elements. But unlike stacks, queues follow the FIFO (First-In First-Out) principle. Elements added to a queue are pushed to the tail, or the end, of the queue, and only the element at the front of the queue is allowed to be removed.
Da mesma forma que ocorre com as pilhas, as filas são uma coleção de elementos. Mas, ao contrário delas, as filas seguem o princípio FIFO (First-In First-Out, o primeiro a entrar é o primeiro a sair). Elementos adicionados à fila vão empurrados para o final da fila. Apenas o elemento da frente da fila pode ser removido.
We could use an array to represent a queue, but just like stacks, we want to limit the amount of control we have over our queues.
Nós poderíamos usar um array para representar uma fila, mas, assim como fizemos como as pilhas, queremos limitar a quantidade de controle que temos sobre elas.
The two main methods of a queue class is the enqueue and the dequeue method. The enqueue method pushes an element to the tail of the queue, and the dequeue method removes and returns the element at the front of the queue. Other useful methods are the front, size, and isEmpty methods.
Os dois métodos principais de uma classe de fila são os métodos enqueue (colocar na fila) e dequeue (remover da fila). O método enqueue faz um push de um elemento para o final da fila, enquanto o método dequeue remove e retorna o elemento na frente da fila. Outros métodos úteis são os métodos front, size e isEmpty.
# --instructions--
Write an `enqueue` method that pushes an element to the tail of the queue, a `dequeue` method that removes and returns the front element, a `front` method that lets us see the front element, a `size` method that shows the length, and an `isEmpty` method to check if the queue is empty.
Escreva um método `enqueue` que faça o push de um elemento para o final da fila, um método `dequeue`, que remove e retorna o elemento da frente, um método `front`, que nos permite ver o elemento da frente, um método `size`, que mostra o tamanho da fila, e um método `isEmpty` para verificar se a fila está vazia.
# --hints--
Your `Queue` class should have a `enqueue` method.
A classe `Queue` deve ter o método `enqueue`.
```js
assert(
@ -31,7 +31,7 @@ assert(
);
```
Your `Queue` class should have a `dequeue` method.
A classe `Queue` deve ter o método `dequeue`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
Your `Queue` class should have a `front` method.
A classe `Queue` deve ter o método `front`.
```js
assert(
@ -53,7 +53,7 @@ assert(
);
```
Your `Queue` class should have a `size` method.
A classe `Queue` deve ter o método `size`.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
Your `Queue` class should have an `isEmpty` method.
A classe `Queue` deve ter o método `isEmpty`.
```js
assert(
@ -75,7 +75,7 @@ assert(
);
```
The `dequeue` method should remove and return the front element of the queue
O método `dequeue` deve remover e retornar o elemento da frente da fila
```js
assert(
@ -88,7 +88,7 @@ assert(
);
```
The `front` method should return value of the front element of the queue
O método `front` deve retornar o valor do elemento da frente da fila
```js
assert(
@ -101,7 +101,7 @@ assert(
);
```
The `size` method should return the length of the queue
O método `size` deve retornar o tamanho da fila
```js
assert(
@ -113,7 +113,7 @@ assert(
);
```
The `isEmpty` method should return `false` if there are elements in the queue
O método `isEmpty` deve retornar `false` quando houver elementos na fila
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 8d1323c8c441eddfaeb5bdef
title: Create a Set Class
title: Criar uma classe conjunto
challengeType: 1
forumTopicId: 301632
dashedName: create-a-set-class
@ -8,7 +8,7 @@ dashedName: create-a-set-class
# --description--
In this exercise we are going to create a class named `Set` to emulate an abstract data structure called "set". A set is like an array, but it cannot contain duplicate values. The typical use for a set is to simply check for the presence of an item. We can see how the ES6 `Set` object works in the example below:
Neste exercício, vamos criar uma classe chamada `Set` para emular uma estrutura de dados abstrata chamada "set" (conjunto). Um conjunto é como um array, mas não pode conter valores duplicados. A utilização típica de um conjunto é simplesmente verificar a presença de um item. Podemos ver como o objeto `Set` do ES6 funciona no exemplo abaixo:
```js
const set1 = new Set([1, 2, 3, 5, 5, 2, 0]);
@ -20,17 +20,17 @@ console.log(set1.has(6));
// output: false
```
First, we will create an add method that adds a value to our set collection as long as the value does not already exist in the set. Then we will create a remove method that removes a value from the set collection if it already exists. And finally, we will create a size method that returns the number of elements inside the set collection.
Primeiramente, criaremos um método add que adiciona um valor à coleção desde que o valor já não exista no conjunto. Então, criaremos um método remove que remove um valor da coleção definida, se ele já existir lá. Por fim, criaremos um método size, que retorna o número de elementos dentro da coleção definida.
# --instructions--
Create an `add` method that adds a unique value to the set collection and returns `true` if the value was successfully added and `false` otherwise.
Crie um método `add`, que adiciona um valor único à coleção do conjunto, retornando `true` se o valor for adicionado com sucesso e `false` se não for.
Create a `remove` method that accepts a value and checks if it exists in the set. If it does, then this method should remove it from the set collection, and return `true`. Otherwise, it should return `false`. Create a `size` method that returns the size of the set collection.
Crie um método `remove` que aceita um valor e verifica se ele existe no conjunto. Se existir, o método deve remover o valor da coleção do conjunto e retornar `true`. Caso contrário, ele deverá retornar `false`. Crie um método `size` que retorne o tamanho da coleção do conjunto.
# --hints--
Your `Set` class should have an `add` method.
A classe `Set` deve ter o método `add`.
```js
assert(
@ -41,7 +41,7 @@ assert(
);
```
Your `add` method should not add duplicate values.
O método `add` não deve adicionar valores duplicados.
```js
assert(
@ -56,7 +56,7 @@ assert(
);
```
Your `add` method should return `true` when a value has been successfully added.
O método `add` deve retornar `true` quando um valor for adicionado ao conjunto com sucesso.
```js
assert(
@ -68,7 +68,7 @@ assert(
);
```
Your `add` method should return `false` when a duplicate value is added.
O método `add` deve retornar `false` quando tentar adicionar um valor duplicado.
```js
assert(
@ -81,7 +81,7 @@ assert(
);
```
Your `Set` class should have a `remove` method.
A classe `Set` deve ter o método `remove`.
```js
assert(
@ -92,7 +92,7 @@ assert(
);
```
Your `remove` method should only remove items that are present in the set.
O método `remove` só deve remover itens presentes no conjunto.
```js
assert.deepEqual(
@ -107,7 +107,7 @@ assert.deepEqual(
);
```
Your `remove` method should remove the given item from the set.
O método `remove` deve remover o item fornecido do conjunto.
```js
assert(
@ -122,7 +122,7 @@ assert(
);
```
Your `Set` class should have a `size` method.
A classe `Set` deve ter o método `size`.
```js
assert(
@ -133,7 +133,7 @@ assert(
);
```
The `size` method should return the number of elements in the collection.
O método `size` deve retornar o número de elementos do conjunto.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8250367417b2b2512c5f
title: Create a Stack Class
title: Criar uma classe de pilha
challengeType: 1
forumTopicId: 301633
dashedName: create-a-stack-class
@ -8,15 +8,15 @@ dashedName: create-a-stack-class
# --description--
In the last section, we talked about what a stack is and how we can use an array to represent a stack. In this section, we will be creating our own stack class. Although you can use arrays to create stacks, sometimes it is best to limit the amount of control we have with our stacks. Apart from the `push` and `pop` method, stacks have other useful methods. Let's add a `peek`, `isEmpty`, and `clear` method to our stack class.
Na última seção, falamos sobre o que é uma pilha (stack, em inglês) e sobre como podemos usar um array para representá-la. Nesta seção, vamos criar a nossa própria classe de pilha. Embora você possa usar arrays para criar pilhas, às vezes é melhor limitar o volume de controle que temos com relação às pilhas. Além dos métodos `push` e `pop`, as pilhas têm outros métodos úteis. Vamos adicionar os métodos `peek`, `isEmpty` e `clear` à nossa classe de pilha.
# --instructions--
Write a `push` method that pushes an element to the top of the stack, a `pop` method that removes and returns the element on the top of the stack, a `peek` method that looks at the top element in the stack, an `isEmpty` method that checks if the stack is empty, and a `clear` method that removes all elements from the stack. Normally stacks don't have this, but we've added a `print` helper method that console logs the collection.
Escreva um método `push`, que insere um elemento no topo da pilha, um método `pop`, que remove e retorna o elemento do topo da pilha, um método `peek`, que examina o elemento que está no topo da pilha, um método `isEmpty`, que verifica se a pilha está vazia, e um método `clear` que remove todos os elementos da pilha. Normalmente pilhas não têm isso, mas nós adicionamos um método auxiliar `print`, que registra no console a coleção.
# --hints--
Your `Stack` class should have a `push` method.
A classe `Stack` deve ter o método `push`.
```js
assert(
@ -27,7 +27,7 @@ assert(
);
```
Your `Stack` class should have a `pop` method.
A classe `Stack` deve ter o método `pop`.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
Your `Stack` class should have a `peek` method.
A classe `Stack` deve ter o método `peek`.
```js
assert(
@ -49,7 +49,7 @@ assert(
);
```
Your `Stack` class should have a `isEmpty` method.
A classe `Stack` deve ter o método `isEmpty`.
```js
assert(
@ -60,7 +60,7 @@ assert(
);
```
Your `Stack` class should have a `clear` method.
A classe `Stack` deve ter o método `clear`.
```js
assert(
@ -71,7 +71,7 @@ assert(
);
```
The `peek` method should return the top element of the stack
O método `peek` deve retornar o elemento do topo da pilha
```js
assert(
@ -84,7 +84,7 @@ assert(
);
```
The `pop` method should remove and return the top element of the stack
O método `pop` deve remover e retornar o elemento do topo da pilha
```js
assert(
@ -97,7 +97,7 @@ assert(
);
```
The `isEmpty` method should return true if a stack does not contain any elements
O método `isEmpty` deve retornar true se uma pilha não tiver nenhum elemento
```js
assert(
@ -108,7 +108,7 @@ assert(
);
```
The `clear` method should remove all element from the stack
O método `clear` deve remover todos os elementos da pilha
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c84
title: Create a Trie Search Tree
title: Criar uma árvore de busca Trie
challengeType: 1
forumTopicId: 301634
dashedName: create-a-trie-search-tree
@ -8,15 +8,15 @@ dashedName: create-a-trie-search-tree
# --description--
Here we will move on from binary search trees and take a look at another type of tree structure called a trie. A trie is an ordered search tree commonly used to hold strings, or more generically associative arrays or dynamic datasets in which the keys are strings. They are very good at storing sets of data when many keys will have overlapping prefixes, for example, all the words in a dictionary. Unlike a binary tree, nodes are not associated with actual values. Instead, the path to a node represents a specific key. For instance, if we wanted to store the string code in a trie, we would have four nodes, one for each letter: c — o — d — e. Following that path through all these nodes will then create code as a string — that path is the key we stored. Then, if we wanted to add the string coding, it would share the first three nodes of code before branching away after the d. In this way, large datasets can be stored very compactly. In addition, search can be very quick because it is effectively limited to the length of the string you are storing. Furthermore, unlike binary trees a node can store any number of child nodes. As you might have guessed from the above example, some metadata is commonly stored at nodes that hold the end of a key so that on later traversals that key can still be retrieved. For instance, if we added codes in our example above we would need some way to know that the e in code represents the end of a key that was previously entered. Otherwise, this information would effectively be lost when we add codes.
Aqui, vamos sair da busca binária e dar uma olhada em outro tipo de estrutura de árvore chamada Trie. Uma Trie é uma árvore de busca ordenada comumente usada para manter strings, ou, mais genericamente, arrays associativos ou conjuntos de dados dinâmicos em que as chaves são strings. Elas são muito boas em armazenar conjuntos de dados quando muitas chaves terão prefixos sobrepostos, como, por exemplo, as palavras de um dicionário. Ao contrário de uma árvore binária, os nós não estão associados com valores reais. Em vez disso, o caminho para um nó representa uma chave específica. Por exemplo, se quiséssemos armazenar a string "code" em uma Trie, teríamos quatro nós, um para cada letra: c — o — d — e. Seguir esse caminho através de todos esses nós, então, criará "code" como uma string — esse caminho é a chave que armazenamos. Então, se quiséssemos adicionar a string "coding", ela compartilharia os três primeiros nós de "code" antes de se ramificar após o d. Desta forma, grandes conjuntos de dados podem ser armazenados de modo bastante compacto. Além disso, a busca pode ser muito rápida porque está efetivamente limitada ao tamanho da string que você está armazenando. Além disso, ao contrário das árvores binárias, um nó pode armazenar qualquer número de nós filhos. Como você já deve ter adivinhado a partir do exemplo acima, alguns metadados são normalmente armazenados em nós que possuem o fim de uma chave para que, ao percorrer os dados posteriormente, a chave ainda possa ser recuperada. Por exemplo, se adicionarmos "codes" no nosso exemplo acima, precisaremos saber de algum modo que o "e" no código representa o final de uma chave que foi inserida anteriormente. Caso contrário, esta informação estaria, de fato, perdida quando acrescentássemos "codes".
# --instructions--
Let's create a trie to store words. It will accept words through an `add` method and store these in a trie data structure. It will also allow us to query if a given string is a word with an `isWord` method, and retrieve all the words entered into the trie with a `print` method. `isWord` should return a boolean value and print should return an array of all these words as string values. In order for us to verify that this data structure is implemented correctly, we've provided a `Node` structure for each node in the tree. Each node will be an object with a `keys` property which is a JavaScript Map object. This will hold the individual letters that are valid keys of each node. We've also created an `end` property on the nodes that can be set to `true` if the node represents the termination of a word.
Vamos criar uma Trie para armazenar palavras. Ele vai aceitar palavras através de um método `add` e armazená-las em uma estrutura de dados de Trie. Ele também permitirá consultar se uma determinada string é uma palavra com um método `isWord`, além de recuperar todas as palavras inseridas na Trie com um método `print`. `isWord` deve retornar um valor booleano e print deve retornar um array com todas essas palavras como valores de string. Para que possamos verificar se esta estrutura de dados foi implementada corretamente, fornecemos uma estrutura `Node` para cada nó da árvore. Cada nó será um objeto com uma propriedade `keys`, que é um objeto Map do JavaScript. Ele guardará as letras individuais, que são as chaves válidas de cada nó. Também criamos uma propriedade `end` nos nós que pode ser definidas como `true` se o nó representar o final de uma palavra.
# --hints--
The Trie should have an add method.
A Trie deve ter um método add.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
The Trie should have a print method.
A Trie deve ter um método print.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The Trie should have an isWord method.
A Trie deve ter um método isWord.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
The print method should return all items added to the trie as strings in an array.
O método print deve retornar todos os itens adicionados à Trie como strings em um array.
```js
assert(
@ -93,7 +93,7 @@ assert(
);
```
The isWord method should return true only for words added to the trie and false for all other words.
O método isWord deve retornar true apenas para palavras adicionadas à Trie e false para todas as outras palavras.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8d
title: Create an ES6 JavaScript Map
title: Criar um mapa da ES6 JavaScript
challengeType: 1
forumTopicId: 301635
dashedName: create-an-es6-javascript-map
@ -8,21 +8,21 @@ dashedName: create-an-es6-javascript-map
# --description--
The new version of JavaScript provides us with a built-in Map object which provides much of the functionality we wrote by hand in the last challenge. This Map object, although similar to regular JavaScript objects, provides some useful functionality that normal objects lack. For example, an ES6 Map tracks the insertion order of items that are added to it. Here is a more complete overview of its methods: `.has(key)` returns true or false based on the presence of a key `.get(key)` returns the value associated with a key `.set(key, value)` sets a new key, value pair `.delete(key)` removes a key, value pair `.clear()` removes all key, value pairs `.entries()` returns an array of all the keys in insertion order `.values()` returns an array of all the values in insertion order
A nova versão do JavaScript nos fornece um objeto Map integrado, com a maior parte da funcionalidade que escrevemos manualmente no último desafio. Este objeto Map, embora semelhante a objetos JavaScript normais, fornece algumas funcionalidade úteis que faltam aos objetos normais. Por exemplo, um Map de ES6 rastreia a ordem de inserção dos itens que são adicionados a ele. Aqui vemos uma visão geral mais completa de seus métodos: `.has(key)` returna true ou false com base na presença de uma chave `.get(key)` retorna o valor associado à uma chave `.set(key, value)` define um novo par chave-valor `.delete(key)` remove um par chave-valor `.clear()` remove todos os pares chave-valor `.entries()` retorna um array de todas as chaves em ordem de inserção `.values()` retorna um array de todos os valores em ordem de inserção
# --instructions--
Define a JavaScript Map object and assign to it a variable called myMap. Add the key, value pair `freeCodeCamp`, `Awesome!` to it.
Defina um objeto Map do JavaScript e atribua a ele uma variável chamada myMap. Adicione o par chave-valor `freeCodeCamp`, `Awesome!` a ele.
# --hints--
The myMap object should exist.
O objeto myMap deve existir.
```js
assert(typeof myMap === 'object');
```
myMap should contain the key value pair `freeCodeCamp`, `Awesome!`.
myMap deve conter o par chave-valor `freeCodeCamp`, `Awesome!`.
```js
assert(myMap.get('freeCodeCamp') === 'Awesome!');

View File

@ -1,6 +1,6 @@
---
id: 587d8254367417b2b2512c70
title: Create and Add to Sets in ES6
title: Criar e adicionar a conjuntos na ES6
challengeType: 1
forumTopicId: 301636
dashedName: create-and-add-to-sets-in-es6
@ -8,34 +8,34 @@ dashedName: create-and-add-to-sets-in-es6
# --description--
Now that you have worked through ES5, you are going to perform something similar in ES6. This will be considerably easier. ES6 contains a built-in data structure `Set` so many of the operations you wrote by hand are now included for you. Let's take a look:
Agora que você trabalhou na ES5 e a conhece, vamos fazer algo semelhante na ES6. Isso será consideravelmente mais fácil. A ES6 contém uma estrutura de dados integrada chamada `Set`. Portanto, muitas das operações que você escreveu à mão estão agora incluídas para você. Vamos dar uma olhada:
To create a new empty set:
Para criar um novo conjunto vazio:
```js
var set = new Set();
```
You can create a set with a value:
Você pode criar um conjunto com um valor:
```js
var set = new Set(1);
```
You can create a set with an array:
Você pode criar um conjunto com um array:
```js
var set = new Set([1, 2, 3]);
```
Once you have created a set, you can add the values you wish using the `add` method:
Depois de criar um conjunto, você pode adicionar os valores que deseja usando o método `add`:
```js
var set = new Set([1, 2, 3]);
set.add([4, 5, 6]);
```
As a reminder, a set is a data structure that cannot contain duplicate values:
É importante lembrar que um conjunto é uma estrutura de dados que não pode conter valores duplicados:
```js
var set = new Set([1, 2, 3, 1, 2, 3]);
@ -44,11 +44,11 @@ var set = new Set([1, 2, 3, 1, 2, 3]);
# --instructions--
For this exercise, return a set with the following values: `1, 2, 3, 'Taco', 'Cat', 'Awesome'`
Para este exercício, retorne um conjunto com os seguintes valores: `1, 2, 3, 'Taco', 'Cat', 'Awesome'`
# --hints--
Your `Set` should only contain the values `1, 2, 3, Taco, Cat, Awesome`.
O `Set` deve conter apenas os valores `1, 2, 3, Taco, Cat, Awesome`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8258367417b2b2512c80
title: Delete a Leaf Node in a Binary Search Tree
title: Excluir um nó de folha em uma árvore binária de busca
challengeType: 1
forumTopicId: 301637
dashedName: delete-a-leaf-node-in-a-binary-search-tree
@ -8,15 +8,15 @@ dashedName: delete-a-leaf-node-in-a-binary-search-tree
# --description--
This is the first of three challenges where we will implement a more difficult operation in binary search trees: deletion. Deletion is difficult because removing nodes breaks links in the tree. These links must be carefully reestablished to ensure the binary tree structure is maintained. For some deletions, this means the tree must be rearranged. In general, you will encounter one of three cases when trying to delete a node: Leaf Node: The target to delete has zero children. One Child: The target to delete only has one child. Two Children: The target to delete has two child nodes. Removing a leaf node is easy, we simply remove it. Deleting a node with one child is also relatively easy, we simply remove it and link its parent to child of the node we deleted. Removing a node with two children is more difficult, however, because this creates two child nodes that need to be reconnected to the parent tree. We'll see how to deal with this case in the third challenge. Additionally, you need to be mindful of some edge cases when handling deletion. What if the tree is empty? What if the node to delete is the root node? What if there are only two elements in the tree? For now, let's handle the first case where we delete a leaf node.
Este é o primeiro de três desafios onde implementaremos uma operação mais difícil em árvores binárias de busca: a exclusão. A exclusão é difícil porque remover nós quebra as ligações da árvore. Estas ligações devem ser cuidadosamente restabelecidas para garantir a manutenção da estrutura da árvore binária. Para algumas exclusões, isto significa que a árvore tem de ser reorganizada. Em geral, você encontrará um dos três casos ao tentar excluir um nó: Nó de folha: o destino que se quer excluir tem zero filhos. Um filho: o destino que se quer excluir tem apenas um filho. Dois filhos: o destino que se quer excluir tem dois nós filhos. Remover um nó de folha é fácil, simplesmente o removemos. Excluir um nó com um filho também é relativamente fácil, simplesmente removemos ele e vinculamos o seu pai ao filho do nó que excluímos. Remover um nó com dois filhos é mais difícil, no entanto, porque cria dois nós filhos que precisam ser reconectados à árvore pai. Vamos ver como lidar com esse caso no terceiro desafio. Além disso, você precisa estar atento a alguns casos extremos ao lidar com a exclusão. E se a árvore estiver vazia? E se o nó a ser excluído é o nó raiz? E se há apenas dois elementos na árvore? Por agora, vamos lidar com o primeiro caso, em que excluímos um nó de folha.
# --instructions--
Create a method on our binary tree called `remove`. We'll build the logic for our deletion operation in here. First, you'll want to create a function within remove that finds the node we are trying to delete in the current tree. If the node is not present in the tree, `remove` should return `null`. Now, if the target node is a leaf node with no children, then the parent reference to it should be set to `null`. This effectively deletes the node from the tree. To do this, you will have to keep track of the parent of the node we are trying to delete as well. It will also be useful to create a way to track the number of children the target node has, as this will determine which case our deletion falls under. We will handle the second and third cases in the next challenges. Good luck!
Crie um método em nossa árvore binária chamado `remove`. Vamos construir a lógica para nossa operação de exclusão aqui. Primeiro, você vai querer criar uma função dentro de remove que encontre o nó que estamos tentando excluir na árvore atual. Se o nó não estiver presente na árvore, `remove` deve retornar `null`. Agora, se o nó de destino for um nó de folha sem filhos, então a referência pai deve ser definida como `null`. Isto efetivamente exclui o nó da árvore. Para fazer isso, você terá que acompanhar o pai do nó que estamos tentando excluir também. Também será útil criar uma maneira de rastrear o número de filhos que o nó alvo tem, pois isso determinará qual o caso da nossa exclusão. Trataremos do segundo e do terceiro caso nos próximos desafios. Boa sorte!
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
The binary search tree should have a method called `remove`.
A árvore binária de busca deve ter um método chamado `remove`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
Trying to remove an element that does not exist should return `null`.
Tentar remover um elemento que não existe deve retornar `null`.
```js
assert(
@ -65,7 +65,7 @@ assert(
);
```
If the root node has no children, deleting it should set the root to `null`.
Se o nó raiz não tem filhos, a exclusão deve definir a raiz como `null`.
```js
assert(
@ -86,7 +86,7 @@ assert(
);
```
The `remove` method should remove leaf nodes from the tree.
O método `remove` deve remover os nós de folha da árvore.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8258367417b2b2512c81
title: Delete a Node with One Child in a Binary Search Tree
title: Exclua um nó com um filho em uma árvore binária de busca
challengeType: 1
forumTopicId: 301638
dashedName: delete-a-node-with-one-child-in-a-binary-search-tree
@ -8,15 +8,15 @@ dashedName: delete-a-node-with-one-child-in-a-binary-search-tree
# --description--
Now that we can delete leaf nodes let's move on to the second case: deleting a node with one child. For this case, say we have a tree with the following nodes 1 — 2 — 3 where 1 is the root. To delete 2, we simply need to make the right reference in 1 point to 3. More generally to delete a node with only one child, we make that node's parent reference the next node in the tree.
Agora que podemos excluir nós de folhas vamos passar para o segundo caso: excluir um nó com um filho. Para este caso, vamos supor uma árvore com os seguintes nós: 1 — 2 — 3, onde 1 é a raiz. Para excluir 2, temos simplesmente de fazer a referência da direita em 1 apontar para 3. De modo mais geral, para excluir um nó com apenas um filho, fazemos com que o pai desse nó referencie o próximo nó da árvore.
# --instructions--
We've provided some code in our `remove` method that accomplishes the tasks from the last challenge. We find the target to delete and its parent and define the number of children the target node has. Let's add the next case here for target nodes with only one child. Here, we'll have to determine if the single child is a left or right branch in the tree and then set the correct reference in the parent to point to this node. In addition, let's account for the case where the target is the root node (this means the parent node will be `null`). Feel free to replace all the starter code with your own as long as it passes the tests.
Fornecemos parte do código em nosso método `remove` que realiza as tarefas do último desafio. Encontramos o destino a ser excluído e seu pai e definimos o número de filhos que o nó de destino possui. Vamos adicionar o próximo caso aqui para os nós de destino com apenas um filho. Aqui, teremos que determinar se o filho único é um ramo à esquerda ou à direita na árvore e, então, definir a referência correta no pai para que aponte para este nó. Além disso, vamos levar em conta o caso em que o destino é o nó raiz (o que significa que o nó pai será `null`). Sinta-se à vontade para substituir todo o código inicial por seu próprio código, contanto que ele passe nos testes.
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
The binary search tree should have a method called `remove`.
A árvore binária de busca deve ter um método chamado `remove`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
Trying to remove an element that does not exist should return `null`.
Tentar remover um elemento que não existe deve retornar `null`.
```js
assert(
@ -65,7 +65,7 @@ assert(
);
```
If the root node has no children, deleting it should set the root to `null`.
Se o nó raiz não tem filhos, a exclusão deve definir a raiz como `null`.
```js
assert(
@ -86,7 +86,7 @@ assert(
);
```
The `remove` method should remove leaf nodes from the tree.
O método `remove` deve remover os nós de folha da árvore.
```js
assert(
@ -114,7 +114,7 @@ assert(
);
```
The `remove` method should remove nodes with one child.
O método `remove` deve remover os nós com um filho.
```js
assert(
@ -140,7 +140,7 @@ assert(
);
```
Removing the root in a tree with two nodes should set the second to be the root.
Remover a raiz de uma árvore com dois nós deve definir o segundo nó como a raiz.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8258367417b2b2512c82
title: Delete a Node with Two Children in a Binary Search Tree
title: Exclua um nó com dois filhos em uma árvore binária de busca
challengeType: 1
forumTopicId: 301639
dashedName: delete-a-node-with-two-children-in-a-binary-search-tree
@ -8,15 +8,15 @@ dashedName: delete-a-node-with-two-children-in-a-binary-search-tree
# --description--
Removing nodes that have two children is the hardest case to implement. Removing a node like this produces two subtrees that are no longer connected to the original tree structure. How can we reconnect them? One method is to find the smallest value in the right subtree of the target node and replace the target node with this value. Selecting the replacement in this way ensures that it is greater than every node in the left subtree it becomes the new parent of but also less than every node in the right subtree it becomes the new parent of. Once this replacement is made the replacement node must be removed from the right subtree. Even this operation is tricky because the replacement may be a leaf or it may itself be the parent of a right subtree. If it is a leaf we must remove its parent's reference to it. Otherwise, it must be the right child of the target. In this case, we must replace the target value with the replacement value and make the target reference the replacement's right child.
Remover nós que têm dois filhos é o caso mais difícil de implementar. Remover um nó como este produz duas subárvores que não estão mais conectadas à estrutura original da árvore. Como podemos reconectá-las? Um método é encontrar o menor valor na subárvore à direita do nó de destino e substituir o nó de destino por este valor. Selecionar a substituição desta forma garante que ela é maior do que cada nó na subárvore à esquerda da qual ela se torna o novo pai, mas também menor do que qualquer nó na subárvore à direita da qual ela se torna o novo pai. Uma vez que esta substituição é feita, o nó de substituição deve ser removido da subárvore à direita. Até mesmo esta operação é complicada, porque a substituição pode ser uma folha ou pode ser ela mesma o pai de uma subárvore à direita. Se se trata de uma folha, temos de retirar a referência de seu pai a ela. Caso contrário, ela deverá ser o filho à direita do destino. Neste caso, temos de substituir o valor de destino pelo valor de substituição e fazer com que o destino referencie o filho à direita.
# --instructions--
Let's finish our `remove` method by handling the third case. We've provided some code again for the first two cases. Add some code now to handle target nodes with two children. Any edge cases to be aware of? What if the tree has only three nodes? Once you are finished this will complete our deletion operation for binary search trees. Nice job, this is a pretty hard problem!
Vamos terminar nosso método `remove` tratando do terceiro caso. Já fornecemos um pouco de código novamente para os dois primeiros casos. Adicione um código agora para lidar com nós de destino com dois filhos. Há algum caso extremo em que devemos prestar atenção? E se a árvore tiver apenas três nós? Depois de ter terminado, isso vai completar nossa operação de exclusão para as árvores binárias de busca. Bom trabalho! Esse é um problema muito difícil!
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
The binary search tree should have a method called `remove`.
A árvore binária de busca deve ter um método chamado `remove`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
Trying to remove an element that does not exist should return `null`.
Tentar remover um elemento que não existe deve retornar `null`.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
If the root node has no children, deleting it should set the root to `null`.
Se o nó raiz não tem filhos, a exclusão deve definir a raiz como `null`.
```js
assert(
@ -80,7 +80,7 @@ assert(
);
```
The `remove` method should remove leaf nodes from the tree.
O método `remove` deve remover os nós de folha da árvore.
```js
assert(
@ -107,7 +107,7 @@ assert(
);
```
The `remove` method should remove nodes with one child.
O método `remove` deve remover os nós com um filho.
```js
assert(
@ -133,7 +133,7 @@ assert(
);
```
Removing the root in a tree with two nodes should set the second to be the root.
Remover a raiz de uma árvore com dois nós deve definir o segundo nó como a raiz.
```js
assert(
@ -155,7 +155,7 @@ assert(
);
```
The `remove` method should remove nodes with two children while maintaining the binary search tree structure.
O método `remove` deve remover nós com dois filhos, mantendo a estrutura da árvore binária de busca.
```js
assert(
@ -212,7 +212,7 @@ assert(
);
```
The root should be removable on a tree of three nodes.
A raiz deve ser removível em uma árvore de três nós.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825d367417b2b2512c96
title: Depth-First Search
title: Busca em profundidade
challengeType: 1
forumTopicId: 301640
dashedName: depth-first-search
@ -8,31 +8,31 @@ dashedName: depth-first-search
# --description--
Similar to <dfn>breadth-first search</dfn>, here we will learn about another graph traversal algorithm called <dfn>depth-first search</dfn>.
Do mesmo modo que na <dfn>busca em largura</dfn>, aqui aprenderemos sobre outro algoritmo de travessia de grafos chamado <dfn>busca em profundidade</dfn>.
Whereas the breadth-first search searches incremental edge lengths away from the source node, <dfn>depth-first search</dfn> first goes down a path of edges as far as it can.
Enquanto a busca em largura busca pela distância das arestas do nó de origem de modo incremental, a <dfn>busca em profundidade</dfn> desce todo o caminho das arestas o mais distante que ela puder.
Once it reaches one end of a path, the search will backtrack to the last node with an un-visited edge path and continue searching.
Ao chegar ao fim de um caminho, a busca voltará para o último nó com um caminho de aresta não visitado e continuará a procurar.
The animation below shows how the algorithm works. The algorithm starts with the top node and visits the nodes in the numbered order.
A animação abaixo mostra como o algoritmo funciona. O algoritmo começa com o nó superior e visita os nós em ordem numerada.
<img class='img-responsive' src='https://camo.githubusercontent.com/aaad9e39961daf34d967c616edeb50abf3bf1235/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37662f44657074682d46697273742d5365617263682e676966' />
Notice how, unlike breadth-first search, every time a node is visited, it doesn't visit all of its neighbors. Instead, it first visits one of its neighbors and continues down that path until there are no more nodes to be visited on that path.
Observe como, diferente da busca em largura, cada vez que um nó é visitado, ele não visita todos os seus vizinhos. Em vez disso, visita pela primeira vez um dos seus vizinhos e continua por esse caminho até que não haja mais nós a visitar nele.
To implement this algorithm, you'll want to use a stack. A stack is an array where the last element added is the first to be removed. This is also known as a <dfn>Last-In-First-Out</dfn> data structure. A stack is helpful in depth-first search algorithms because, as we add neighbors to the stack, we want to visit the most recently added neighbors first and remove them from the stack.
Para implementar este algoritmo, você vai querer usar uma pilha. Uma pilha é um array onde o último elemento adicionado é o primeiro a ser removido. Isto também é conhecido como uma estrutura de dados <dfn>Last-In-First-Out</dfn> (ou seja, o último a entrar é o primeiro a sair). Uma pilha é útil em algoritmos de busca em profundidade porque, conforme adicionamos vizinhos à pilha, queremos visitar primeiro os vizinhos que foram adicionados mais recentemente e removê-los da pilha.
A simple output of this algorithm is a list of nodes which are reachable from a given node. Therefore, you'll also want to keep track of the nodes you visit.
Uma saída simples deste algoritmo é uma lista de nós que são acessíveis a partir de um determinado nó. Portanto, você também vai querer acompanhar os nós que visita.
# --instructions--
Write a function `dfs()` that takes an undirected, adjacency matrix `graph` and a node label `root` as parameters. The node label will just be the numeric value of the node between `0` and `n - 1`, where `n` is the total number of nodes in the graph.
Escreva uma função `dfs()` que recebe um `graph` de matriz de adjacência e uma etiqueta de nó `root` como parâmetros. A etiqueta do nó será apenas o valor numérico do nó entre `0` e `n - 1`, onde `n` é o número total de nós no grafo.
Your function should output an array of all nodes reachable from `root`.
A função deve gerar um array de todos os nós acessíveis a partir de `root`.
# --hints--
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` with a start node of `1` should return an array with `0`, `1`, `2`, and `3`.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` com o nó inicial `1` deve retornar um array com `0`, `1`, `2` e `3`.
```js
assert.sameMembers(
@ -49,7 +49,7 @@ assert.sameMembers(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` with a start node of `1` should return an array with four elements.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` com o nó inicial `1` deve retornar um array com quatro elementos.
```js
assert(
@ -65,7 +65,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` with a start node of `3` should return an array with `3`.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` com o nó inicial `3` deve retornar um array com `3`.
```js
assert.sameMembers(
@ -82,7 +82,7 @@ assert.sameMembers(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` with a start node of `3` should return an array with one element.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` com o nó inicial `3` deve retornar um array com um elemento.
```js
assert(
@ -98,7 +98,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `3` should return an array with `2` and `3`.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` com o nó inicial `3` deve retornar um array com `2` e `3`.
```js
assert.sameMembers(
@ -115,7 +115,7 @@ assert.sameMembers(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `3` should return an array with two elements.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` com o nó inicial `3` deve retornar um array com dois elementos.
```js
assert(
@ -131,7 +131,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `0` should return an array with `0` and `1`.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` com o nó inicial `0` deve retornar um array com `0` e `1`.
```js
assert.sameMembers(
@ -148,7 +148,7 @@ assert.sameMembers(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `0` should return an array with two elements.
O grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` com o nó inicial `0` deve retornar um array com dois elementos.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7d
title: Find the Minimum and Maximum Height of a Binary Search Tree
title: Encontrar a altura mínima e a máxima de uma árvore binária de busca
challengeType: 1
forumTopicId: 301641
dashedName: find-the-minimum-and-maximum-height-of-a-binary-search-tree
@ -8,19 +8,19 @@ dashedName: find-the-minimum-and-maximum-height-of-a-binary-search-tree
# --description--
In the last challenge we described a scenario in which a tree could become unbalanced. To understand the concept of balance, let's take a look at another tree property: height. Height in a tree represents the distance from the root node to any given leaf node. Different paths in a highly branched tree structure may have different heights, but for a given tree there will be a minimum and maximum height. If the tree is balanced, these values will differ at most by one. This means that in a balanced tree, all the leaf nodes exist within the same level, or if they are not within the same level they are at most one level apart.
No último desafio, descrevemos um cenário em que uma árvore poderia se tornar desbalanceada. Para entender o conceito de balanço, vamos dar uma olhada em outra propriedade da árvore: altura. A altura de uma árvore representa a distância do nó raiz para qualquer nó de folha dado. Caminhos diferentes em uma estrutura de árvore altamente ramificada podem ter alturas diferentes, mas, para uma determinada árvore, haverá uma altura mínima e máxima. Se a árvore estiver balanceada, estes valores terão uma diferença de, no máximo, um. Isto significa que, em uma árvore equilibrada, todos os nós de folhas existem no mesmo nível. Se não se situarem no mesmo nível, estarão, no máximo, a um nível de distância.
The property of balance is important for trees because it is what determines the efficiency of tree operations. As we explained in the last challenge, we face worst case time complexity for heavily unbalanced trees. Self-balancing trees are commonly used to account for this issue in trees with dynamic data sets. Common examples of these include AVL trees, red-black trees, and B-trees. These trees all contain additional internal logic which re-balance the tree when insertions or deletions create a state of imbalance.
A propriedade de balanço é importante para as árvores, pois é isso que determina a eficiência das operações em uma delas. Como explicamos no último desafio, enfrentamos a pior das hipóteses de complexidade para árvores muito desbalanceadas. As árvores de autobalanceáveis são habitualmente utilizadas para dar conta desta questão nas árvores com conjuntos de dados dinâmicos. Exemplos comuns destas árvores incluem árvores AVL, árvores red-black e árvores B (B-trees). Todas estas árvores contêm uma lógica interna adicional que rebalanceia a árvore quando inserções ou exclusões criam um estado de desbalanceamento.
**Note:** A similar property to height is depth, which refers to how far a given node is from the root node.
**Observação:** uma propriedade similar à altura é a profundidade, que se refere à distância de um determinado nó do nó raiz.
# --instructions--
Write two methods for our binary tree: `findMinHeight` and `findMaxHeight`. These methods should return an integer value for the minimum and maximum height within a given binary tree, respectively. If the node is empty let's assign it a height of `-1` (that's the base case). Finally, add a third method `isBalanced` which returns `true` or `false` depending on whether the tree is balanced or not. You can use the first two methods you just wrote to determine this.
Escreva dois métodos para a nossa árvore binária: `findMinHeight` e `findMaxHeight`. Esses métodos devem retornar um valor inteiro para as alturas mínima e máxima dentro de uma determinada árvore binária, respectivamente. Se o nó estiver vazio, vamos atribuir uma altura de `-1` (esse é o caso base). Por fim, vamos adicionar um terceiro método `isBalanced`, que retorna `true` ou `false`, dependendo de a árvore estar balanceada ou não. Você pode usar os dois primeiros métodos que acabou de escrever para determinar isso.
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -34,7 +34,7 @@ assert(
);
```
The binary search tree should have a method called `findMinHeight`.
A árvore binária de busca deve ter um método chamado `findMinHeight`.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
The binary search tree should have a method called `findMaxHeight`.
A árvore binária de busca deve ter um método chamado `findMaxHeight`.
```js
assert(
@ -66,7 +66,7 @@ assert(
);
```
The binary search tree should have a method called `isBalanced`.
A árvore binária de busca deve ter um método chamado `isBalanced`.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
The `findMinHeight` method should return the minimum height of the tree.
O método `findMinHeight` deve retornar a altura mínima da árvore.
```js
assert(
@ -109,7 +109,7 @@ assert(
);
```
The `findMaxHeight` method should return the maximum height of the tree.
O método `findMaxHeight` deve retornar a altura máxima da árvore.
```js
assert(
@ -136,7 +136,7 @@ assert(
);
```
An empty tree should return a height of `-1`.
Uma árvore vazia deve retornar a altura de `-1`.
```js
assert(
@ -155,7 +155,7 @@ assert(
);
```
The `isBalanced` method should return `false` if the tree is an unbalanced binary search tree.
O método `isBalanced` deve retornar `false` se a árvore é uma árvore binária de busca desbalanceada.
```js
assert(
@ -182,7 +182,7 @@ assert(
);
```
The `isBalanced` method should return `true` if the tree is a balanced binary search tree.
O método `isBalanced` deve retornar `true` se a árvore é uma árvore binária de busca balanceada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8256367417b2b2512c7a
title: Find the Minimum and Maximum Value in a Binary Search Tree
title: Encontrar o valor mínimo e o máximo de uma árvore binária de busca
challengeType: 1
forumTopicId: 301642
dashedName: find-the-minimum-and-maximum-value-in-a-binary-search-tree
@ -8,11 +8,11 @@ dashedName: find-the-minimum-and-maximum-value-in-a-binary-search-tree
# --description--
In this challenge you will define two methods, `findMin` and `findMax`. These methods should return the minimum and maximum value held in the binary search tree (don't worry about adding values to the tree for now, we have added some in the background). If you get stuck, reflect on the invariant that must be true for binary search trees: each left subtree is less than or equal to its parent and each right subtree is greater than or equal to its parent. Let's also say that our tree can only store integer values. If the tree is empty, either method should return `null`.
Neste desafio, você vai definir dois métodos, `findMin` e `findMax`. Estes métodos devem retornar o valor mínimo e o máximo mantidos na árvore binária de busca (não se preocupe em adicionar valores à árvore por enquanto, porque já acrescentamos alguns em segundo plano). Se você ficar preso, pense sobre aquilo que deve ser verdadeiro e imutável em árvores binárias de busca: cada subárvore à esquerda é menor ou igual a seu pai e cada subárvore à direita é maior ou igual a seu pai. Digamos também que nossa árvore só pode armazenar valores inteiros. Se a árvore estiver vazia, qualquer método deve retornar `null`.
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -26,7 +26,7 @@ assert(
);
```
The binary search tree should have a method called `findMin`.
A árvore binária de busca deve ter um método chamado `findMin`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The binary search tree should have a method called `findMax`.
A árvore binária de busca deve ter um método chamado `findMax`.
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
The `findMin` method should return the minimum value in the binary search tree.
O método `findMin` deve retornar o valor mínimo da árvore binária de busca.
```js
assert(
@ -85,7 +85,7 @@ assert(
);
```
The `findMax` method should return the maximum value in the binary search tree.
O método `findMax` deve retornar o valor máximo da árvore binária de busca.
```js
assert(
@ -112,7 +112,7 @@ assert(
);
```
The `findMin` and `findMax` methods should return `null` for an empty tree.
Os métodos `findMin` e `findMax` devem retornar `null` para uma árvore vazia.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8c
title: Implement Heap Sort with a Min Heap
title: Implementar a ordenação de heap com um Min Heap
challengeType: 1
forumTopicId: 301643
dashedName: implement-heap-sort-with-a-min-heap
@ -8,17 +8,17 @@ dashedName: implement-heap-sort-with-a-min-heap
# --description--
Now that we can add and remove elements let's see some of the applications heaps can be used for. Heaps are commonly used to implement priority queues because they always store an item of greatest or least value in first position. In addition, they are used to implement a sorting algorithm called heap sort. We'll see how to do this here. Heap sort uses a min heap, the reverse of a max heap. A min heap always stores the element of least value in the root position.
Agora que podemos adicionar e remover elementos, vamos ver algumas pilhas (heaps) de aplicações que podem ser usadas. As heaps são comumente usadas para implementar filas de prioridade porque armazenam sempre um item com maior ou menor valor na primeira posição. Além disso, elas são usadas para implementar um algoritmo de ordenação chamado Heap Sort. Vamos ver como fazer isso aqui. O Heap Sort usa um Min Heap, o inverso de um Max Heap. Um Min Heap sempre armazena o elemento de menor valor na posição raiz.
Heap sort works by taking an unsorted array, adding each item in the array into a min heap, and then extracting every item out of the min heap into a new array. The min heap structure ensures that the new array will contain the original items in least to greatest order. This is one of the most efficient sorting algorithms with average and worst case performance of O(nlog(n)).
O Heap Sort funciona pegando um array não ordenado, adicionando cada item do array a uma heap mínima, e, em seguida, extraindo cada item da heap mínima para um novo array. A estrutura de heap mínima garante que o novo array conterá os itens originais na ordem do menor para o maior. Este é um dos algoritmos de ordenação mais eficientes com performance de O(nlog(n)) na média e no pior caso.
# --instructions--
Let's implement heap sort with a min heap. Feel free to adapt your max heap code here. Create an object `MinHeap` with `insert`, `remove`, and `sort` methods. The `sort` method should return an array of all the elements in the min heap sorted from smallest to largest.
Vamos implementar o Heap Sort com um Min Heap. Sinta-se à vontade para adaptar seu código máximo aqui. Crie um objeto `MinHeap` com os métodos `insert`, `remove` e `sort`. O método `sort` deve retornar um array de todos os elementos do Min Heap ordenados do menor para o maior.
# --hints--
The MinHeap data structure should exist.
A estrutura de dados MinHeap deve existir.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
MinHeap should have a method called insert.
MinHeap deve ter um método chamado insert.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
MinHeap should have a method called remove.
MinHeap deve ter um método chamado remove.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
MinHeap should have a method called sort.
MinHeap deve ter um método chamado sort.
```js
assert(
@ -80,7 +80,7 @@ assert(
);
```
The sort method should return an array containing all items added to the min heap in sorted order.
O método sort deve retornar um array que contenha todos os itens adicionados ao Min Heap ordenados.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8256367417b2b2512c79
title: Incidence Matrix
title: Matriz de incidência
challengeType: 1
forumTopicId: 301644
dashedName: incidence-matrix
@ -8,21 +8,21 @@ dashedName: incidence-matrix
# --description--
Yet another way to represent a graph is to put it in an <dfn>incidence matrix.</dfn>
Outra forma de representar um grafo é colocá-lo em uma <dfn>matriz de incidência</dfn>
An <dfn>incidence matrix</dfn> is a two-dimensional (2D) array. Generally speaking, an incidence matrix relates two different classes of objects between its two dimensions. This kind of matrix is similar to an adjacency matrix. However, the rows and columns mean something else here.
Uma <dfn>matriz de incidência</dfn> é um array bidimensional (2D). Em geral, uma matriz de incidência relaciona duas classes diferentes de objetos entre suas duas dimensões. Esse tipo de matriz é semelhante a uma matriz de adjacência. No entanto, as linhas e as colunas significam algo mais neste caso.
In graphs, we have edges and nodes. These will be our "two different classes of objects". This matrix will have the rows be the nodes and columns be the edges. This means that we can have an uneven number of rows and columns.
Nos grafos, temos arestas e nós. Estas serão as nossas "duas classes diferentes de objetos". Esta matriz terá as linhas representando os nós e as colunas representando as arestas. Isto significa que podemos ter um número desigual de linhas e colunas.
Each column will represent a unique edge. Also, each edge connects two nodes. To show that there is an edge between two nodes, you will put a 1 in the two rows of a particular column. Below is a 3 node graph with one edge between node 1 and node 3.
Cada coluna representará uma única aresta. Além disso, cada aresta conectará dois nós. Para mostrar que há uma aresta entre dois nós, você colocará um 1 nas duas linhas de uma coluna específica. Abaixo vemos um grafo de 3 nós com uma aresta entre o nó 1 e o nó 3.
<blockquote> 1<br> ---<br>1 | 1<br>2 | 0<br>3 | 1</blockquote>
Here is an example of an `incidence matrix` with 4 edges and 4 nodes. Remember, the columns are the edges and rows are the nodes themselves.
Aqui está um exemplo de uma `incidence matrix` (matriz de incidência) com 4 arestas e 4 nós. Lembre-se, as colunas são as arestas e as linhas são os próprios nós.
<blockquote> 1 2 3 4<br> --------<br>1 | 0 1 1 1<br>2 | 1 1 0 0<br>3 | 1 0 0 1<br>4 | 0 0 1 0</blockquote>
Below is a JavaScript implementation of the same thing.
Abaixo, vemos uma implementação em JavaScript da mesma coisa.
```js
var incMat = [
@ -33,7 +33,7 @@ var incMat = [
];
```
To make a directed graph, use `-1` for an edge leaving a particular node and `1` for an edge entering a node.
Para criar um grafo direcionado, use `-1` para uma aresta que saia de um nó específico e `1` para uma aresta que chegue a um nó.
```js
var incMatDirected = [
@ -44,17 +44,17 @@ var incMatDirected = [
];
```
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (`0` or `1`). You can have different weights depending on your application. A different weight is represented as numbers greater than 1.
Grafos também podem ter <dfn>pesos</dfn> nas arestas. Até agora, tivemos arestas <dfn>sem peso</dfn>, onde apenas a presença e a falta de aresta é binária (`0` ou `1`). Você pode ter pesos diferentes, dependendo da aplicação. Um peso diferente é representado como números maiores que 1.
# --instructions--
Create an incidence matrix of an undirected graph with five nodes and four edges. This matrix should be in a multi-dimensional array.
Crie uma matriz de incidência de um grafo não direcionado com cinco nós e quatro arestas. Esta matriz deve estar em um array multidimensional.
These five nodes have the following relationships. The first edge is between the first and second node. The second edge is between the second and third node. The third edge is between the third and fifth node. The fourth edge is between the fourth and second node. All edge weights are one and the edge order matters.
Estes cinco nós têm as seguintes relações. A primeira aresta está entre o primeiro e o segundo nó. A segunda aresta está entre o segundo e o terceiro nó. A terceira aresta entre o terceiro e o quinto nó. A quarta aresta está entre o quarto e o segundo nó. Todos os pesos das arestas são um e a ordem das arestas importa.
# --hints--
`incMatUndirected` should only contain five nodes.
`incMatUndirected` deve conter apenas cinco nós.
```js
assert(
@ -69,25 +69,25 @@ assert(
);
```
There should be a first edge between the first and second node.
Deve haver uma primeira aresta entre o primeiro e o segundo nó.
```js
assert(incMatUndirected[0][0] === 1 && incMatUndirected[1][0] === 1);
```
There should be a second edge between the second and third node.
Deve haver uma segunda aresta entre o segundo e o terceiro nó.
```js
assert(incMatUndirected[1][1] === 1 && incMatUndirected[2][1] === 1);
```
There should be a third edge between the third and fifth node.
Deve haver uma terceira aresta entre o terceiro e o quinto nó.
```js
assert(incMatUndirected[2][2] === 1 && incMatUndirected[4][2] === 1);
```
There should be a fourth edge between the second and fourth node.
Deve haver uma quarta aresta entre o segundo e o quarto nó.
```js
assert(incMatUndirected[1][3] === 1 && incMatUndirected[3][3] === 1);

View File

@ -1,6 +1,6 @@
---
id: 587d825a367417b2b2512c8a
title: Insert an Element into a Max Heap
title: Inserir um elemento em um Max Heap
challengeType: 1
forumTopicId: 301703
dashedName: insert-an-element-into-a-max-heap
@ -8,47 +8,47 @@ dashedName: insert-an-element-into-a-max-heap
# --description--
Now we will move on to another tree data structure, the binary heap. A binary heap is a partially ordered binary tree which satisfies the heap property. The heap property specifies a relationship between parent and child nodes. You may have a max heap, in which all parent nodes are greater than or equal to their child nodes, or a min heap, in which the reverse is true. Binary heaps are also complete binary trees. This means that all levels of the tree are fully filled and if the last level is partially filled it is filled from left to right.
Agora, vamos passar para outra estrutura de dados em árvore, o heap binário. Um heap (pilha) binário é uma árvore binária parcialmente ordenada que satisfaz a propriedade heap. A propriedade heap especifica uma relação entre o nó pai e os nós filhos. Você pode ter um Max Heap, no qual todos os nós pai são maiores ou iguais aos seus nós filhos, ou um Min Heap, em que o inverso é verdadeiro. Heaps binários também são árvores binárias completas. Isso significa que todos os níveis da árvore estão totalmente preenchidos e, se o último nível estiver parcialmente preenchido, ele é preenchido da esquerda para a direita.
While binary heaps may be implemented as tree structures with nodes that contain left and right references, the partial ordering according to the heap property allows us to represent the heap with an array. The parent-children relationship is what we're interested in and with simple arithmetic we can compute the children of any parent and the parent of any child node.
Enquanto os heaps binários podem ser implementados como estruturas de árvore, com nós que contêm referências à esquerda ou à direita, a ordenação parcial de acordo com a propriedade heap nos permite representar o heap como um array. A relação pai-filho é o que nos interessa e, com aritmética simples, podemos calcular os filhos de qualquer pai ou o pai de qualquer nó filho.
For instance, consider this array representation of a binary min heap:
Por exemplo, considere esta representação de array de um Min Heap binário:
```js
[ 6, 22, 30, 37, 63, 48, 42, 76 ]
```
The root node is the first element, `6`. Its children are `22` and `30`. If we look at the relationship between the array indices of these values, for index `i` the children are `2 * i + 1` and `2 * i + 2`. Similarly, the element at index `0` is the parent of these two children at indices `1` and `2`. More generally, we can find the parent of a node at any index with the following: `Math.floor((i - 1) / 2)`. These patterns will hold true as the binary tree grows to any size. Finally, we can make a slight adjustment to make this arithmetic even easier by skipping the first element in the array. Doing this creates the following relationship for any element at a given index `i`:
O nó raiz é o primeiro elemento, `6`. Seus filhos são `22` e `30`. Se olharmos para a relação entre os índices do array desses valores, para o índice `i`, os filhos são `2 * i + 1` e `2 * i + 2`. Da mesma forma, o elemento no índice `0` é o pai desses dois filhos nos índices `1` e `2`. De forma mais geral, podemos encontrar o pai de um nó em qualquer índice com o seguinte: `Math.floor((i - 1) / 2)`. Esses padrões se manterão fiéis à medida que a árvore binária cresce até qualquer tamanho. Por fim, podemos fazer um ligeiro ajuste para tornar esta aritmética ainda mais fácil, ignorando o primeiro elemento do array. Fazer isso cria a seguinte relação para qualquer elemento em um determinado índice `i`:
Example array representation:
Exemplo de representação de array:
```js
[ null, 6, 22, 30, 37, 63, 48, 42, 76 ]
```
An element's left child: `i * 2`
Um elemento é o filho da esquerda: `i * 2`
An element's right child: `i * 2 + 1`
Um elemento é o filho da direita: `i * 2 + 1`
An element's parent: `Math.floor(i / 2)`
Um elemento é o pai: `Math.floor(i / 2)`
Once you wrap your head around the math, using an array representation is very useful because node locations can be quickly determined with this arithmetic and memory usage is diminished because you don't need to maintain references to child nodes.
Assim que você compreender a matemática, usar uma representação de array passa a ser muito útil, porque os locais dos nós podem ser determinados rapidamente com esta aritmética e o uso de memória é diminuído, porque você não precisa manter referências aos nós filhos.
# --instructions--
Instructions: Here we will create a max heap. Start by just creating an `insert` method which adds elements to our heap. During insertion, it is important to always maintain the heap property. For a max heap this means the root element should always have the greatest value in the tree and all parent nodes should be greater than their children. For an array implementation of a heap, this is typically accomplished in three steps:
Instruções: Aqui vamos criar um Max Heap. Comece criando um método `insert` que adiciona elementos ao nosso heap. Durante a inserção, é importante manter sempre a propriedade heap. Para um heap máximo, isso significa que o elemento raiz deve sempre ter o maior valor na árvore e todos os nós pai devem ser maiores que seus filhos. Para uma implementação de um array de heap, isso normalmente é feito em três etapas:
<ol>
<li>Add the new element to the end of the array.</li>
<li>If the element is larger than its parent, switch them.</li>
<li>Continue switching until the new element is either smaller than its parent or you reach the root of the tree.</li>
<li>Adicione o novo elemento ao final do array.</li>
<li>Se o elemento for maior do que o seu pai, troque-o.</li>
<li>Continue alterando até que o novo elemento seja menor que o seu pai ou até que você alcance a raiz da árvore.</li>
</ol>
Finally, add a `print` method which returns an array of all the items that have been added to the heap.
Por fim, adicione um método `print`, que retorne um array de todos os itens que foram adicionados ao heap.
# --hints--
The MaxHeap data structure should exist.
A estrutura de dados MaxHeap deve existir.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
MaxHeap should have a method called insert.
MaxHeap deve ter um método chamado insert.
```js
assert(
@ -78,7 +78,7 @@ assert(
);
```
MaxHeap should have a method called print.
MaxHeap deve ter um método chamado print.
```js
assert(
@ -94,7 +94,7 @@ assert(
);
```
The insert method should add elements according to the max heap property.
O método insert deve adicionar elementos de acordo com a propriedade do Max Heap.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c83
title: Invert a Binary Tree
title: Inverter uma árvore binária
challengeType: 1
forumTopicId: 301704
dashedName: invert-a-binary-tree
@ -8,11 +8,11 @@ dashedName: invert-a-binary-tree
# --description--
Here will we create a function to invert a binary tree. Given a binary tree, we want to produce a new tree that is equivalently the mirror image of this tree. Running an inorder traversal on an inverted tree will explore the nodes in reverse order when compared to the inorder traversal of the original tree. Write a method to do this called `invert` on our binary tree. Calling this method should invert the current tree structure. Ideally, we would like to do this in-place in linear time. That is, we only visit each node once and we modify the existing tree structure as we go, without using any additional memory. Good luck!
Aqui criaremos uma função para inverter uma árvore binária. Dada uma árvore binária, queremos produzir uma nova árvore que é equivalentemente à imagem de espelho desta árvore. Executar uma travessia em ordem em uma árvore invertida vai explorar os nós em ordem inversa quando comparado com a travessia em ordem da árvore original. Escreva um método para fazer isso chamado `invert` em nossa árvore binária. Chamar este método deve inverter a estrutura atual da árvore. O ideal é que façamos isso em tempo linear. Ou seja, só visitamos cada nó uma vez e modificamos a estrutura em árvore existente conforme fazemos a travessia, sem usar qualquer memória adicional. Boa sorte!
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -26,7 +26,7 @@ assert(
);
```
The binary search tree should have a method called `invert`.
A árvore binária de busca deve ter um método chamado `invert`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The `invert` method should correctly invert the tree structure.
O método `invert` deve inverter corretamente a estrutura da árvore.
```js
assert(
@ -70,7 +70,7 @@ assert(
);
```
Inverting an empty tree should return `null`.
Inverter uma árvore vazia deve retornar `null`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8250367417b2b2512c5e
title: Learn how a Stack Works
title: Aprender como funciona uma pilha
challengeType: 1
forumTopicId: 301705
dashedName: learn-how-a-stack-works
@ -8,43 +8,43 @@ dashedName: learn-how-a-stack-works
# --description--
You are probably familiar with stack of books on your table. You have likely used the undo feature of a text editor. You are also probably used to hitting the back button on your phone to go back to the previous view in your app.
Você provavelmente está familiarizado com uma pilha de livros sobre sua mesa. Você provavelmente usou o recurso de desfazer de um editor de texto. Você também já deve estar acostumado a apertar o botão voltar no seu telefone para voltar ao modo de exibição anterior no seu aplicativo.
You know what they all have in common? They all store the data in a way so that you can traverse backwards.
Sabem o que eles têm em comum? Todos eles armazenam os dados de uma maneira para que você possa percorrer os dados no sentido inverso.
The topmost book in the stack was the one that was put there last. If you remove that book from your stack's top, you would expose the book that was put there before the last book and so on.
O livro de cima da pilha foi o que foi colocado lá por último. Se você remover esse livro da parte superior da pilha, você deixaria exposto o livro que foi colocado lá antes do último livro e assim por diante.
If you think about it, in all the above examples, you are getting <dfn>Last-In-First-Out</dfn> type of service. We will try to mimic this with our code.
Se você pensar nisso, em todos os exemplos acima, você está obtendo o tipo de serviço <dfn>Last-In-First-Out</dfn> (o último a entrar é o primeiro a sair). Vamos tentar replicar isso com o nosso código.
This data storage scheme is called a <dfn>Stack</dfn>. In particular, we would have to implement the `push()` method that pushes JavaScript objects at the top of the stack; and `pop()` method, that removes the JavaScript object that's at the top of the stack at the current moment.
Este esquema de armazenamento de dados é chamado de <dfn>Pilha</dfn> (ou stack, em inglês). Em particular, teremos que implementar o método `push()`, que coloca objetos do JavaScript no topo da pilha, e o método `pop()`, que remove os objeto do JavaScript no topo da pilha neste momento.
# --instructions--
Here we have a stack of homework assignments represented as an array: `"BIO12"` is at the base, and `"PSY44"` is at the top of the stack.
Aqui temos uma pilha de tarefas representadas como um array: `"BIO12"` está na base, e `"PSY44"` está no topo da pilha.
Modify the given array and treat it like a `stack` using the JavaScript methods mentioned above. Remove the top element `"PSY44"` from the stack. Then add `"CS50"` to be the new top element of the stack.
Modifique o array fornecido e trate-o como uma `stack` usando os métodos do JavaScript mencionados acima. Remover o elemento superior `"PSY44"` da pilha. Em seguida, adicione `"CS50"` para que ele seja o novo elemento superior da pilha.
# --hints--
`homeworkStack` should only contain 4 elements.
`homeworkStack` deve conter apenas 4 elementos.
```js
assert(homeworkStack.length === 4);
```
The last element in `homeworkStack` should be `"CS50"`.
O último elemento em `homeworkStack` deve ser `"CS50"`.
```js
assert(homeworkStack[3] === 'CS50');
```
`homeworkStack` should not contain `"PSY44"`.
`homeworkStack` não deve conter `"PSY44"`.
```js
assert(homeworkStack.indexOf('PSY44') === -1);
```
The initial declaration of the `homeworkStack` should not be changed.
A declaração inicial de `homeworkStack` não deve ser alterada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8254367417b2b2512c6e
title: Perform a Difference on Two Sets of Data
title: Obter a diferença entre dois conjuntos de dados
challengeType: 1
forumTopicId: 301706
dashedName: perform-a-difference-on-two-sets-of-data
@ -8,13 +8,13 @@ dashedName: perform-a-difference-on-two-sets-of-data
# --description--
In this exercise we are going to perform a difference on 2 sets of data. We will create a method on our `Set` data structure called `difference`. A difference of sets should compare two sets and return the items present in the first set that are absent in the second. This method should take another `Set` as an argument and return the `difference` of the two sets.
Neste exercício, vamos obter a diferença entre dois conjuntos de dados. Vamos criar um método sobre nossa estrutura de dados `Set`, chamado `difference`. Uma diferença entre conjuntos deve comparar dois conjuntos e retornar os itens presentes no primeiro conjunto que estão ausentes no segundo. Este método deve receber outro `Set` como um argumento e retornar a `difference` dos dois conjuntos.
For example, if `setA = ['a','b','c']` and `setB = ['a','b','d','e']`, then the difference of setA and setB is: `setA.difference(setB) = ['c']`.
Por exemplo, se `setA = ['a','b','c']` e `setB = ['a','b','d','e']`, a diferença entre o setA e o setB é: `setA.difference(setB) = ['c']`.
# --hints--
Your `Set` class should have a `difference` method.
A classe `Set` deve ter o método `difference`.
```js
assert(
@ -25,7 +25,7 @@ assert(
);
```
Your `difference` method should return the proper collection.
O método `difference` deve retornar a coleção adequada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8254367417b2b2512c6f
title: Perform a Subset Check on Two Sets of Data
title: Verificar subconjuntos em dois conjuntos de dados
challengeType: 1
forumTopicId: 301707
dashedName: perform-a-subset-check-on-two-sets-of-data
@ -8,13 +8,13 @@ dashedName: perform-a-subset-check-on-two-sets-of-data
# --description--
In this exercise, we are going to perform a subset test on 2 sets of data. We will create a method on our `Set` data structure called `isSubsetOf`. This will compare the first set against the second, and if the first set is fully contained within the second, it will return `true`.
Neste exercício, vamos realizar um teste de subconjuntos entre dois conjuntos de dados. Vamos criar um método em nossa estrutura de dados `Set`, chamado `isSubsetOf`. Isto vai comparar o primeiro conjunto com o segundo. Se o primeiro conjunto estiver totalmente contido no segundo, ele retornará `true`.
For example, if `setA = ['a','b']` and `setB = ['a','b','c','d']`, then `setA` is a subset of `setB`, so `setA.isSubsetOf(setB)` should return `true`.
Por exemplo, se `setA = ['a','b']` e `setB = ['a','b','c','d']`, então `setA` é um subconjunto de `setB`, então `setA.isSubsetOf(setB)` deve retornar `true`.
# --hints--
Your `Set` class should have a `isSubsetOf` method.
A classe `Set` deve ter o método `isSubsetOf`.
```js
assert(
@ -25,7 +25,7 @@ assert(
);
```
The first Set() should be contained in the second Set
O primeiro conjunto deve estar contido no segundo
```js
assert(
@ -43,7 +43,7 @@ assert(
);
```
`['a', 'b'].isSubsetOf(['a', 'b', 'c', 'd'])` should return `true`
`['a', 'b'].isSubsetOf(['a', 'b', 'c', 'd'])` deve retornar `true`
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
`['a', 'b', 'c'].isSubsetOf(['a', 'b'])` should return `false`
`['a', 'b', 'c'].isSubsetOf(['a', 'b'])` deve retornar `false`
```js
assert(
@ -80,7 +80,7 @@ assert(
);
```
`[].isSubsetOf([])` should return `true`
`[].isSubsetOf([])` deve retornar `true`
```js
assert(
@ -93,7 +93,7 @@ assert(
);
```
`['a', 'b'].isSubsetOf(['c', 'd'])` should return `false`
`['a', 'b'].isSubsetOf(['c', 'd'])` deve retornar `false`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8253367417b2b2512c6c
title: Perform a Union on Two Sets
title: Realizar a união entre dois conjuntos
challengeType: 1
forumTopicId: 301708
dashedName: perform-a-union-on-two-sets
@ -8,13 +8,13 @@ dashedName: perform-a-union-on-two-sets
# --description--
In this exercise we are going to perform a union on two sets of data. We will create a method on our `Set` data structure called `union`. This method should take another `Set` as an argument and return the `union` of the two sets, excluding any duplicate values.
Neste exercício, vamos realizar a união entre dois conjuntos de dados. Vamos criar um método na nossa estrutura de dados `Set`, chamado `union`. Este método deve receber outro `Set` como um argumento e retornar a `union` dos dois conjuntos, excluindo os valores duplicados.
For example, if `setA = ['a','b','c']` and `setB = ['a','b','d','e']`, then the union of setA and setB is: `setA.union(setB) = ['a', 'b', 'c', 'd', 'e']`.
Por exemplo, se `setA = ['a','b','c']` e `setB = ['a','b','d','e']`, a união do setA e do setB é: `setA.union(setB) = ['a', 'b', 'c', 'd', 'e']`.
# --hints--
Your `Set` class should have a `union` method.
A classe `Set` deve ter o método `union`.
```js
assert(
@ -25,7 +25,7 @@ assert(
);
```
The union of a Set containing values ["a", "b", "c"] and a Set containing values ["c", "d"] should return a new Set containing values ["a", "b", "c", "d"].
A união de um conjunto contendo os valores ["a", "b", "c"] e um conjunto contendo valores ["c", "d"] deve retornar um novo conjunto contendo os valores ["a", "b", "c", "d"].
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8253367417b2b2512c6d
title: Perform an Intersection on Two Sets of Data
title: Realizar a interseção entre dois conjuntos de dados
challengeType: 1
forumTopicId: 301709
dashedName: perform-an-intersection-on-two-sets-of-data
@ -8,13 +8,13 @@ dashedName: perform-an-intersection-on-two-sets-of-data
# --description--
In this exercise we are going to perform an intersection on 2 sets of data. We will create a method on our `Set` data structure called `intersection`. An intersection of sets represents all values that are common to two or more sets. This method should take another `Set` as an argument and return the `intersection` of the two sets.
Neste exercício, vamos obter a interseção entre dois conjuntos de dados. Vamos criar um método na nossa estrutura de dados `Set`, chamado `intersection`. Uma interseção de conjuntos representa todos os valores que são comuns a dois ou mais conjuntos. Este método deve receber outro `Set` como um argumento e retornar a `intersection` dos dois conjuntos.
For example, if `setA = ['a','b','c']` and `setB = ['a','b','d','e']`, then the intersection of setA and setB is: `setA.intersection(setB) = ['a', 'b']`.
Por exemplo, se `setA = ['a','b','c']` e `setB = ['a','b','d','e']`, a interseção do setA e do setB é: `setA.intersection(setB) = ['a', 'b']`.
# --hints--
Your `Set` class should have a `intersection` method.
A classe `Set` deve ter o método `intersection`.
```js
assert(
@ -25,7 +25,7 @@ assert(
);
```
The proper collection should be returned.
A coleção adequada deve ser retornada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8b
title: Remove an Element from a Max Heap
title: Remover um elemento de um Max Heap
challengeType: 1
forumTopicId: 301710
dashedName: remove-an-element-from-a-max-heap
@ -8,21 +8,21 @@ dashedName: remove-an-element-from-a-max-heap
# --description--
Now that we can add elements to our heap let's see how we can remove elements. Removing and inserting elements both require similar logic. In a max heap you will usually want to remove the greatest value, so this involves simply extracting it from the root of our tree. This will break the heap property of our tree, so we must reestablish it in some way. Typically, for a max heap this is done in the following way:
Agora que podemos adicionar elementos à nossa heap, vamos ver como podemos remover elementos. Remover e inserir elementos requerem uma lógica similar. Em um max heap, você normalmente vai querer remover o maior valor, então isso envolve simplesmente tirá-lo da raiz da nossa árvore. Isto vai quebrar a propriedade heap de nossa árvore, então temos de restabelecer a propriedade de alguma forma. Normalmente, para um Max Heap, isso é feito da seguinte maneira:
<ol>
<li>Move the last element in the heap into the root position.</li>
<li>If either child of the root is greater than it, swap the root with the child of greater value.</li>
<li>Continue swapping until the parent is greater than both children or you reach the last level in the tree.</li>
<li>Mova o último elemento no heap para a posição raiz.</li>
<li>Se qualquer filho da raiz for maior do que ela, troque a raiz pelo filho de maior valor.</li>
<li>Continue trocando até que o pai seja maior que os dois filhos ou até que você atinja o último nível da árvore.</li>
</ol>
# --instructions--
Instructions: Add a method to our max heap called `remove`. This method should return the greatest value that has been added to our max heap and remove it from the heap. It should also reorder the heap so the heap property is maintained. After removing an element, the next greatest element remaining in the heap should become the root.
Instruções: adicione um método a nosso Max Heap chamado `remove`. Este método deve retornar o maior valor que for adicionado ao nosso Max Heap e removê-lo da heap. Ele também deve reordenar o heap para que a propriedade heap seja mantida. Depois de remover um elemento, o próximo elemento de maior valor do restante do heap deve se tornar a raiz.
# --hints--
The MaxHeap data structure should exist.
A estrutura de dados MaxHeap deve existir.
```js
assert(
@ -36,7 +36,7 @@ assert(
);
```
MaxHeap should have a method called print.
MaxHeap deve ter um método chamado print.
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
MaxHeap should have a method called insert.
MaxHeap deve ter um método chamado insert.
```js
assert(
@ -68,7 +68,7 @@ assert(
);
```
MaxHeap should have a method called remove.
MinHeap deve ter um método chamado remove.
```js
assert(
@ -84,7 +84,7 @@ assert(
);
```
The remove method should remove the greatest element from the max heap while maintaining the max heap property.
O método remove deve remover o maior elemento do Max Heap ao mesmo tempo em que mantém a propriedade do Max Heap.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c65
title: Remove Elements from a Linked List by Index
title: Remover elementos de uma lista encadeada por índice
challengeType: 1
forumTopicId: 301711
dashedName: remove-elements-from-a-linked-list-by-index
@ -8,23 +8,23 @@ dashedName: remove-elements-from-a-linked-list-by-index
# --description--
Before we move on to another data structure, let's get a couple of last bits of practice with linked lists.
Antes de avançarmos para outra estrutura de dados, vamos aprender algumas práticas finais com listas encadeadas.
Let's write a `removeAt` method that removes the `element` at a given `index`. The method should be called `removeAt(index)`. To remove an `element` at a certain `index`, we'll need to keep a running count of each node as we move along the linked list.
Vamos escrever um método `removeAt`, que remove o `element` em um determinado `index`. O método deve ser chamado `removeAt(index)`. Para remover um `element` em um certo `index`, precisaremos manter uma contagem em execução de cada nó enquanto percorremos a lista encadeada.
A common technique used to iterate through the elements of a linked list involves a <dfn>'runner'</dfn>, or sentinel, that 'points' at the nodes that your code is comparing. In our case, starting at the `head` of our list, we start with a `currentIndex` variable that starts at `0`. The `currentIndex` should increment by one for each node we pass.
Uma técnica comum usada para iterar através dos elementos de uma lista encadeada envolve um <dfn>'percorredor'</dfn>, ou sentinela, que 'aponte' para os nós que o seu código está comparando. Em nosso caso, começando com a `head` de nossa lista, iniciamos com uma variável `currentIndex` com o valor `0`. O `currentIndex` deve incrementar de um em um para cada nó que percorrermos.
Just like our `remove(element)` method, which [we covered in a previous lesson](/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list), we need to be careful not to orphan the rest of our list when we remove the node in our `removeAt(index)` method. We keep our nodes contiguous by making sure that the node that has reference to the removed node has a reference to the next node.
Assim como nosso método `remove(element)`, que [abordamos em uma aula anterior](/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list), precisamos ser cuidadosos para não deixar órfã o resto de nossa lista quando removermos o nó em nosso método `removeAt(index)`. Manteremos nossos nós um após o outro, garantindo que o nó que possui a referência ao nó removido tenha uma referência ao próximo nó.
# --instructions--
Write a `removeAt(index)` method that removes and returns a node at a given `index`. The method should return `null` if the given `index` is either negative, or greater than or equal to the `length` of the linked list.
Escreva um método `removeAt(index)`, que remove e retorna um nó em um determinado `index`. O método deve retornar `null` se o dado `index` for negativo, maior que ou igual ao `length` da lista encadeada.
**Note:** Remember to keep count of the `currentIndex`.
**Observação:** lembre-se de manter a contagem do `currentIndex`.
# --hints--
Your `LinkedList` class should have a `removeAt` method.
A classe `LinkedList` deve ter o método `removeAt`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
Your `removeAt` method should reduce the `length` of the linked list by one.
O método `removeAt` deve diminuir o `length` da lista encadeada em um.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
Your `removeAt` method should remove the element at the specified index from the linked list.
O método `removeAt` deve remover o elemento no índice especificado da lista encadeada.
```js
assert(
@ -69,7 +69,7 @@ assert(
);
```
When only one element is present in the linked list, your `removeAt` method should remove and return the element at specified index, and reduce the length of the linked list.
Quando apenas um elemento está presente na lista encadeada, o método `removeAt` deve remover e retornar o elemento no índice especificado e reduzir o tamanho da lista encadeada.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
Your `removeAt` method should return the element of the removed node.
O método `removeAt` deve retornar o elemento do nó removido.
```js
assert(
@ -96,7 +96,7 @@ assert(
);
```
Your `removeAt` method should return `null` and the linked list should not change if the given index is less than `0`.
O método `removeAt` deve retornar `null` e a lista encadeada não deve mudar se o índice dado for menor que `0`.
```js
assert(
@ -115,7 +115,7 @@ assert(
);
```
Your `removeAt` method should return `null` and the linked list should not change if the given index is greater than or equal to the `length` of the list.
O método `removeAt` deve retornar `null` e a lista encadeada não deve mudar se o índice dado for maior que ou igual ao `length` da lista.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c63
title: Remove Elements from a Linked List
title: Remover elementos de uma lista encadeada
challengeType: 1
forumTopicId: 301712
dashedName: remove-elements-from-a-linked-list
@ -8,23 +8,23 @@ dashedName: remove-elements-from-a-linked-list
# --description--
The next important method that any implementation of a linked list will need is a `remove` method. This method should take the element we want to remove as an argument, and then search the list to find and remove the node that contains that element.
O próximo método importante que qualquer implementação de uma lista encadeada precisará é de um método `remove`. Este método deve receber como argumento o elemento que queremos remover, e, em seguida, procurar na lista para encontrar e remover o nó que contém esse elemento.
Whenever we remove a node from a linked list, it's important that we don't accidentally orphan the rest of the list in doing so. Recall that every node's `next` property points to the node that follows it in the list. If we're removing the middle element, say, we'll want to make sure that we have a connection from that element's previous node's `next` property to the middle element's `next` property (which is the next node in the list!)
Sempre que removermos um nó de uma lista encadeada, é importante que não deixemos o resto da lista órfã ao fazer isso. Lembre-se de que todos os pontos de propriedade `next` dos nós apontam para o nó que os segue na lista. Se estivermos removendo o elemento do meio, digamos, vamos precisar ter certeza de que temos uma conexão com a propriedade `next` do nó anterior daquele elemento para a propriedade `next` do elemento do meio (que é o próximo nó na lista!)
This might sound really confusing, so let's return to the conga line example so we have a good conceptual model. Picture yourself in a conga line, and the person directly in front of you leaves the line. The person who just left the line no longer has her hands on anyone in line--and you no longer have your hands on the person that left. You step forward and put your hands on next person you see.
Isso pode parecer muito confuso, então vamos voltar ao exemplo da fila de dançarinos de conga para que tenhamos um bom modelo conceitual. Imagine-se em uma fila de dançarinos de conga e que a pessoa diretamente à sua frente saia da fila. A pessoa que acabou de deixar a fila já não tem as mãos sobre ninguém da fila - e você já não tem as mãos sobre a pessoa que saiu. Você dá um passo para a frente e coloca as mãos na próxima pessoa que vê.
If the element we wish to remove is the `head` element, we reassign the `head` to the second node of the linked list.
Se o elemento que queremos remover for o elemento `head`, reatribuímos a propriedade `head` para o segundo nó da lista encadeada.
# --instructions--
Write a `remove` method that takes an element and removes it from the linked list.
Escreva um método `remove` que pegue um elemento e o remova da lista encadeada.
**Note:** The `length` of the list should decrease by one every time an element is removed from the linked list.
**Observação:** o `length` da lista deve diminuir em um sempre que um elemento for removido da lista encadeada.
# --hints--
Your `LinkedList` class should have a `remove` method.
A classe `LinkedList` deve ter o método `remove`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
Your `remove` method should reassign `head` to the second node when the first node is removed.
O método `remove` deve reatribuir `head` ao segundo nó quando o primeiro nó for removido.
```js
assert(
@ -49,7 +49,7 @@ assert(
);
```
Your `remove` method should decrease the `length` of the linked list by one for every node removed.
O método `remove` deve diminuir o `length` da lista encadeada em um para cada nó removido.
```js
assert(
@ -65,7 +65,7 @@ assert(
);
```
Your `remove` method should reassign the reference of the previous node of the removed node to the removed node's `next` reference.
O método `remove` deve reatribuir a referência do nó anterior ao nó removido para a referência `next` do nó removido.
```js
assert(
@ -81,7 +81,7 @@ assert(
);
```
Your `remove` method should not change the linked list if the element does not exist in the linked list.
O método `remove` não deve alterar a lista encadeada se o elemento não existir nela.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8254367417b2b2512c71
title: Remove items from a set in ES6
title: Remover itens de um conjunto na ES6
challengeType: 1
forumTopicId: 301713
dashedName: remove-items-from-a-set-in-es6
@ -8,15 +8,15 @@ dashedName: remove-items-from-a-set-in-es6
# --description--
Let's practice removing items from an ES6 Set using the `delete` method.
Vamos praticar a remoção de itens de um conjunto da ES6 usando o método `delete`.
First, create an ES6 Set:
Primeiro, crie um conjunto (Set) da ES6:
```js
var set = new Set([1,2,3]);
```
Now remove an item from your Set with the `delete` method.
Agora, remova um item do seu conjunto com o método `delete`.
```js
set.delete(1);
@ -25,13 +25,13 @@ console.log([...set]) // should return [ 2, 3 ]
# --instructions--
Now, create a set with the integers 1, 2, 3, 4, & 5.
Crie um conjunto com os números inteiros 1, 2, 3, 4 e 5.
Remove the values 2 and 5, and then return the set.
Remova os valores 2 e 5. Então, retorne o conjunto.
# --hints--
Your Set should contain the values 1, 3, & 4
O conjunto deve conter os valores 1, 3 e 4
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825a367417b2b2512c88
title: Reverse a Doubly Linked List
title: Inverter uma lista duplamente encadeada
challengeType: 1
forumTopicId: 301714
dashedName: reverse-a-doubly-linked-list
@ -8,11 +8,11 @@ dashedName: reverse-a-doubly-linked-list
# --description--
Let's create one more method for our doubly linked list called reverse which reverses the list in place. Once the method is executed the head should point to the previous tail and the tail should point to the previous head. Now, if we traverse the list from head to tail we should meet the nodes in a reverse order compared to the original list. Trying to reverse an empty list should return null.
Vamos criar mais um método para a nossa lista duplamente encadeada, chamado reverse, que inverterá a lista atual. Quando o método for executado, a head (início da lista) deve apontar para a tail (fim da lista) anterior e a tail deve apontar para a head anterior. Agora, se percorrermos a lista da head para a tail, devemos encontrar os nós em uma ordem inversa em comparação com a lista original. Tentar reverter uma lista vazia deve retornar null.
# --hints--
The DoublyLinkedList data structure should exist.
A estrutura de dados DoublyLinkedList deve existir.
```js
assert(
@ -26,7 +26,7 @@ assert(
);
```
The DoublyLinkedList should have a method called reverse.
A DoublyLinkedList deve ter um método chamado reverse.
```js
assert(
@ -43,7 +43,7 @@ assert(
);
```
Reversing an empty list should return null.
Inverter uma árvore vazia deve retornar null.
```js
assert(
@ -57,7 +57,7 @@ assert(
);
```
The reverse method should reverse the list.
O método reverse deverá inverter a lista.
```js
assert(
@ -77,7 +77,7 @@ assert(
);
```
The next and previous references should be correctly maintained when a list is reversed.
As referências next e previous devem ser mantidas corretamente quando a lista é revertida.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c64
title: Search within a Linked List
title: Pesquisar em uma lista encadeada
challengeType: 1
forumTopicId: 301715
dashedName: search-within-a-linked-list
@ -8,19 +8,19 @@ dashedName: search-within-a-linked-list
# --description--
Let's add a few more useful methods to our linked list class. Wouldn't it be useful if we could tell if our list was empty or not, as with our `Stack` and `Queue` classes?
Vamos adicionar mais alguns métodos úteis à nossa classe de lista encadeada. Não seria útil se pudéssemos dizer se nossa lista estava vazia ou não. como em nossas classes `Stack` e `Queue`?
We should also be able to find specific elements in our linked list. Traversing through data structures is something you'll want to get a lot of practice with! Let's create an `indexOf` method that takes an `element` as an argument, and returns that element's `index` in the linked list. If the element is not found in the linked list, return `-1`.
Deveríamos também poder encontrar elementos específicos na nossa lista encadeada. Percorrer estruturas de dados é algo que você vai querer praticar bastante! Vamos criar um método `indexOf`, que recebe um `element` como argumento, e retorna o `index` desse elemento na lista encadeada. Se o elemento não for encontrado na lista encadeada, retorne `-1`.
Let's also implement a method that does the opposite: an `elementAt` method that takes an `index` as an argument and returns the `element` at the given `index`. If no `element` is found, return `undefined`.
Vamos também implementar um método que faz o oposto: um método `elementAt`, que recebe um `index` como um argumento e retorna o `element` que está no `index` fornecido. Se nenhum `element` passar no teste, retorne `undefined`.
# --instructions--
Write an `isEmpty` method that checks if the linked list is empty, an `indexOf` method that returns the `index` of a given element, and an `elementAt` that returns an `element` at a given `index.`
Escreva um método `isEmpty`, que verifique se a lista está vazia, um método `indexOf`, que retorna o `index` de um determinado elemento, e um método `elementAt`, que retorna um `element` em um dado `index.`
# --hints--
Your `LinkedList` class should have an `isEmpty` method.
A classe `LinkedList` deve ter o método `isEmpty`.
```js
assert(
@ -31,7 +31,7 @@ assert(
);
```
Your `isEmpty` method should return `false` when there is at least one element in linked list.
O método `isEmpty` deve retornar `false` quando houver pelo menos um elemento na lista encadeada.
```js
assert(
@ -45,7 +45,7 @@ assert(
);
```
Your `isEmpty` method should return `true` when there are no elements in linked list.
O método `isEmpty` deve retornar `true` quando não houver elementos na lista encadeada.
```js
assert(
@ -56,7 +56,7 @@ assert(
);
```
Your `LinkedList` class should have an `indexOf` method.
A classe `LinkedList` deve ter o método `indexOf`.
```js
assert(
@ -67,7 +67,7 @@ assert(
);
```
Your `indexOf` method should return the index of a given element found in linked list.
O método `indexOf` deve retornar o índice de um determinado elemento encontrado na lista encadeada.
```js
assert(
@ -81,7 +81,7 @@ assert(
);
```
Your `indexOf` method should return `-1` if the given element is not found in linked list
O método `indexOf` deve retornar `-1` se o elemento fornecido não for encontrado na lista encadeada
```js
assert(
@ -95,7 +95,7 @@ assert(
);
```
Your `LinkedList` class should have an `elementAt` method.
A classe `LinkedList` deve ter o método `elementAt`.
```js
assert(
@ -106,7 +106,7 @@ assert(
);
```
Your `elementAt` method should return the element found at a given index in linked list.
O método `elementAt` deve retornar o elemento encontrado no índice fornecido da lista encadeada.
```js
assert(
@ -120,7 +120,7 @@ assert(
);
```
Your `elementAt` method should return `undefined` if the given element is not found at a given index in linked list.
O método `elementAt` deve retornar `undefined` se o elemento fornecido não for encontrado no índice fornecido na lista encadeada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8253367417b2b2512c6a
title: Typed Arrays
title: Arrays tipados
challengeType: 1
forumTopicId: 301716
dashedName: typed-arrays
@ -8,21 +8,21 @@ dashedName: typed-arrays
# --description--
Arrays are JavaScript objects that can hold a lot of different elements.
Arrays são objetos JavaScript que podem ter muitos elementos diferentes.
```js
var complexArr = [1, 5, "2", "Word", {"name": "James"}];
```
Basically what happens in the background is that your browser will automatically give the right amount of memory space for that array. It will also change as needed if you add or remove data.
Basicamente, o que acontece em segundo plano é que o seu navegador dará automaticamente o espaço de memória certo para esse array. Ele também será alterado conforme necessário, se você adicionar ou remover dados.
However, in the world of high performance and different element types, sometimes you need to be more specific on how much memory is given to an array.
No entanto, no mundo do alto desempenho e de diferentes tipos de elementos, às vezes, você precisa ser mais específico sobre a quantidade de memória que é dada a um array.
<dfn>Typed arrays</dfn> are the answer to this problem. You are now able to say how much memory you want to give an array. Below is a basic overview of the different types of arrays available and the size in bytes for each element in that array.
<dfn>Arrays tipados</dfn> são a resposta para este problema. Agora, você pode dizer quanta memória você deseja dar a um array. Abaixo, vemos uma visão geral básica dos diferentes tipos de arrays disponíveis e o tamanho em bytes para cada elemento do array.
<table class='table table-striped'><tbody><tr><th>Type</th><th>Each element size in bytes</th></tr><tr><td><code>Int8Array</code></td><td>1</td></tr><tr><td><code>Uint8Array</code></td><td>1</td></tr><tr><td><code>Uint8ClampedArray</code></td><td>1</td></tr><tr><td><code>Int16Array</code></td><td>2</td></tr><tr><td><code>Uint16Array</code></td><td>2</td></tr><tr><td><code>Int32Array</code></td><td>4</td></tr><tr><td><code>Uint32Array</code></td><td>4</td></tr><tr><td><code>Float32Array</code></td><td>4</td></tr><tr><td><code>Float64Array</code></td><td>8</td></tr></tbody></table>
<table class='table table-striped'><tbody><tr><th>Tipo</th><th>Tamanho de cada elemento em bytes</th></tr><tr><td><code>Int8Array</code></td><td>1</td></tr><tr><td><code>Uint8Array</code></td><td>1</td></tr><tr><td><code>Uint8ClampedArray</code></td><td>1</td></tr><tr><td><code>Int16Array</code></td><td>2</td></tr><tr><td><code>Uint16Array</code></td><td>2</td></tr><tr><td><code>Int32Array</code></td><td>4</td></tr><tr><td><code>Uint32Array</code></td><td>4</td></tr><tr><td><code>Float32Array</code></td><td>4</td></tr><tr><td><code>Float64Array</code></td><td>8</td></tr></tbody></table>
There are two ways in creating these kind of arrays. One way is to create it directly. Below is how to create a 3 length `Int16Array`.
Há duas maneiras de criar este tipo de array. Uma delas é criá-lo diretamente. Abaixo vemos como criar um `Int16Array` de tamanho 3.
```js
var i8 = new Int16Array(3);
@ -30,8 +30,8 @@ console.log(i8);
// Returns [0, 0, 0]
```
You can also create a <dfn>buffer</dfn> to assign how much data (in bytes) you want the array to take up. **Note**
To create typed arrays using buffers, you need to assign the number of bytes to be a multiple of the bytes listed above.
Também é possível criar um <dfn>buffer</dfn> para atribuir a quantidade de dados (em bytes) que o array deseja ocupar. **Observação**
Para criar arrays tipados usando buffers, você precisa atribuir o número de bytes como um múltiplo dos bytes listados acima.
```js
// Create same Int16Array array differently
@ -43,35 +43,35 @@ i8View.byteLength; // Returns 6
console.log(i8View); // Returns [0, 0, 0]
```
<dfn>Buffers</dfn> are general purpose objects that just carry data. You cannot access them normally. To access them, you need to first create a <dfn>view</dfn>.
<dfn>Buffers</dfn> são objetos de propósito genérico que simplesmente carregam dados. Você não pode acessá-los normalmente. Para acessá-los, primeiro você precisa criar uma <dfn>visualização</dfn>.
```js
i8View[0] = 42;
console.log(i8View); // Returns [42, 0, 0]
```
**Note**
Typed arrays do not have some of the methods traditional arrays have such as `.pop()` or `.push()`. Typed arrays also fail `Array.isArray()` that checks if something is an array. Although simpler, this can be an advantage for less-sophisticated JavaScript engines to implement them.
**Observação**
Arrays tipados não possuem alguns dos métodos que os arrays tradicionais têm, como `.pop()` ou `.push()`. Arrays tipados também falham testes com o método `Array.isArray()`, que verifica se algo é um array. Embora sejam mais simples, isso pode ser uma vantagem para que mecanismos de JavaScript menos sofisticados possam implementá-los.
# --instructions--
First create a `buffer` that is 64-bytes. Then create a `Int32Array` typed array with a view of it called `i32View`.
Primeiro, crie um `buffer` de 64 bytes. Em seguida, crie um array tipado `Int32Array` com uma visualização dele chamada `i32View`.
# --hints--
Your `buffer` should be 64 bytes large.
O `buffer` deve ter 64 bytes de tamanho.
```js
assert(buffer.byteLength === 64);
```
Your `i32View` view of your buffer should be 64 bytes large.
A visualização `i32View` de seu buffer deve ter 64 bytes de tamanho.
```js
assert(i32View.byteLength === 64);
```
Your `i32View` view of your buffer should be 16 elements long.
A visualização `i32View` de seu buffer deve ter 16 elementos.
```js
assert(i32View.length === 16);

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c72
title: Use .has and .size on an ES6 Set
title: Usar .has e .size em um conjunto da ES6
challengeType: 1
forumTopicId: 301717
dashedName: use--has-and--size-on-an-es6-set
@ -8,21 +8,21 @@ dashedName: use--has-and--size-on-an-es6-set
# --description--
Let's look at the .has and .size methods available on the ES6 Set object.
Vamos analisar os métodos .has e .size disponíveis no objeto Set da ES6.
First, create an ES6 Set
Primeiro, crie um conjunto (Set) da ES6
```js
var set = new Set([1,2,3]);
```
The .has method will check if the value is contained within the set.
O método .has verificará se o valor está contido dentro do conjunto.
```js
var hasTwo = set.has(2);
```
The .size method will return an integer representing the size of the Set
O método .size retornará um inteiro representando o tamanho do conjunto
```js
var howBig = set.size;
@ -30,11 +30,11 @@ var howBig = set.size;
# --instructions--
In this exercise we will pass an array and a value to the checkSet() function. Your function should create an ES6 set from the array argument. Find if the set contains the value argument. Find the size of the set. And return those two values in an array.
Neste exercício, vamos passar um array e um valor para a função checkSet(). A função deve criar um set da ES6 a partir do argumento do array. Descubra se o conjunto contém o argumento do valor. Encontre o tamanho do conjunto. Por fim, retorne esses dois valores em um array.
# --hints--
`checkSet([4, 5, 6], 3)` should return [ false, 3 ]
`checkSet([4, 5, 6], 3)` deve retornar [ false, 3 ]
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8258367417b2b2512c7f
title: Use Breadth First Search in a Binary Search Tree
title: Usar a busca em largura na árvore binária de busca
challengeType: 1
forumTopicId: 301718
dashedName: use-breadth-first-search-in-a-binary-search-tree
@ -8,17 +8,17 @@ dashedName: use-breadth-first-search-in-a-binary-search-tree
# --description--
Here we will introduce another tree traversal method: breadth-first search. In contrast to the depth-first search methods from the last challenge, breadth-first search explores all the nodes in a given level within a tree before continuing on to the next level. Typically, queues are utilized as helper data structures in the design of breadth-first search algorithms.
Aqui vamos introduzir outro método de travessia de árvores: busca em largura. Em contraste com os métodos de busca em profundidade do último desafio, a busca em largura explora todos os nós em um determinado nível de uma árvore antes de continuar para o próximo nível. Normalmente, as filas (queues) são utilizadas como estruturas de dados auxiliares na criação dos algoritmos de busca em largura.
In this method, we start by adding the root node to a queue. Then we begin a loop where we dequeue the first item in the queue, add it to a new array, and then inspect both its child subtrees. If its children are not null, they are each enqueued. This process continues until the queue is empty.
Neste método, começamos adicionando o nó raiz a uma fila. Em seguida, começamos um laço onde separamos o primeiro item da fila, o adicionamos a um novo array e, então, inspecionamos suas subárvores filhas. Se as filhas não forem nulas, elas serão colocadas na fila. Este processo continua até que a fila esteja vazia.
# --instructions--
Let's create a breadth-first search method in our tree called `levelOrder`. This method should return an array containing the values of all the tree nodes, explored in a breadth-first manner. Be sure to return the values in the array, not the nodes themselves. A level should be traversed from left to right. Next, let's write a similar method called `reverseLevelOrder` which performs the same search but in the reverse direction (right to left) at each level.
Vamos criar um método de busca em largura em nossa árvore chamado `levelOrder`. Este método deve retornar um array que contenha os valores de todos os nós da árvore, explorados em uma busca em largura. Certifique-se de retornar os valores no array, não os próprios nós. Um nível deve ser atravessado da esquerda para a direita. Em seguida, vamos escrever um método similar chamado `reverseLevelOrder`, que executa a mesma busca, mas na direção inversa (da direita para a esquerda) em cada nível.
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
The binary search tree should have a method called `levelOrder`.
A árvore binária de busca deve ter um método chamado `levelOrder`.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The binary search tree should have a method called `reverseLevelOrder`.
A árvore binária de busca deve ter um método chamado `reverseLevelOrder`.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
The `levelOrder` method should return an array of the tree node values explored in level order.
O método `levelOrder` deve retornar um array de valores dos nós da árvore explorados na ordem dos níveis.
```js
assert(
@ -94,7 +94,7 @@ assert(
);
```
The `reverseLevelOrder` method should return an array of the tree node values explored in reverse level order.
O método `reverseLevelOrder` deve retornar um array de valores dos nós da árvore explorados na ordem inversa dos níveis.
```js
assert(
@ -124,7 +124,7 @@ assert(
);
```
The `levelOrder` method should return `null` for an empty tree.
O método `levelOrder` deve retornar `null` para uma árvore vazia.
```js
assert(
@ -143,7 +143,7 @@ assert(
);
```
The `reverseLevelOrder` method should return `null` for an empty tree.
O método `reverseLevelOrder` deve retornar `null` para uma árvore vazia.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7e
title: Use Depth First Search in a Binary Search Tree
title: Usar busca em profundidade em uma árvore binária de busca
challengeType: 1
forumTopicId: 301719
dashedName: use-depth-first-search-in-a-binary-search-tree
@ -8,15 +8,15 @@ dashedName: use-depth-first-search-in-a-binary-search-tree
# --description--
We know how to search a binary search tree for a specific value. But what if we just want to explore the entire tree? Or what if we don't have an ordered tree and we need to just search for a value? Here we will introduce some tree traversal methods which can be used to explore tree data structures. First up is depth-first search. In depth-first search, a given subtree is explored as deeply as possible before the search continues on to another subtree. There are three ways this can be done: In-order: Begin the search at the left-most node and end at the right-most node. Pre-order: Explore all the roots before the leaves. Post-order: Explore all the leaves before the roots. As you may guess, you may choose different search methods depending on what type of data your tree is storing and what you are looking for. For a binary search tree, an inorder traversal returns the nodes in sorted order.
Sabemos como procurar por um valor específico em uma árvore binária. Mas e se quisermos pesquisar a árvore inteira? E se não tivermos uma árvore ordenada e precisarmos simplesmente pesquisar por um valor? Aqui, vamos introduzir alguns métodos de travessia que podem ser usados para pesquisar essa estrutura de dados. O primeiro método será a busca em profundidade. Na busca em profundidade, uma determinada subárvore é pesquisada o mais profundamente possível antes da busca continuar para outra subárvore. Podemos realizar essa busca de três formas: Em ordem: começa a pesquisa no nó mais à esquerda e termina no nó mais à direita. Pré-ordem: pesquisa todas as raízes antes das folhas. Pós-ordem: pesquisa todas as folhas antes das raízes. Como você pode imaginar, você pode escolher métodos de busca diferentes, dependendo dos dados que sua árvore armazena e do que você está procurando. Em uma árvore binária de busca, uma travessia de ordem retorna os nós de forma ordenada.
# --instructions--
Here we will create these three search methods on our binary search tree. Depth-first search is an inherently recursive operation which continues to explore further subtrees so long as child nodes are present. Once you understand this basic concept, you can simply rearrange the order in which you explore the nodes and subtrees to produce any of the three searches above. For example, in post-order search we would want to recurse all the way to a leaf node before we begin to return any of the nodes themselves, whereas in pre-order search we would want to return the nodes first, and then continue recursing down the tree. Define `inorder`, `preorder`, and `postorder` methods on our tree. Each of these methods should return an array of items which represent the tree traversal. Be sure to return the integer values at each node in the array, not the nodes themselves. Finally, return `null` if the tree is empty.
Aqui, vamos usar estes três métodos de pesquisa na nossa árvore binária de busca. A busca em profundidade é uma operação inerentemente recursiva que continua a pesquisar mais subárvores enquanto existirem nós filhos. Uma vez que você entende este conceito básico, você pode simplesmente reorganizar a ordem da pesquisa nos nós e nas subárvores para produzir qualquer uma das três buscas. Por exemplo, na busca de pós-ordem, a pesquisa deve, recursivamente, ir até o nó da folha antes de retornar qualquer um dos nós em si. Por outro lado, na busca de pré-ordem, a pesquisa deve retornar os nós primeiro e depois continuar a pesquisa pela árvore. Use os métodos em ordem (`inorder`), pré-ordem (`preorder`) e pós-ordem (`postorder`) na nossa árvore. Cada um desses métodos deve retornar um array de itens que representa a travessia da árvore. Certifique-se de retornar os valores numéricos em cada nó do array, não os nós em si. Por fim, retorne `null` se a árvore estiver vazia.
# --hints--
The `BinarySearchTree` data structure should exist.
A estrutura de dados `BinarySearchTree` deve existir.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
The binary search tree should have a method called `inorder`.
A árvore binária de busca deve ter um método chamado `inorder`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
The binary search tree should have a method called `preorder`.
A árvore binária de busca deve ter um método chamado `preorder`.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
The binary search tree should have a method called `postorder`.
A árvore binária de busca deve ter um método chamado `postorder`.
```js
assert(
@ -78,7 +78,7 @@ assert(
);
```
The `inorder` method should return an array of the node values that result from an inorder traversal.
O método `inorder` deve retornar um array com os valores de cada nó.
```js
assert(
@ -108,7 +108,7 @@ assert(
);
```
The `preorder` method should return an array of the node values that result from a preorder traversal.
O método `preorder` deve retornar um array com os valores de cada nó.
```js
assert(
@ -138,7 +138,7 @@ assert(
);
```
The `postorder` method should return an array of the node values that result from a postorder traversal.
O método `postorder` deve retornar um array com os valores de cada nó.
```js
assert(
@ -168,7 +168,7 @@ assert(
);
```
The `inorder` method should return `null` for an empty tree.
O método `inorder` deve retornar `null` quando a árvore estiver vazia.
```js
assert(
@ -187,7 +187,7 @@ assert(
);
```
The `preorder` method should return `null` for an empty tree.
O método `preorder` deve retornar `null` quando a árvore estiver vazia.
```js
assert(
@ -206,7 +206,7 @@ assert(
);
```
The `postorder` method should return `null` for an empty tree.
O método `postorder` deve retornar `null` quando a árvore estiver vazia.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c73
title: Use Spread and Notes for ES5 Set() Integration
title: Usar spread e notas para a integração do Set() da ES5
challengeType: 1
forumTopicId: 301720
dashedName: use-spread-and-notes-for-es5-set-integration
@ -8,11 +8,11 @@ dashedName: use-spread-and-notes-for-es5-set-integration
# --description--
Do you remember the ES6 spread operator `...`?
Você se lembra do operador spread da ES6 `...`?
`...` can take iterable objects in ES6 and turn them into arrays.
`...` pode pegar objetos iteráveis no ES6 e transformá-los em arrays.
Let's create a Set, and check out the spread function.
Vamos criar um conjunto e conferir a função spread.
```js
var set = new Set([1,2,3]);
@ -22,13 +22,13 @@ console.log(setToArr) // returns [ 1, 2, 3 ]
# --instructions--
In this exercise we will pass a set object to the `checkSet` function. It should return an array containing the values of the Set.
Nesse exercício, passaremos um objeto definido para a função `checkSet`. Ela deve retornar um array contendo os valores do conjunto.
Now you've successfully learned how to use the ES6 `Set()` object, good job!
Agora, você aprendeu com sucesso como usar o objeto `Set()` da ES6. Bom trabalho!
# --hints--
`checkSet(new Set([1,2,3,4,5,6,7])` should return `[1, 2, 3, 4, 5, 6, 7]`.
`checkSet(new Set([1,2,3,4,5,6,7])` deve retornar `[1, 2, 3, 4, 5, 6, 7]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c61
title: Work with Nodes in a Linked List
title: Trabalhar com nós em uma lista encadeada
challengeType: 1
forumTopicId: 301721
dashedName: work-with-nodes-in-a-linked-list
@ -8,25 +8,25 @@ dashedName: work-with-nodes-in-a-linked-list
# --description--
Another common data structure you'll run into in computer science is the <dfn>linked list</dfn>. A linked list is a linear collection of data elements, called 'nodes', each of which points to the next. Each <dfn>node</dfn> in a linked list contains two key pieces of information: the `element` itself, and a reference to the next `node`.
Outra estrutura de dados comum que você vai encontrar frequentemente em ciência da computação é a <dfn>lista encadeada</dfn>. Uma lista encadeada é uma coleção linear de elementos de dados, chamados "nós". Cada um destes nós aponta para o próximo. Cada <dfn>nó</dfn> em uma lista encadeada contém duas informações importantes: o `element` em si e uma referência ao próximo `node` (nó).
Imagine that you are in a conga line. You have your hands on the next person in the line, and the person behind you has their hands on you. You can see the person straight ahead of you, but they are blocking the view of the other people ahead in line. A node is just like a person in a conga line: they know who they are and they can only see the next person in line, but they are not aware of the other people ahead or behind them.
Imagine que está em uma fila de dançarinos de conga. Suas mãos estão sobre a próxima pessoa na fila e a pessoa que está atrás de você tem as mãos sobre você. Você pode ver a pessoa diretamente à sua frente, mas ela está bloqueando a vista das outras pessoas na frente dela. Um nó é como uma pessoa em uma fila de dançarinos de conga: eles sabem quem eles são e só podem ver a próxima pessoa na fila, mas não conhecem as outras pessoas à frente ou atrás delas.
# --instructions--
In our code editor, we've created two nodes, `Kitten` and `Puppy`, and we've manually connected the `Kitten` node to the `Puppy` node.
No nosso editor de código, criamos dois nós, `Kitten` e `Puppy`, e conectamos manualmente o nó `Kitten` com o nó `Puppy`.
Create a `Cat` and `Dog` node and manually add them to the line.
Crie um nó de `Cat` e um nó `Dog` e adicione-os manualmente à lista.
# --hints--
Your `Puppy` node should have a reference to a `Cat` node.
O nó `Puppy` deve ter uma referência a um nó `Cat`.
```js
assert(Puppy.next.element === 'Cat');
```
Your `Cat` node should have a reference to a `Dog` node.
O nó `Cat` deve ter uma referência a um nó `Dog`.
```js
assert(Cat.next.element === 'Dog');

View File

@ -1,6 +1,6 @@
---
id: 5900f36e1000cf542c50fe80
title: 'Problem 1: Multiples of 3 and 5'
title: 'Problema 1: Múltiplos de 3 e 5'
challengeType: 5
forumTopicId: 301722
dashedName: problem-1-multiples-of-3-and-5
@ -8,37 +8,37 @@ dashedName: problem-1-multiples-of-3-and-5
# --description--
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Se listarmos todos os números naturais abaixo de 10 que são múltiplos de 3 ou 5, obteremos 3, 5, 6 e 9. A soma destes múltiplos é 23.
Find the sum of all the multiples of 3 or 5 below the provided parameter value `number`.
Calcule a soma de todos os múltiplos de 3 ou 5 menor que o parâmetro `number`.
# --hints--
`multiplesOf3and5(10)` should return a number.
`multiplesOf3and5(10)` deve retornar um número.
```js
assert(typeof multiplesOf3and5(10) === 'number');
```
`multiplesOf3and5(49)` should return 543.
`multiplesOf3and5(49)` deve retornar 543.
```js
assert.strictEqual(multiplesOf3and5(49), 543);
```
`multiplesOf3and5(1000)` should return 233168.
`multiplesOf3and5(1000)` deve retornar 233168.
```js
assert.strictEqual(multiplesOf3and5(1000), 233168);
```
`multiplesOf3and5(8456)` should return 16687353.
`multiplesOf3and5(8456)` deve retornar 16687353.
```js
assert.strictEqual(multiplesOf3and5(8456), 16687353);
```
`multiplesOf3and5(19564)` should return 89301183.
`multiplesOf3and5(19564)` deve retornar 89301183.
```js
assert.strictEqual(multiplesOf3and5(19564), 89301183);

View File

@ -1,6 +1,6 @@
---
id: 5900f3761000cf542c50fe89
title: 'Problem 10: Summation of primes'
title: 'Problema 10: Soma dos números primos'
challengeType: 5
forumTopicId: 301723
dashedName: problem-10-summation-of-primes
@ -8,37 +8,37 @@ dashedName: problem-10-summation-of-primes
# --description--
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
A soma dos números primos abaixo de 10 é 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below `n`.
Encontre a soma de todos os números primos abaixo de `n`.
# --hints--
`primeSummation(17)` should return a number.
`primeSummation(17)` deve retornar um número.
```js
assert(typeof primeSummation(17) === 'number');
```
`primeSummation(17)` should return 41.
`primeSummation(17)` deve retornar 41.
```js
assert.strictEqual(primeSummation(17), 41);
```
`primeSummation(2001)` should return 277050.
`primeSummation(2001)` deve retornar 277050.
```js
assert.strictEqual(primeSummation(2001), 277050);
```
`primeSummation(140759)` should return 873608362.
`primeSummation(140759)` deve retornar 873608362.
```js
assert.strictEqual(primeSummation(140759), 873608362);
```
`primeSummation(2000000)` should return 142913828922.
`primeSummation(2000000)` deve retornar 142913828922.
```js
assert.strictEqual(primeSummation(2000000), 142913828922);

View File

@ -1,6 +1,6 @@
---
id: 5900f3781000cf542c50fe8a
title: 'Problem 11: Largest product in a grid'
title: 'Problema 11: Maior produto em uma grade'
challengeType: 5
forumTopicId: 301734
dashedName: problem-11-largest-product-in-a-grid
@ -8,7 +8,7 @@ dashedName: problem-11-largest-product-in-a-grid
# --description--
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
Na grade 20×20 abaixo, quatro números ao longo de uma linha diagonal foram marcados em vermelho.
<div style='text-align: center;'>
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08<br>
@ -33,25 +33,25 @@ In the 20×20 grid below, four numbers along a diagonal line have been marked in
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48<br>
</div>
The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
O produto desses números é 26 × 63 × 78 × 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in a given `arr` grid?
Qual é o maior produto de quatro números adjacentes (próximos) na mesma direção (cima, baixo, esquerda, direita ou diagonal) na grade fornecida através do parâmetro `arr`?
# --hints--
`largestGridProduct(testGrid)` should return a number.
`largestGridProduct(testGrid)` deve retornar um número.
```js
assert(typeof largestGridProduct(testGrid) === 'number');
```
`largestGridProduct(testGrid)` should return 14169081.
`largestGridProduct(testGrid)` deve retornar 14169081.
```js
assert.strictEqual(largestGridProduct(testGrid), 14169081);
```
`largestGridProduct(grid)` should return 70600674.
`largestGridProduct(grid)` deve retornar 70600674.
```js
assert.strictEqual(largestGridProduct(grid), 70600674);

View File

@ -1,6 +1,6 @@
---
id: 5900f3781000cf542c50fe8b
title: 'Problem 12: Highly divisible triangular number'
title: 'Problema 12: Maior número triangular divisível'
challengeType: 5
forumTopicId: 301746
dashedName: problem-12-highly-divisible-triangular-number
@ -8,57 +8,57 @@ dashedName: problem-12-highly-divisible-triangular-number
# --description--
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
A sequência de números de triângulos é gerada pela adição de números naturais. Portanto, o número do 7º triângulo é 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Os primeiros dez termos seriam:
<div style='text-align: center;'>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...</div>
Let us list the factors of the first seven triangle numbers:
Abaixo está a lista dos 7 primeiros números do triângulo:
<div style='padding-left: 4em;'><b>1:</b> 1</div>
<div style='padding-left: 4em;'><b>3:</b> 1, 3</div>
<div style='padding-left: 4em;'><b>6:</b> 1, 2, 3, 6</div>
<div style='padding-left: 4em;'><b>10:</b> 1, 2, 5, 10</div>
<div style='padding-left: 4em;'><b>15:</b> 1, 3, 5, 15</div>
<div style='padding-left: 4em;'><b>21:</b> 1, 3, 7, 21</div>
<div style='padding-left: 4em;'><b>71:</b> 1, 2, 3, 21</div>
<div style='padding-left: 4em;'><b>28:</b> 1, 2, 4, 7, 14, 28</div>
We can see that 28 is the first triangle number to have over five divisors.
Podemos ver que 28 é o primeiro triângulo a ter mais de cinco divisores.
What is the value of the first triangle number to have over `n` divisors?
Qual é o valor do primeiro triângulo a ter mais de `n` divisores?
# --hints--
`divisibleTriangleNumber(5)` should return a number.
`divisibleTriangleNumber(5)` deve retornar um número.
```js
assert(typeof divisibleTriangleNumber(5) === 'number');
```
`divisibleTriangleNumber(5)` should return 28.
`divisibleTriangleNumber(5)` deve retornar 28.
```js
assert.strictEqual(divisibleTriangleNumber(5), 28);
```
`divisibleTriangleNumber(23)` should return 630.
`divisibleTriangleNumber(23)` deve retornar 630.
```js
assert.strictEqual(divisibleTriangleNumber(23), 630);
```
`divisibleTriangleNumber(167)` should return 1385280.
`divisibleTriangleNumber(167)` deve retornar 1385280.
```js
assert.strictEqual(divisibleTriangleNumber(167), 1385280);
```
`divisibleTriangleNumber(374)` should return 17907120.
`divisibleTriangleNumber(374)` deve retornar 17907120.
```js
assert.strictEqual(divisibleTriangleNumber(374), 17907120);
```
`divisibleTriangleNumber(500)` should return 76576500.
`divisibleTriangleNumber(500)` deve retornar 76576500.
```js
assert.strictEqual(divisibleTriangleNumber(500), 76576500);

View File

@ -1,6 +1,6 @@
---
id: 5900f36e1000cf542c50fe81
title: 'Problem 2: Even Fibonacci Numbers'
title: 'Problema 2: Apenas números pares da sequência de Fibonacci'
challengeType: 5
forumTopicId: 301838
dashedName: problem-2-even-fibonacci-numbers
@ -8,63 +8,63 @@ dashedName: problem-2-even-fibonacci-numbers
# --description--
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
Cada novo número na sequência de Fibonacci é gerado pela soma dos dois números anteriores. Ao começar com 1 e 2, os primeiros 10 números serão:
<div style='text-align: center;'>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</div>
By considering the terms in the Fibonacci sequence whose values do not exceed `n`, find the sum of the even-valued terms.
Considerando os números na sequência de Fibonacci cujos valores não excedem `n`, encontre a soma dos números pares.
# --hints--
`fiboEvenSum(10)` should return a number.
`fiboEvenSum(10)` deve retornar um número.
```js
assert(typeof fiboEvenSum(10) === 'number');
```
Your function should return an `even` value.
A função deve retornar um valor par (`even`).
```js
assert.equal(fiboEvenSum(10) % 2 === 0, true);
```
Your function should sum the even-valued Fibonacci numbers: `fiboEvenSum(8)` should return 10.
A função deve somar os números pares de Fibonacci: `fiboEvenSum(8)` deve retornar 10.
```js
assert.strictEqual(fiboEvenSum(8), 10);
```
`fiboEvenSum(10)` should return 10.
`fiboEvenSum(10)` deve retornar 10.
```js
assert.strictEqual(fiboEvenSum(10), 10);
```
`fiboEvenSum(34)` should return 44.
`fiboEvenSum(34)` deve retornar 44.
```js
assert.strictEqual(fiboEvenSum(34), 44);
```
`fiboEvenSum(60)` should return 44.
`fiboEvenSum(60)` deve retornar 44.
```js
assert.strictEqual(fiboEvenSum(60), 44);
```
`fiboEvenSum(1000)` should return 798.
`fiboEvenSum(1000)` deve retornar 798.
```js
assert.strictEqual(fiboEvenSum(1000), 798);
```
`fiboEvenSum(100000)` should return 60696.
`fiboEvenSum(100000)` deve retornar 60696.
```js
assert.strictEqual(fiboEvenSum(100000), 60696);
```
`fiboEvenSum(4000000)` should return 4613732.
`fiboEvenSum(4000000)` deve retornar 4613732.
```js
assert.strictEqual(fiboEvenSum(4000000), 4613732);

View File

@ -1,6 +1,6 @@
---
id: 5900f36f1000cf542c50fe82
title: 'Problem 3: Largest prime factor'
title: 'Problema 3: Maior fator primo'
challengeType: 5
forumTopicId: 301952
dashedName: problem-3-largest-prime-factor
@ -8,55 +8,55 @@ dashedName: problem-3-largest-prime-factor
# --description--
The prime factors of 13195 are 5, 7, 13 and 29.
Os fatores primos de 13195 são 5, 7, 13 e 29.
What is the largest prime factor of the given `number`?
Qual é o maior fator primo do parâmetro `number`?
# --hints--
`largestPrimeFactor(2)` should return a number.
`largestPrimeFactor(2)` deve retornar um número.
```js
assert(typeof largestPrimeFactor(2) === 'number');
```
`largestPrimeFactor(2)` should return 2.
`largestPrimeFactor(2)` deve retornar 2.
```js
assert.strictEqual(largestPrimeFactor(2), 2);
```
`largestPrimeFactor(3)` should return 3.
`largestPrimeFactor(3)` deve retornar 3.
```js
assert.strictEqual(largestPrimeFactor(3), 3);
```
`largestPrimeFactor(5)` should return 5.
`largestPrimeFactor(5)` deve retornar 5.
```js
assert.strictEqual(largestPrimeFactor(5), 5);
```
`largestPrimeFactor(7)` should return 7.
`largestPrimeFactor(7)` deve retornar 7.
```js
assert.strictEqual(largestPrimeFactor(7), 7);
```
`largestPrimeFactor(8)` should return 2.
`largestPrimeFactor(8)` deve retornar 2.
```js
assert.strictEqual(largestPrimeFactor(8), 2);
```
`largestPrimeFactor(13195)` should return 29.
`largestPrimeFactor(13195)` deve retornar 29.
```js
assert.strictEqual(largestPrimeFactor(13195), 29);
```
`largestPrimeFactor(600851475143)` should return 6857.
`largestPrimeFactor(600851475143)` deve retornar 6857.
```js
assert.strictEqual(largestPrimeFactor(600851475143), 6857);

View File

@ -1,6 +1,6 @@
---
id: 5900f3701000cf542c50fe83
title: 'Problem 4: Largest palindrome product'
title: 'Problema 4: Maior palíndromo de um produto'
challengeType: 5
forumTopicId: 302065
dashedName: problem-4-largest-palindrome-product
@ -8,25 +8,25 @@ dashedName: problem-4-largest-palindrome-product
# --description--
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Um número palíndromo é aquele que pode ser lido da esquerda para a direita e vice-versa. O maior palíndromo feito a partir do produto de dois algarismos é 9009 = 91 × 99.
Find the largest palindrome made from the product of two `n`-digit numbers.
Encontre o maior palíndromo feito a partir do produto de dois números de `n` dígitos.
# --hints--
`largestPalindromeProduct(2)` should return a number.
`largestPalindromeProduct(2)` deve retornar um número.
```js
assert(typeof largestPalindromeProduct(2) === 'number');
```
`largestPalindromeProduct(2)` should return 9009.
`largestPalindromeProduct(2)` deve retornar 9009.
```js
assert.strictEqual(largestPalindromeProduct(2), 9009);
```
`largestPalindromeProduct(3)` should return 906609.
`largestPalindromeProduct(3)` deve retornar 906609.
```js
assert.strictEqual(largestPalindromeProduct(3), 906609);

View File

@ -1,6 +1,6 @@
---
id: 5900f3711000cf542c50fe84
title: 'Problem 5: Smallest multiple'
title: 'Problema 5: Menor múltiplo'
challengeType: 5
forumTopicId: 302160
dashedName: problem-5-smallest-multiple
@ -8,43 +8,43 @@ dashedName: problem-5-smallest-multiple
# --description--
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
2520 é o menor número que pode ser dividido por cada um dos números entre 1 e 10, sem nenhum resto.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to `n`?
Qual é o menor número positivo que é igualmente divisível por todos os números de 1 a `n`?
# --hints--
`smallestMult(5)` should return a number.
`smallestMult(5)` deve retornar um número.
```js
assert(typeof smallestMult(5) === 'number');
```
`smallestMult(5)` should return 60.
`smallestMult(5)` deve retornar 60.
```js
assert.strictEqual(smallestMult(5), 60);
```
`smallestMult(7)` should return 420.
`smallestMult(7)` deve retornar 420.
```js
assert.strictEqual(smallestMult(7), 420);
```
`smallestMult(10)` should return 2520.
`smallestMult(10)` deve retornar 2520.
```js
assert.strictEqual(smallestMult(10), 2520);
```
`smallestMult(13)` should return 360360.
`smallestMult(13)` deve retornar 360360.
```js
assert.strictEqual(smallestMult(13), 360360);
```
`smallestMult(20)` should return 232792560.
`smallestMult(20)` deve retornar 232792560.
```js
assert.strictEqual(smallestMult(20), 232792560);

View File

@ -1,6 +1,6 @@
---
id: 5900f3721000cf542c50fe85
title: 'Problem 6: Sum square difference'
title: 'Problema 6: Diferença da soma dos quadrados'
challengeType: 5
forumTopicId: 302171
dashedName: problem-6-sum-square-difference
@ -8,39 +8,39 @@ dashedName: problem-6-sum-square-difference
# --description--
The sum of the squares of the first ten natural numbers is,
A soma dos quadrados dos primeiros dez números naturais é,
<div style='text-align: center;'>1<sup>2</sup> + 2<sup>2</sup> + ... + 10<sup>2</sup> = 385</div>
The square of the sum of the first ten natural numbers is,
O quadrado da soma dos primeiros dez números naturais é,
<div style='text-align: center;'>(1 + 2 + ... + 10)<sup>2</sup> = 55<sup>2</sup> = 3025</div>
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.
Por isso, a diferença entre a soma dos quadrados dos primeiros dez números naturais e o quadrado da soma é 3025 385 = 2640.
Find the difference between the sum of the squares of the first `n` natural numbers and the square of the sum.
Calcule a diferença entre a soma dos quadrados dos primeiros `n` números naturais e o quadrado da soma.
# --hints--
`sumSquareDifference(10)` should return a number.
`sumSquareDifference(10)` deve retornar um número.
```js
assert(typeof sumSquareDifference(10) === 'number');
```
`sumSquareDifference(10)` should return 2640.
`sumSquareDifference(10)` deve retornar 2640.
```js
assert.strictEqual(sumSquareDifference(10), 2640);
```
`sumSquareDifference(20)` should return 41230.
`sumSquareDifference(20)` deve retornar 41230.
```js
assert.strictEqual(sumSquareDifference(20), 41230);
```
`sumSquareDifference(100)` should return 25164150.
`sumSquareDifference(100)` deve retornar 25164150.
```js
assert.strictEqual(sumSquareDifference(100), 25164150);

View File

@ -1,6 +1,6 @@
---
id: 5900f3731000cf542c50fe86
title: 'Problem 7: 10001st prime'
title: 'Problema 7: 10001º número primo'
challengeType: 5
forumTopicId: 302182
dashedName: problem-7-10001st-prime
@ -8,43 +8,43 @@ dashedName: problem-7-10001st-prime
# --description--
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
Ao listar os primeiros seis números primos: 2, 3, 5, 7, 11 e 13, podemos ver que o sexto número primo é 13.
What is the `n`th prime number?
Qual é o `n`-ésimo número primo?
# --hints--
`nthPrime(6)` should return a number.
`nthPrime(6)` deve retornar um número.
```js
assert(typeof nthPrime(6) === 'number');
```
`nthPrime(6)` should return 13.
`nthPrime(6)` deve retornar 13.
```js
assert.strictEqual(nthPrime(6), 13);
```
`nthPrime(10)` should return 29.
`nthPrime(10)` deve retornar 29.
```js
assert.strictEqual(nthPrime(10), 29);
```
`nthPrime(100)` should return 541.
`nthPrime(100)` deve retornar 541.
```js
assert.strictEqual(nthPrime(100), 541);
```
`nthPrime(1000)` should return 7919.
`nthPrime(1000)` deve retornar 7919.
```js
assert.strictEqual(nthPrime(1000), 7919);
```
`nthPrime(10001)` should return 104743.
`nthPrime(10001)` deve retornar 104743.
```js
assert.strictEqual(nthPrime(10001), 104743);

View File

@ -1,6 +1,6 @@
---
id: 5900f3741000cf542c50fe87
title: 'Problem 8: Largest product in a series'
title: 'Problema 8: Maior produto em uma série'
challengeType: 5
forumTopicId: 302193
dashedName: problem-8-largest-product-in-a-series
@ -8,7 +8,7 @@ dashedName: problem-8-largest-product-in-a-series
# --description--
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
O número abaixo possui 1000 algarismos. Se você pegar, em ordem, 4 algarismos quaisquer, o maior produto que você vai encontrar é 9 × 9 × 8 × 9 = 5832.
<div style='text-align: center;'>73167176531330624919225119674426574742355349194934</div>
<div style='text-align: center;'>96983520312774506326239578318016984801869478851843</div>
@ -31,23 +31,23 @@ The four adjacent digits in the 1000-digit number that have the greatest product
<div style='text-align: center;'>05886116467109405077541002256983155200055935729725</div>
<div style='text-align: center;'>71636269561882670428252483600823257530420752963450</div>
Find the `n` adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
Encontre os `n` algarismos adjacentes no número de 1000 algarismos que têm o maior produto. Qual é o valor do produto?
# --hints--
`largestProductinaSeries(4)` should return a number.
`largestProductinaSeries(4)` deve retornar um número.
```js
assert(typeof largestProductinaSeries(4) === 'number');
```
`largestProductinaSeries(4)` should return 5832.
`largestProductinaSeries(4)` deve retornar 5832.
```js
assert.strictEqual(largestProductinaSeries(4), 5832);
```
`largestProductinaSeries(13)` should return 23514624000.
`largestProductinaSeries(13)` deve retornar 23514624000.
```js
assert.strictEqual(largestProductinaSeries(13), 23514624000);

View File

@ -1,6 +1,6 @@
---
id: 5900f3761000cf542c50fe88
title: 'Problem 9: Special Pythagorean triplet'
title: 'Problema 9: Terno pitagórico especial'
challengeType: 5
forumTopicId: 302205
dashedName: problem-9-special-pythagorean-triplet
@ -8,35 +8,35 @@ dashedName: problem-9-special-pythagorean-triplet
# --description--
A Pythagorean triplet is a set of three natural numbers, `a` &lt; `b` &lt; `c`, for which,
Um terno pitagórico é um conjunto de três números naturais, `a` &lt; `b` &lt; `c` tal que
<div style='text-align: center;'><var>a</var><sup>2</sup> + <var>b</var><sup>2</sup> = <var>c</var><sup>2</sup></div>
For example, 3<sup>2</sup> + 4<sup>2</sup> = 9 + 16 = 25 = 5<sup>2</sup>.
Por exemplo, 3<sup>2</sup> + 4<sup>2</sup> = 9 + 16 = 25 = 5<sup>2</sup>.
There exists exactly one Pythagorean triplet for which `a` + `b` + `c` = 1000. Find the product `abc` such that `a` + `b` + `c` = `n`.
Há exatamente um terno pitagórico para o qual `a` + `b` + `c` = 1000. Encontre o produto `abc` tal que `a` + `b` + `c` = `n`.
# --hints--
`specialPythagoreanTriplet(24)` should return a number.
`specialPythagoreanTriplet(24)` deve retornar um número.
```js
assert(typeof specialPythagoreanTriplet(24) === 'number');
```
`specialPythagoreanTriplet(24)` should return 480.
`specialPythagoreanTriplet(24)` deve retornar 480.
```js
assert.strictEqual(specialPythagoreanTriplet(24), 480);
```
`specialPythagoreanTriplet(120)` should return 49920, 55080 or 60000
`specialPythagoreanTriplet(120)` deve retornar 49920, 55080 ou 60000
```js
assert([49920, 55080, 60000].includes(specialPythagoreanTriplet(120)));
```
`specialPythagoreanTriplet(1000)` should return 31875000.
`specialPythagoreanTriplet(1000)` deve retornar 31875000.
```js
assert.strictEqual(specialPythagoreanTriplet(1000), 31875000);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acb
title: 100 doors
title: 100 portas
challengeType: 5
forumTopicId: 302217
dashedName: 100-doors
@ -8,27 +8,27 @@ dashedName: 100-doors
# --description--
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and 'toggle' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (i.e., door #2, #4, #6, ...) and toggle it. The third time, visit every 3rd door (i.e., door #3, #6, #9, ...), etc., until you only visit the 100th door.
Há 100 portas seguidas que estão todas fechadas inicialmente. Você faz 100 passagens pelas portas. A primeira vez que passar, visite todas as portas e 'alterne' a porta (se a porta estiver fechada, abra-a; se estiver aberta, feche-a). Na segunda vez, só visite as portas pares (ou seja, as porta 2, 4, 6, ...) e alterne-as. Na terceira vez, visite as portas de 3 em 3 (por exemplo, as portas 3, 6, 9, ...), até que você só visite a porta 100.
# --instructions--
Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.
Implemente uma função para determinar o estado das portas após a último passagem. Retorne o resultado final em um array, com o número da porta incluído no array apenas se ela estiver aberta.
# --hints--
`getFinalOpenedDoors` should be a function.
`getFinalOpenedDoors` deve ser uma função.
```js
assert(typeof getFinalOpenedDoors === 'function');
```
`getFinalOpenedDoors` should return an array.
`getFinalOpenedDoors` deve retornar um array.
```js
assert(Array.isArray(getFinalOpenedDoors(100)));
```
`getFinalOpenedDoors` should produce the correct result.
`getFinalOpenedDoors` deve produzir o resultado correto.
```js
assert.deepEqual(getFinalOpenedDoors(100), solution);

View File

@ -1,6 +1,6 @@
---
id: 5951e88f64ebf159166a1176
title: 24 game
title: Jogo dos 24
challengeType: 5
forumTopicId: 302218
dashedName: 24-game
@ -8,23 +8,23 @@ dashedName: 24-game
# --description--
The [24 Game](https://en.wikipedia.org/wiki/24_Game) tests a person's mental arithmetic.
O [Jogo dos 24](https://en.wikipedia.org/wiki/24_Game) testa a aritmética mental das pessoas.
The aim of the game is to arrange four numbers in a way that when evaluated, the result is 24
O objetivo do jogo é organizar quatro números de maneira que, quando avaliados, o resultado seja 24
# --instructions--
Implement a function that takes a string of four digits as its argument, with each digit from 1 to 9 (inclusive) with repetitions allowed, and returns an arithmetic expression that evaluates to the number 24. If no such solution exists, return "no solution exists".
Implemente uma função que receba uma string de quatro algarismos como argumento, com cada algarismo de 1 a 9 (inclusive), com repetições permitidas, e que retorne uma expressão aritmética que avalie como chegar ao número 24. Se essa solução não existir, retorne "no solution exists".
**Rules:**
**Regras:**
<ul>
<li> Only the following operators/functions are allowed: multiplication, division, addition, subtraction. </li>
<li> Division should use floating point or rational arithmetic, etc, to preserve remainders. </li>
<li> Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). </li>
<li> The order of the digits when given does not have to be preserved. </li>
<li> Apenas os operadores/funções seguintes são permitidos: multiplicação, divisão, adição, subtração. </li>
<li> A divisão deve usar o ponto flutuante ou a aritmética de racionais, etc., para preservar os restos. </li>
<li> Formar números com mais de um dígito a partir dos que foram fornecidos não é permitido. (Portanto, uma resposta de 12+12 quando for fornecido 1, 2, 2 e 1 está errada). </li>
<li> A ordem dos dígitos fornecida não precisa ser preservada. </li>
</ul>
| Example input | Example output |
| Exemplo de entrada | Exemplo de saída |
| ------------------------- | ------------------------- |
| <code>solve24("4878");</code> | <code>(7-8/8)\*4</code> |
| <code>solve24("1234");</code> | <code>3\*1\*4\*2</code> |
@ -33,31 +33,31 @@ Implement a function that takes a string of four digits as its argument, with ea
# --hints--
`solve24` should be a function.
`solve24` deve ser uma função.
```js
assert(typeof solve24 === 'function');
```
`solve24("4878")` should return `(7-8/8)*4` or `4*(7-8/8)`
`solve24("4878")` deve retornar `(7-8/8)*4` ou `4*(7-8/8)`
```js
assert(include(answers[0], removeParentheses(solve24(testCases[0]))));
```
`solve24("1234")` should return any arrangement of `1*2*3*4`
`solve24("1234")` deve retornar qualquer combinação de `1*2*3*4`
```js
assert(include(answers[1], removeParentheses(solve24(testCases[1]))));
```
`solve24("6789")` should return `(6*8)/(9-7)` or `(8*6)/(9-7)`
`solve24("6789")` deve retornar `(6*8)/(9-7)` ou `(8*6)/(9-7)`
```js
assert(include(answers[2], removeParentheses(solve24(testCases[2]))));
```
`solve24("1127")` should return a permutation of `(1+7)*(1+2)`
`solve24("1127")` deve retornar uma permutação de `(1+7)*(1+2)`
```js
assert(include(answers[3], removeParentheses(solve24(testCases[3]))));

View File

@ -1,6 +1,6 @@
---
id: 5949b579404977fbaefcd736
title: 9 billion names of God the integer
title: 9 bilhões de nomes de Deus, o inteiro
challengeType: 5
forumTopicId: 302219
dashedName: 9-billion-names-of-god-the-integer
@ -8,21 +8,21 @@ dashedName: 9-billion-names-of-god-the-integer
# --description--
This task is a variation of the [short story by Arthur C. Clarke](https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary "wp: The Nine Billion Names of God#Plot_summary").
Esta tarefa é uma variação do [conto escrito por Arthur C. Clarke](https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary "wp: The Nine Billion Names of God#Plot_summary").
(Solvers should be aware of the consequences of completing this task.)
(Quem chegar à solução deve estar ciente das consequências de concluir esta tarefa.)
In detail, to specify what is meant by a "name":
Em detalhes, para especificar o que significa um "nome":
<ul>
<li>The integer 1 has 1 name "1".</li>
<li>The integer 2 has 2 names "1+1" and "2".</li>
<li>The integer 3 has 3 names "1+1+1", "2+1", and "3".</li>
<li>The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".</li>
<li>The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".</li>
<li>O inteiro 1 tem 1 nome: "1".</li>
<li>O inteiro 2 tem 2 nomes: "1+1" e "2".</li>
<li>O inteiro 3 tem 3 nomes: "1+1+1", "2+1" e "3".</li>
<li>O inteiro 4 tem 5 nomes: "1+1+1+1", "2+1+1", "2+2", "3+1", "4".</li>
<li>O inteiro 5 tem 7 nomes: "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".</li>
</ul>
This can be visualized in the following form:
Isto pode ser visualizado do seguinte modo:
<pre> 1
1 1
@ -32,53 +32,53 @@ This can be visualized in the following form:
1 3 3 2 1 1
</pre>
Where row $n$ corresponds to integer $n$, and each column $C$ in row $m$ from left to right corresponds to the number of names beginning with $C$.
Onde a linha $n$ corresponde ao inteiro $n$ e cada coluna $C$ na linha $m$ da esquerda para a direita corresponde ao número de nomes que começam com $C$.
Optionally note that the sum of the $n$-th row $P(n)$ is the integer partition function.
Como opção, note que a soma da $n$-ésima linha $P(n)$ é a função de partição de inteiros.
# --instructions--
Implement a function that returns the sum of the $n$-th row.
Implemente uma função que retorna a soma da $n$-ésima linha.
# --hints--
`numberOfNames` should be function.
`numberOfNames` deve ser uma função.
```js
assert(typeof numberOfNames === 'function');
```
`numberOfNames(5)` should equal 7.
`numberOfNames(5)` deve ser igual a 7.
```js
assert.equal(numberOfNames(5), 7);
```
`numberOfNames(12)` should equal 77.
`numberOfNames(12)` deve ser igual a 77.
```js
assert.equal(numberOfNames(12), 77);
```
`numberOfNames(18)` should equal 385.
`numberOfNames(18)` deve ser igual a 385.
```js
assert.equal(numberOfNames(18), 385);
```
`numberOfNames(23)` should equal 1255.
`numberOfNames(23)` deve ser igual a 1255.
```js
assert.equal(numberOfNames(23), 1255);
```
`numberOfNames(42)` should equal 53174.
`numberOfNames(42)` deve ser igual a 53174.
```js
assert.equal(numberOfNames(42), 53174);
```
`numberOfNames(123)` should equal 2552338241.
`numberOfNames(123)` deve ser igual a 2552338241.
```js
assert.equal(numberOfNames(123), 2552338241);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acc
title: ABC Problem
title: Problema do ABC
challengeType: 5
forumTopicId: 302220
dashedName: abc-problem
@ -8,7 +8,7 @@ dashedName: abc-problem
# --description--
You are given a collection of ABC blocks (e.g., childhood alphabet blocks). There are 20 blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:
Você recebe uma coleção de blocos ABC (por exemplo, blocos de alfabeto de infância). Há 20 blocos com duas letras em cada bloco. Um alfabeto completo é garantido entre todos os lados dos blocos. A coleção de amostra de blocos:
<pre>(B O)
(X K)
@ -34,60 +34,60 @@ You are given a collection of ABC blocks (e.g., childhood alphabet blocks). Ther
# --instructions--
Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
Implemente uma função que recebe uma string (palavra) e determina se a palavra pode ser escrita com a coleção de blocos fornecida.
Some rules to keep in mind:
Algumas regras para se ter em mente:
<ul>
<li>Once a letter on a block is used, that block cannot be used again.</li>
<li>The function should be case-insensitive.</li>
<li>Quando uma letra em um bloco é usada, esse bloco não pode ser usado novamente.</li>
<li>A função não deve distinguir maiúsculas e minúsculas.</li>
</ul>
# --hints--
`canMakeWord` should be a function.
`canMakeWord` deve ser uma função.
```js
assert(typeof canMakeWord === 'function');
```
`canMakeWord` should return a boolean.
`canMakeWord` deve retornar um booleano.
```js
assert(typeof canMakeWord('hi') === 'boolean');
```
`canMakeWord("bark")` should return true.
`canMakeWord("bark")` deve retornar true.
```js
assert(canMakeWord(words[0]));
```
`canMakeWord("BooK")` should return false.
`canMakeWord("BooK")` deve retornar false.
```js
assert(!canMakeWord(words[1]));
```
`canMakeWord("TReAT")` should return true.
`canMakeWord("TReAT")` deve retornar true.
```js
assert(canMakeWord(words[2]));
```
`canMakeWord("COMMON")` should return false.
`canMakeWord("COMMON")` deve retornar false.
```js
assert(!canMakeWord(words[3]));
```
`canMakeWord("squAD")` should return true.
`canMakeWord("squAD")` deve retornar true.
```js
assert(canMakeWord(words[4]));
```
`canMakeWord("conFUSE")` should return true.
`canMakeWord("conFUSE")` deve retornar true.
```js
assert(canMakeWord(words[5]));

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acd
title: 'Abundant, deficient and perfect number classifications'
title: 'Classificações de números abundantes, deficientes e perfeitos'
challengeType: 5
forumTopicId: 302221
dashedName: abundant-deficient-and-perfect-number-classifications
@ -8,55 +8,55 @@ dashedName: abundant-deficient-and-perfect-number-classifications
# --description--
These define three classifications of positive integers based on their proper divisors.
Estas classificações definem três categorias de inteiros positivos com base nos seus divisores.
Let $P(n)$ be the sum of the proper divisors of `n` where proper divisors are all positive integers `n` other than `n` itself.
Vamos considerar que $P(n)$ é a soma dos divisores apropriados de `n`, onde todos os divisores adequados são inteiros positivos `n` diferentes de `n`.
If `P(n) < n` then `n` is classed as `deficient`
Se `P(n) < n`, `n` é classificado como `deficient`
If `P(n) === n` then `n` is classed as `perfect`
Se `P(n) === n`, `n` é classificado como `perfect`
If `P(n) > n` then `n` is classed as `abundant`
Se `P(n) > n`, `n` é classificado como `abundant`
**Example**: `6` has proper divisors of `1`, `2`, and `3`. `1 + 2 + 3 = 6`, so `6` is classed as a perfect number.
**Exemplo**: `6` tem divisores adequados em `1`, `2`e `3`. `1 + 2 + 3 = 6`, então `6` é classificado como um número perfeito.
# --instructions--
Implement a function that calculates how many of the integers from `1` to `num` (inclusive) are in each of the three classes. Output the result as an array in the following format `[deficient, perfect, abundant]`.
Implementar uma função que calcule quantos números inteiros de `1` a `num` (inclusive) estão em cada uma das três classes. Exiba o resultado como um array no seguinte formato: `[deficient, perfect, abundant]`.
# --hints--
`getDPA` should be a function.
`getDPA` deve ser uma função.
```js
assert(typeof getDPA === 'function');
```
`getDPA(5000)` should return an array.
`getDPA(5000)` deve retornar um array.
```js
assert(Array.isArray(getDPA(5000)));
```
`getDPA(5000)` return array should have a length of `3`.
O array de retorno de `getDPA(5000)` deve ter tamanho `3`.
```js
assert(getDPA(5000).length === 3);
```
`getDPA(5000)` should return `[3758, 3, 1239]`.
`getDPA(5000)` deve retornar `[3758, 3, 1239]`.
```js
assert.deepEqual(getDPA(5000), [3758, 3, 1239]);
```
`getDPA(10000)` should return `[7508, 4, 2488]`.
`getDPA(10000)` deve retornar `[7508, 4, 2488]`.
```js
assert.deepEqual(getDPA(10000), [7508, 4, 2488]);
```
`getDPA(20000)` should return `[15043, 4, 4953]`.
`getDPA(20000)` deve retornar `[15043, 4, 4953]`.
```js
assert.deepEqual(getDPA(20000), [15043, 4, 4953]);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339ace
title: Accumulator factory
title: Fábrica de acumuladores
challengeType: 5
forumTopicId: 302222
dashedName: accumulator-factory
@ -8,41 +8,41 @@ dashedName: accumulator-factory
# --description--
A problem posed by [Paul Graham](https://en.wikipedia.org/wiki/Paul_Graham_(programmer)) is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Um problema proposto por [Paul Graham](https://en.wikipedia.org/wiki/Paul_Graham_(programmer)) é o de criar uma função que recebe um único argumento (numérico) e que retorna outra função que é um acumulador. A função de acumulador retornada, por sua vez, também recebe um único argumento numérico e retorna a soma de todos os valores numéricos passados até aquele momento para esse acumulador (incluindo o valor inicial passado quando o acumulador foi criado).
# --instructions--
Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them.
Crie uma função que receba um número $n$ e gere funções acumuladoras que retornam a soma de cada número já passado para elas.
**Rules:**
**Regras:**
Do not use global variables.
Não use variáveis globais.
**Hint:**
**Dica:**
Closures save outer state.
Closures salvam o estado externo.
# --hints--
`accumulator` should be a function.
`accumulator` deve ser uma função.
```js
assert(typeof accumulator === 'function');
```
`accumulator(0)` should return a function.
`accumulator(0)` deve retornar uma função.
```js
assert(typeof accumulator(0) === 'function');
```
`accumulator(0)(2)` should return a number.
`accumulator(0)(2)` deve retornar um número.
```js
assert(typeof accumulator(0)(2) === 'number');
```
Passing in the values 3, -4, 1.5, and 5 should return 5.5.
Ao passar os valores 3, -4, 1.5 e 5, o valor retornado deve ser 5.5.
```js
assert(testFn(5) === 5.5);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acf
title: Ackermann function
title: Função de Ackermann
challengeType: 5
forumTopicId: 302223
dashedName: ackermann-function
@ -8,45 +8,45 @@ dashedName: ackermann-function
# --description--
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
A função de Ackermann é um exemplo clássico de uma função recursiva, especialmente porque não é uma função recursiva primitiva. Ela cresce muito rapidamente em valor, assim como no tamanho da sua árvore de chamadas.
The Ackermann function is usually defined as follows:
A função de Ackermann é geralmente definida da seguinte forma:
$A(m, n) = \\begin{cases} n+1 & \\mbox{if } m = 0 \\\\ A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0. \\end{cases}$
Its arguments are never negative and it always terminates.
Os argumentos nunca são negativos e sempre terminam.
# --instructions--
Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.
Escreva uma função que retorne o valor de $A(m, n)$. A precisão arbitrária é a preferida aqui (já que a função cresce tão rapidamente), mas não é necessária.
# --hints--
`ack` should be a function.
`ack` deve ser uma função.
```js
assert(typeof ack === 'function');
```
`ack(0, 0)` should return 1.
`ack(0, 0)` deve retornar 1.
```js
assert(ack(0, 0) === 1);
```
`ack(1, 1)` should return 3.
`ack(1, 1)` deve retornar 3.
```js
assert(ack(1, 1) === 3);
```
`ack(2, 5)` should return 13.
`ack(2, 5)` deve retornar 13.
```js
assert(ack(2, 5) === 13);
```
`ack(3, 3)` should return 61.
`ack(3, 3)` deve retornar 61.
```js
assert(ack(3, 3) === 61);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339ad0
title: Align columns
title: Alinhar colunas
challengeType: 5
forumTopicId: 302224
dashedName: align-columns
@ -8,11 +8,11 @@ dashedName: align-columns
# --description--
Given an array of many lines, where fields within a line are delineated by a single `$` character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column.
Dado um array de muitas linhas, onde os campos dentro de uma linha são delineados por um único caractere `$`, escreva um programa que alinha cada coluna de campos, garantindo que as palavras em cada coluna estejam separadas por pelo menos um espaço. Além disso, permita que cada palavra em uma coluna seja deixada justificada à esquerda, justificada à direita ou justificada ao centro em sua coluna.
# --instructions--
Use the following text to test your programs:
Use o texto a seguir para testar seus programas:
```js
const testText = [
@ -29,16 +29,16 @@ const testText = [
];
```
**Note that:**
**Observe que:**
- The example input texts lines may, or may not, have trailing dollar characters.
- All columns should share the same alignment.
- Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
- Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal. Lines in it should be joined using new line character (`\n`).
- The minimum space between columns should be computed from the text and not hard-coded.
- It is not a requirement to add separating characters between or around columns.
- As linhas de textos de entrada de exemplo podem, ou não, ter caracteres de dólar à frente.
- Todas as colunas devem compartilhar o mesmo alinhamento.
- Caracteres de espaço consecutivos adjacentes produzidos ao final das linhas são insignificantes para os propósitos da tarefa.
- O texto de saída será visto em uma fonte monoespaçada em um editor de texto simples ou em um terminal básico. As linhas nele devem ser unidas usando o caractere de nova linha (`\n`).
- O espaço mínimo entre colunas deve ser calculado a partir do texto e não inserido no código de antemão.
- Não é um requisito adicionar caracteres separados entre ou em torno das colunas.
For example, one of the lines from the `testText`, after jusitifing to the right, left and center respectivelly:
Por exemplo, uma das linhas do `testText`, após justificar à direita, à esquerda e ao centro, respectivamente, será:
```js
' column are separated by at least one space.\n'
@ -48,25 +48,25 @@ For example, one of the lines from the `testText`, after jusitifing to the right
# --hints--
`formatText` should be a function.
`formatText` deve ser uma função.
```js
assert(typeof formatText === 'function');
```
`formatText(testText, 'right')` should produce text with columns justified to the right.
`formatText(testText, 'right')` deve produzir texto com colunas justificadas à direita.
```js
assert.strictEqual(formatText(_testText, 'right'), rightAligned);
```
`formatText(testText, 'left')` should produce text with columns justified to the left.
`formatText(testText, 'left')` deve produzir texto com colunas justificadas à esquerda.
```js
assert.strictEqual(formatText(_testText, 'left'), leftAligned);
```
`formatText(testText, 'center')` should produce text with columns justified to the center.
`formatText(testText, 'center')` deve produzir texto com colunas justificadas ao centro.
```js
assert.strictEqual(formatText(_testText, 'center'), centerAligned);

View File

@ -1,6 +1,6 @@
---
id: 5949b579404977fbaefcd737
title: Amicable pairs
title: Pares amigáveis
challengeType: 5
forumTopicId: 302225
dashedName: amicable-pairs
@ -8,42 +8,42 @@ dashedName: amicable-pairs
# --description--
Two integers $N$ and $M$ are said to be [amicable pairs](https://en.wikipedia.org/wiki/Amicable numbers "wp: Amicable numbers") if $N \\neq M$ and the sum of the [proper divisors](https://rosettacode.org/wiki/Proper divisors "Proper divisors") of $N$ ($\\mathrm{sum}(\\mathrm{propDivs}(N))$) $= M$ as well as $\\mathrm{sum}(\\mathrm{propDivs}(M)) = N$.
Dizem que dois inteiros $N$ e $M$ são [pares amigáveis](https://en.wikipedia.org/wiki/Amicable numbers "wp: Amicable numbers") se $N \\neq M$ e a soma dos [divisores adequados](https://rosettacode.org/wiki/Proper divisors "Proper divisors") de $N$ ($\\mathrm{sum}(\\mathrm{propDivs}(N))$) $= M$, bem como $\\mathrm{sum}(\\mathrm{propDivs}(M)) = N$.
**Example:**
**Exemplo:**
**1184** and **1210** are an amicable pair, with proper divisors:
**1184** e **1210** são um par amigável, com divisores adequados:
<ul>
<li>1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and</li>
<li>1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.</li>
<li>1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 e</li>
<li>1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605, respectivamente.</li>
</ul>
# --instructions--
Calculate and show here the Amicable pairs below 20,000 (there are eight).
Calcule e mostre aqui os pares amigáveis abaixo de 20.000 (há oito).
# --hints--
`amicablePairsUpTo` should be a function.
`amicablePairsUpTo` deve ser uma função.
```js
assert(typeof amicablePairsUpTo === 'function');
```
`amicablePairsUpTo(300)` should return `[[220,284]]`.
`amicablePairsUpTo(300)` deve retornar `[[220,284]]`.
```js
assert.deepEqual(amicablePairsUpTo(300), answer300);
```
`amicablePairsUpTo(3000)` should return `[[220,284],[1184,1210],[2620,2924]]`.
`amicablePairsUpTo(3000)` deve retornar `[[220,284],[1184,1210],[2620,2924]]`.
```js
assert.deepEqual(amicablePairsUpTo(3000), answer3000);
```
`amicablePairsUpTo(20000)` should return `[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]`.
`amicablePairsUpTo(20000)` deve retornar `[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]`.
```js
assert.deepEqual(amicablePairsUpTo(20000), answer20000);

View File

@ -1,6 +1,6 @@
---
id: 594d8d0ab97724821379b1e6
title: Averages/Mode
title: Médias/Moda
challengeType: 5
forumTopicId: 302226
dashedName: averagesmode
@ -8,27 +8,27 @@ dashedName: averagesmode
# --description--
Write a program to find the [mode](https://en.wikipedia.org/wiki/Mode (statistics) "wp: Mode (statistics)") value of a collection.
Escreva um programa que encontre o valor da [moda](https://en.wikipedia.org/wiki/Mode (statistics) "wp: Mode (statistics)") de uma coleção.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
O caso em que a coleção está vazia pode ser ignorado. É preciso ter cuidado para lidar com o caso em que a moda não é única.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
Se não for apropriado ou possível dar suporte a uma coleção geral, use um vetor (array), se possível. Se não é apropriado ou possível dar suporte a um tipo de valor não especificado, use números inteiros.
# --hints--
`mode` should be a function.
`mode` deve ser uma função.
```js
assert(typeof mode === 'function');
```
`mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])` should equal `[6]`
`mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])` deve ser igual a `[6]`
```js
assert.deepEqual(mode(arr1), [6]);
```
`mode([1, 2, 4, 4, 1])` should equal `[1, 4]`.
`mode([1, 2, 4, 4, 1])` deve ser igual a `[1, 4]`.
```js
assert.deepEqual(mode(arr2).sort(), [1, 4]);

View File

@ -1,6 +1,6 @@
---
id: 594d966a1467eb84194f0086
title: Averages/Pythagorean means
title: Média/Médias pitagóricas
challengeType: 5
forumTopicId: 302227
dashedName: averagespythagorean-means
@ -8,24 +8,24 @@ dashedName: averagespythagorean-means
# --description--
Compute all three of the [Pythagorean means](https://en.wikipedia.org/wiki/Pythagorean means "wp: Pythagorean means") of the set of integers $1$ through $10$ (inclusive).
Calcule as três [médias pitagóricas](https://en.wikipedia.org/wiki/Pythagorean means "wp: Pythagorean means") do conjunto de inteiros de $1$ a $10$ (inclusive).
Show that $A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$ for this set of positive integers.
Exiba $A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$ para este conjunto de inteiros positivos.
<ul>
<li>The most common of the three means, the <a class='rosetta__link--rosetta' href='https://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean' target='_blank'>arithmetic mean</a>, is the sum of the list divided by its length:<br>
<li>A mais comum das três médias, a <a class='rosetta__link--rosetta' href='https://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean' target='_blank'>média aritmética</a>, é a soma da lista dividida pelo seu tamanho:<br>
<big>$ A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n}$</big></li>
<li>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean' target='_blank'>geometric mean</a> is the $n$th root of the product of the list:<br>
<li>A <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean' target='_blank'>média geométrica</a> é a $n$-ésima raiz do produto da lista:<br>
<big>$ G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n} $</big></li>
<li>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean' target='_blank'>harmonic mean</a> is $n$ divided by the sum of the reciprocal of each item in the list:<br>
<li>A <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean' target='_blank'>média harmônica</a> é $n$ dividido pela soma dos recíprocos de cada item da lista:<br>
<big>$ H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} $</big></li>
</ul>
# --instructions--
When writing your function, assume the input is an ordered array of all inclusive numbers.
Ao escrever sua função, assuma que a entrada é um array ordenado incluindo todos os números.
For the answer, please output an object in the following format:
Para a resposta, dê como resultado um objeto com o seguinte formato:
```js
{
@ -40,13 +40,13 @@ For the answer, please output an object in the following format:
# --hints--
`pythagoreanMeans` should be a function.
`pythagoreanMeans` deve ser uma função.
```js
assert(typeof pythagoreanMeans === 'function');
```
`pythagoreanMeans([1, 2, ..., 10])` should equal the same output above.
`pythagoreanMeans([1, 2, ..., 10])` deve ser igual ao mesmo resultado acima.
```js
assert.deepEqual(pythagoreanMeans(range1), answer1);

View File

@ -1,6 +1,6 @@
---
id: 594da033de4190850b893874
title: Averages/Root mean square
title: Média/Valor eficaz
challengeType: 5
forumTopicId: 302228
dashedName: averagesroot-mean-square
@ -8,23 +8,23 @@ dashedName: averagesroot-mean-square
# --description--
Compute the [Root mean square](https://en.wikipedia.org/wiki/Root mean square "wp: Root mean square") of the numbers 1 through 10 inclusive.
Calcule o [vaor eficaz](https://en.wikipedia.org/wiki/Root mean square "wp: Root mean square") dos números de 1 a 10 inclusive.
The *root mean square* is also known by its initials RMS (or rms), and as the **quadratic mean**.
O *valor eficaz* (ou raiz do valor quadrático médio) também é conhecido por suas iniciais RMS (ou rms) e como **média quadrática**.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
O RMS é calculado como a raiz quadrada da média dos quadrados dos números:
$$x\_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. $$
$$x\_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\sobre n}. $$
# --hints--
`rms` should be a function.
`rms` deve ser uma função.
```js
assert(typeof rms === 'function');
```
`rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])` should equal `6.2048368229954285`.
`rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])` deve ser igual a `6.2048368229954285`.
```js
assert.equal(rms(arr1), answer1);

View File

@ -1,6 +1,6 @@
---
id: 594db4d0dedb4c06a2a4cefd
title: Babbage problem
title: Problema de Babbage
challengeType: 5
forumTopicId: 302229
dashedName: babbage-problem
@ -8,30 +8,30 @@ dashedName: babbage-problem
# --description--
[Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage "wp: Charles_Babbage"), looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
[Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage "wp: Charles_Babbage"), olhando para os tipos de problemas que seu mecanismo analítico poderia resolver, deu este exemplo:
<blockquote>
What is the smallest positive integer whose square ends in the digits 269,696?
<footer style='margin-left: 2em;'>Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, <i>Electronic Computers</i>, second edition, 1970, p. 125.</footer>
Qual é o menor inteiro positivo cujo quadrado termina nos dígitos 269.696?
<footer style='margin-left: 2em;'>Babbage, em carta ao Lord Bowden, 1837; veja Hollingdale e Tootill, <i>Electronic Computers</i>, segunda edição, 1970, p. 125.</footer>
</blockquote>
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Ele acreditava que a resposta seria 99.736, cujo quadrado é 9.947.269.696, mas ele não tinha certeza.
The task is to find out if Babbage had the right answer.
A tarefa é descobrir se Babbage achou a resposta certa.
# --instructions--
Implement a function to return the lowest integer that satisfies the Babbage problem. If Babbage was right, return Babbage's number.
Implemente uma função que retorna o menor inteiro que satisfaça o problema de Babbage. Se Babbage estava certo, retorne o número de Babbage.
# --hints--
`babbage` should be a function.
`babbage` deve ser uma função.
```js
assert(typeof babbage === 'function');
```
`babbage(99736, 269696)` should not return 99736 (there is a smaller answer).
`babbage(99736, 269696)` não deve retornar 99736 (existe uma resposta menor).
```js
assert.equal(babbage(babbageAns, endDigits), answer);

View File

@ -1,6 +1,6 @@
---
id: 594dc6c729e5700999302b45
title: Balanced brackets
title: Colchetes balanceados
challengeType: 5
forumTopicId: 302230
dashedName: balanced-brackets
@ -8,129 +8,129 @@ dashedName: balanced-brackets
# --description--
Determine whether a generated string of brackets is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Determine se uma sequência de colchetes gerada é equilibrada, ou seja, se consiste inteiramente de pares de colchetes de abertura/fechamento (nessa ordem), nenhum dos quais colocado incorretamente.
**Examples:**
| Input | Output |
| ------------------------- | ------ |
| <code>\[]</code> | true |
| <code>]\[</code> | false |
| <code>[][]</code> | true |
| <code>]\[]</code> | false |
| <code>\[]]\[\[]</code> | false |
| <code>\[\[\[\[]]]]</code> | true |
**Exemplos:**
| Entrada | Saída |
| ------------------------- | ----- |
| <code>\[]</code> | true |
| <code>]\[</code> | false |
| <code>[][]</code> | true |
| <code>]\[]</code> | false |
| <code>\[]]\[\[]</code> | false |
| <code>\[\[\[\[]]]]</code> | true |
# --hints--
`isBalanced` should be a function.
`isBalanced` deve ser uma função.
```js
assert(typeof isBalanced === 'function');
```
`isBalanced("[]")` should return true.
`isBalanced("[]")` deve retornar true.
```js
assert(isBalanced(testCases[0]));
```
`isBalanced("]][[[][][][]][")` should return false.
`isBalanced("]][[[][][][]][")` deve retornar false.
```js
assert(!isBalanced(testCases[1]));
```
`isBalanced("[][[[[][][[[]]]]]]")` should return true.
`isBalanced("[][[[[][][[[]]]]]]")` deve retornar true.
```js
assert(isBalanced(testCases[2]));
```
`isBalanced("][")` should return false.
`isBalanced("][")` deve retornar false.
```js
assert(!isBalanced(testCases[3]));
```
`isBalanced("[[[]]]][[]")` should return false.
`isBalanced("[[[]]]][[]")` deve retornar false.
```js
assert(!isBalanced(testCases[4]));
```
`isBalanced("][[]")` should return false.
`isBalanced("][[]")` deve retornar false.
```js
assert(!isBalanced(testCases[5]));
```
`isBalanced("][[][]][[[]]")` should return false.
`isBalanced("][[][]][[[]]")` deve retornar false.
```js
assert(!isBalanced(testCases[6]));
```
`isBalanced("[[][]]][")` should return false.
`isBalanced("[[][]]][")` deve retornar false.
```js
assert(!isBalanced(testCases[7]));
```
`isBalanced("[[[]]][[]]]][][[")` should return false.
`isBalanced("[[[]]][[]]]][][[")` deve retornar false.
```js
assert(!isBalanced(testCases[8]));
```
`isBalanced("[]][[]]][[[[][]]")` should return false.
`isBalanced("[]][[]]][[[[][]]")` deve retornar false.
```js
assert(!isBalanced(testCases[9]));
```
`isBalanced("][]][[][")` should return false.
`isBalanced("][]][[][")` deve retornar false.
```js
assert(!isBalanced(testCases[10]));
```
`isBalanced("[[]][[][]]")` should return true.
`isBalanced("[[]][[][]]")` deve retornar true.
```js
assert(isBalanced(testCases[11]));
```
`isBalanced("[[]]")` should return true.
`isBalanced("[[]]")` deve retornar true.
```js
assert(isBalanced(testCases[12]));
```
`isBalanced("]][]][[]][[[")` should return false.
`isBalanced("]][]][[]][[[")` deve retornar false.
```js
assert(!isBalanced(testCases[13]));
```
`isBalanced("][]][][[")` should return false.
`isBalanced("][]][][[")` deve retornar false.
```js
assert(!isBalanced(testCases[14]));
```
`isBalanced("][][")` should return false.
`isBalanced("][][")` deve retornar false.
```js
assert(!isBalanced(testCases[15]));
```
`isBalanced("[]]]")` should return false.
`isBalanced("[]]]")` deve retornar false.
```js
assert(!isBalanced(testCases[16]));
```
`isBalanced("")` should return true.
`isBalanced("")` deve retornar true.
```js
assert(isBalanced(testCases[17]));

View File

@ -1,6 +1,6 @@
---
id: 5951815dd895584b06884620
title: Circles of given radius through two points
title: Círculos de raio determinado através de dois pontos
challengeType: 5
forumTopicId: 302231
dashedName: circles-of-given-radius-through-two-points
@ -8,30 +8,30 @@ dashedName: circles-of-given-radius-through-two-points
# --description--
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Dados dois pontos em um plano e num raio, geralmente dois círculos de um determinado raio podem ser traçados através dos pontos.
**Exceptions:**
**Exceções:**
<ul>
<li>A radius of zero should be treated as never describing circles (except in the case where the points are coincident).</li>
<li>If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless the radius is equal to zero as well which then collapses the circles to a point.</li>
<li>If the points form a diameter then return a single circle.</li>
<li>If the points are too far apart then no circles can be drawn.</li>
<li>Um raio de zero deve ser tratado como nunca descrevendo círculos (exceto no caso em que os pontos são coincidentes).</li>
<li>Se os pontos forem coincidentes, pode haver um número infinito de círculos em que o ponto de sua circunferência pode ser desenhado, a não ser que o raio seja igual a zero, o que fará com que os círculos não passem de um ponto.</li>
<li>Se os pontos formarem um diâmetro, então retorne um único círculo.</li>
<li>Se os pontos estiverem muito distantes, não será possível desenhar os círculos.</li>
</ul>
# --instructions--
Implement a function that takes two points and a radius and returns the two circles through those points. For each resulting circle, provide the coordinates for the center of each circle rounded to four decimal digits. Return each coordinate as an array, and coordinates as an array of arrays.
Implementa uma função que recebe dois pontos e um raio e retorna os dois círculos através desses pontos. Para cada círculo resultante, forneça as coordenadas para o centro de cada círculo arredondadas para quatro casas decimais. Retorne cada coordenada como um array, e as coordenadas como um array de arrays.
**For edge cases, return the following:**
**Para casos extremos, retorne o seguinte:**
<ul>
<li>If points are on the diameter, return one point. If the radius is also zero however, return <code>"Radius Zero"</code>.</li>
<li>If points are coincident, return <code>"Coincident point. Infinite solutions"</code>.</li>
<li>If points are farther apart than the diameter, return <code>"No intersection. Points further apart than circle diameter"</code>.</li>
<li>Se os pontos estão no diâmetro, retorne um ponto. No entanto, se o raio também for zero, retorne <code>"Radius Zero"</code>.</li>
<li>Se os pontos forem coincidentes, retorne <code>"Coincident point. Infinite solutions"</code>.</li>
<li>Se os pontos estiverem mais distantes do que o diâmetro, retorne <code>"No intersection. Points further apart than circle diameter"</code>.</li>
</ul>
**Sample inputs:**
**Exemplo de entradas:**
<pre> p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
@ -43,37 +43,37 @@ Implement a function that takes two points and a radius and returns the two circ
# --hints--
`getCircles` should be a function.
`getCircles` deve ser uma função.
```js
assert(typeof getCircles === 'function');
```
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)` should return `[[1.8631, 1.9742], [-0.8632, -0.7521]]`.
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)` deve retornar `[[1.8631, 1.9742], [-0.8632, -0.7521]]`.
```js
assert.deepEqual(getCircles(...testCases[0]), answers[0]);
```
`getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)` should return `[0, 1]`
`getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)` deve retornar `[0, 1]`
```js
assert.deepEqual(getCircles(...testCases[1]), answers[1]);
```
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)` should return `Coincident point. Infinite solutions`
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)` deve retornar `Coincident point. Infinite solutions`
```js
assert.deepEqual(getCircles(...testCases[2]), answers[2]);
```
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)` should return `No intersection. Points further apart than circle diameter`
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)` deve retornar `No intersection. Points further apart than circle diameter`
```js
assert.deepEqual(getCircles(...testCases[3]), answers[3]);
```
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)` should return `Radius Zero`
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)` deve retornar `Radius Zero`
```js
assert.deepEqual(getCircles(...testCases[4]), answers[4]);

View File

@ -1,6 +1,6 @@
---
id: 5951a53863c8a34f02bf1bdc
title: Closest-pair problem
title: Problema do par mais próximo
challengeType: 5
forumTopicId: 302232
dashedName: closest-pair-problem
@ -8,66 +8,66 @@ dashedName: closest-pair-problem
# --description--
Provide a function to find the closest two points among a set of given points in two dimensions.
Forneça uma função para encontrar os dois pontos mais próximos entre um conjunto de pontos dados em duas dimensões.
The straightforward solution is a $O(n^2)$ algorithm (which we can call *brute-force algorithm*); the pseudo-code (using indexes) could be simply:
A solução simples é um algoritmo $O(n^2)$ (que podemos chamar de *algoritmo de força bruta*). O pseudocódigo (usando índices) poderia ser, simplesmente:
<pre><strong>bruteForceClosestPair</strong> of P(1), P(2), ... P(N)
<strong>if</strong> N &#x3C; 2 <strong>then</strong>
<strong>return</strong>
<strong>else</strong>
<pre><strong>bruteForceClosestPair</strong> de P(1), P(2), ... P(N)
<strong>se</strong> N &#x3C; 2 <strong>então</strong>
<strong>retorne</strong>
<strong>senão</strong>
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
<strong>foreach</strong> i ∈ [1, N-1]
<strong>foreach</strong> j ∈ [i+1, N]
<strong>if</strong> |P(i) - P(j)| &#x3C; minDistance <strong>then</strong>
<strong>paraCada</strong> i ∈ [1, N-1]
<strong>paraCada</strong> j ∈ [i+1, N]
<strong>se</strong> |P(i) - P(j)| &#x3C; minDistance <strong>então</strong>
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
<strong>endif</strong>
<strong>endfor</strong>
<strong>endfor</strong>
<strong>return</strong> minDistance, minPoints
<strong>endif</strong>
<strong>fimSe</strong>
<strong>fimPara</strong>
<strong>fimPara</strong>
<strong>retorne</strong> minDistance, minPoints
<strong>fimSe</strong>
</pre>
A better algorithm is based on the recursive divide and conquer approach, which is $O(n\log n)$ a pseudo-code could be:
Um algoritmo melhor com base na abordagem recursiva de dividir e conquistar, com complexidade $O(n\log n)$, teria, como pseudocódigo:
<pre><strong>closestPair</strong> of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
<strong>if</strong> N ≤ 3 <strong>then</strong>
<strong>return</strong> closest points of xP using brute-force algorithm
<strong>else</strong>
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
<pre><strong>closestPair</strong> de (xP, yP)
onde xP é P(1) .. P(N) ordenado pela coordenada x, e
yP é P(1) .. P(N) ordenado pela coordenada y (ordem ascendente)
<strong>se</strong> N ≤ 3 <strong>então</strong>
<strong>retorne</strong> pontos mais próximos de xP usando o algoritmo de força bruta
<strong>senão</strong>
xL ← pontos de xP de 1 a ⌈N/2⌉
xR ← pontos de xP de ⌈N/2⌉+1 a N
xm ← xP(⌈N/2⌉)<sub>x</sub>
yL ← { p ∈ yP : p<sub>x</sub> ≤ xm }
yR ← { p ∈ yP : p<sub>x</sub> > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dL, pairL) ← closestPair de (xL, yL)
(dR, pairR) ← closestPair de (xR, yR)
(dmin, pairMin) ← (dR, pairR)
<strong>if</strong> dL &#x3C; dR <strong>then</strong>
<strong>se</strong> dL &#x3C; dR <strong>então</strong>
(dmin, pairMin) ← (dL, pairL)
<strong>endif</strong>
<strong>fimSe</strong>
yS ← { p ∈ yP : |xm - p<sub>x</sub>| &#x3C; dmin }
nS ← number of points in yS
nS ← número de pontos em yS
(closest, closestPair) ← (dmin, pairMin)
<strong>for</strong> i <strong>from</strong> 1 <strong>to</strong> nS - 1
<strong>para</strong> i <strong>de</strong> 1 <strong>a</strong> nS - 1
k ← i + 1
<strong>while</strong> k ≤ nS <strong>and</strong> yS(k)<sub>y</sub> - yS(i)<sub>y</sub> &#x3C; dmin
<strong>if</strong> |yS(k) - yS(i)| &#x3C; closest <strong>then</strong>
<strong>enquanto</strong> k ≤ nS <strong>e</strong> yS(k)<sub>y</sub> - yS(i)<sub>y</sub> &#x3C; dmin
<strong>se</strong> |yS(k) - yS(i)| &#x3C; closest <strong>então</strong>
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
<strong>endif</strong>
<strong>fimSe</strong>
k ← k + 1
<strong>endwhile</strong>
<strong>endfor</strong>
<strong>return</strong> closest, closestPair
<strong>endif</strong>
<strong>fimEnquanto</strong>
<strong>fimPara</strong>
<strong>retorne</strong> closest, closestPair
<strong>fimSe</strong>
</pre>
For the input, expect the argument to be an array of `Point` objects with `x` and `y` members set to numbers. Return an object containing the key:value pairs for `distance` and `pair` (the pair of two closest points).
Para a entrada, espere que o argumento seja um array de objetos `Point` com membros `x` e `y` definidos como números. Retorna um objeto que contém os pares chave-valor de `distance` e `pair` (o par com os dois pontos mais próximos).
For example `getClosestPair` with input array `points`:
Por exemplo, `getClosestPair` com o array de entrada `points`:
```js
const points = [
@ -77,7 +77,7 @@ const points = [
];
```
Would return:
Retornaria:
```js
{
@ -95,24 +95,24 @@ Would return:
}
```
**Note:** Sort the `pair` array by their `x` values in incrementing order.
**Observação:** ordene o array de `pair` por seus valores em `x` na ordem de incrementação.
# --hints--
`getClosestPair` should be a function.
`getClosestPair` deve ser uma função.
```js
assert(typeof getClosestPair === 'function');
```
`getClosestPair(points1).distance` should be `0.0894096443343775`.
`getClosestPair(points1).distance` deve ser `0.0894096443343775`.
```js
assert.equal(getClosestPair(points1).distance, answer1.distance);
```
`getClosestPair(points1).pair` should be `[ { x: 7.46489, y: 4.6268 }, { x: 7.46911, y: 4.71611 } ]`.
`getClosestPair(points1).pair` deve ser `[ { x: 7.46489, y: 4.6268 }, { x: 7.46911, y: 4.71611 } ]`.
```js
assert.deepEqual(
@ -121,13 +121,13 @@ assert.deepEqual(
);
```
`getClosestPair(points2).distance` should be `65.06919393998976`.
`getClosestPair(points2).distance` deve ser `65.06919393998976`.
```js
assert.equal(getClosestPair(points2).distance, answer2.distance);
```
`getClosestPair(points2).pair` should be `[ { x: 37134, y: 1963 }, { x: 37181, y: 2008 } ]`.
`getClosestPair(points2).pair` deve ser `[ { x: 37134, y: 1963 }, { x: 37181, y: 2008 } ]`.
```js
assert.deepEqual(
@ -136,13 +136,13 @@ assert.deepEqual(
);
```
`getClosestPair(points3).distance` should be `6754.625082119658`.
`getClosestPair(points3).distance` deve ser `6754.625082119658`.
```js
assert.equal(getClosestPair(points3).distance, answer3.distance);
```
`getClosestPair(points3).pair` should be `[ { x: 46817, y: 64975 }, { x: 48953, y: 58567 } ]`.
`getClosestPair(points3).pair` deve ser `[ { x: 46817, y: 64975 }, { x: 48953, y: 58567 } ]`.
```js
assert.deepEqual(

Some files were not shown because too many files have changed in this diff Show More