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

@ -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');