Add languages Russian, Arabic, Chinese, Portuguese (#18305)

This commit is contained in:
Beau Carnes
2018-10-10 18:03:03 -04:00
committed by mrugesh mohapatra
parent 09d3eca712
commit 2ca3a2093f
5517 changed files with 371466 additions and 5 deletions

View File

@@ -0,0 +1,74 @@
---
id: 587d8257367417b2b2512c7b
title: Add a New Element to a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Adicionar um novo elemento a uma árvore de pesquisa binária
---
## Description
<section id="description"> Agora que temos uma ideia do básico, vamos escrever um método mais complexo. Neste desafio, criaremos um método para adicionar novos valores à nossa árvore de pesquisa binária. O método deve ser chamado de <code>add</code> e deve aceitar um valor inteiro para adicionar à árvore. Tome cuidado para manter a invariante de uma árvore de pesquisa binária: o valor em cada filho da esquerda deve ser menor ou igual ao valor pai e o valor em cada filho da direita deve ser maior ou igual ao valor pai. Aqui, vamos fazer com que nossa árvore não possa conter valores duplicados. Se tentarmos adicionar um valor que já existe, o método deve retornar <code>null</code> . Caso contrário, se a adição for bem sucedida, <code>undefined</code> deve ser retornado. Dica: as árvores são estruturas de dados naturalmente recursivas! </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>add</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.add == "function")})(), "The binary search tree has a method called <code>add</code>.");'
- text: O método add adiciona elementos de acordo com as regras da árvore de pesquisa binária.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); const expectedResult = [ 1, 4, 7, 8, 34, 45, 73, 87 ]; const result = test.inOrder(); return (expectedResult.toString() === result.toString()); })(), "The add method adds elements according to the binary search tree rules.");'
- text: Adicionar um elemento que já existe retorna <code>null</code>
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== "function") { return false; }; test.add(4); return test.add(4) == null; })(), "Adding an element that already exists returns <code>null</code>");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,92 @@
---
id: 587d8252367417b2b2512c67
title: Add Elements at a Specific Index in a Linked List
challengeType: 1
videoUrl: ''
localeTitle: Adicionar elementos em um índice específico em uma lista vinculada
---
## Description
<section id="description"> Vamos criar um método addAt (index, element) que adiciona um elemento em um determinado índice. Assim como removemos elementos em um determinado índice, precisamos acompanhar o currentIndex à medida que percorremos a lista vinculada. Quando o currentIndex corresponde ao índice fornecido, precisaríamos reatribuir a próxima propriedade do nó anterior para fazer referência ao novo nó adicionado. E o novo nó deve referenciar o próximo nó no currentIndex. Voltando ao exemplo da linha de conga, uma nova pessoa quer entrar na linha, mas ele quer se juntar ao meio. Você está no meio da linha, então tire as mãos da pessoa à sua frente. A nova pessoa se aproxima e coloca as mãos sobre a pessoa que você teve uma vez, e agora você tem as mãos na nova pessoa. Instruções Crie um método addAt (index, element) que adiciona um elemento em um determinado índice. Retornar false se um elemento não puder ser adicionado. Nota Lembre-se de verificar se o índice fornecido é negativo ou maior que o comprimento da lista vinculada. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Seu método <code>addAt</code> deve reatribuir a <code>head</code> para o novo nó quando o índice fornecido for 0.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.addAt(0,"cat"); return test.head().element === "cat"}()), "Your <code>addAt</code> method should reassign <code>head</code> to the new node when the given index is 0.");'
- text: Seu método <code>addAt</code> deve aumentar o tamanho da lista vinculada em um para cada novo nó adicionado à lista vinculada.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.addAt(0,"cat"); return test.size() === 3}()), "Your <code>addAt</code> method should increase the length of the linked list by one for each new node added to the linked list.");'
- text: Seu método <code>addAt</code> deve retornar <code>false</code> se um nó não puder ser adicionado.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); return (test.addAt(4,"cat") === false); }()), "Your <code>addAt</code> method should return <code>false</code> if a node was unable to be added.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,56 @@
---
id: 587d8256367417b2b2512c77
title: Adjacency List
challengeType: 1
videoUrl: ''
localeTitle: Lista de Adjacência
---
## Description
<section id="description"> Os gráficos podem ser representados de maneiras diferentes. Aqui nós descrevemos um caminho, que é chamado de <dfn>lista de adjacências</dfn> . Uma lista de adjacências é essencialmente uma lista com marcadores, onde o lado esquerdo é o nó e o lado direito lista todos os outros nós aos quais está conectado. Abaixo está uma representação de uma lista de adjacências. <blockquote> Nó1: Nó2, Nó3 <br> Nó2: Nó1 <br> Nó3: Nó1 </blockquote> Acima está um gráfico não direcionado porque o <code>Node1</code> está conectado ao <code>Node2</code> e ao <code>Node3</code> , e essa informação é consistente com as conexões <code>Node2</code> e <code>Node3</code> . Uma lista de adjacências para um gráfico direcionado significaria que cada linha da lista mostra a direção. Se o acima foi direcionado, então <code>Node2: Node1</code> significaria que a borda direcionada está apontando do <code>Node2</code> para o <code>Node1</code> . Podemos representar o grafo não direcionado acima como uma lista de adjacências, colocando-o dentro de um objeto JavaScript. <blockquote> var undirectedG = { <br> Nó1: [&quot;Nó2&quot;, &quot;Nó3&quot;], <br> Nó2: [&quot;Nó1&quot;], <br> Nó3: [&quot;Nó1&quot;] <br> }; </blockquote> Isso também pode ser mais simplesmente representado como uma matriz em que os nós apenas têm números em vez de rótulos de seqüência de caracteres. <blockquote> var undirectedGArr = [ <br> [1, 2], # Node1 <br> [0], # Node2 <br> [0] # Node3 <br> ]; </blockquote></section>
## Instructions
<section id="instructions"> Crie uma rede social como um gráfico não direcionado com 4 nós / pessoas chamados <code>James</code> , <code>Jill</code> , <code>Jenny</code> e <code>Jeff</code> . Existem arestas / relações entre James e Jeff, Jill e Jenny, e Jeff e Jenny. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>undirectedAdjList</code> deve conter apenas quatro nós.
testString: 'assert(Object.keys(undirectedAdjList).length === 4, "<code>undirectedAdjList</code> should only contain four nodes.");'
- text: Deve haver uma vantagem entre <code>Jeff</code> e <code>James</code> .
testString: 'assert(undirectedAdjList.James.indexOf("Jeff") !== -1 && undirectedAdjList.Jeff.indexOf("James") !== -1, "There should be an edge between <code>Jeff</code> and <code>James</code>.");'
- text: Deve haver uma vantagem entre <code>Jill</code> e <code>Jenny</code> .
testString: 'assert(undirectedAdjList.Jill.indexOf("Jenny") !== -1 && undirectedAdjList.Jill.indexOf("Jenny") !== -1, "There should be an edge between <code>Jill</code> and <code>Jenny</code>.");'
- text: Deve haver uma vantagem entre <code>Jeff</code> e <code>Jenny</code> .
testString: 'assert(undirectedAdjList.Jeff.indexOf("Jenny") !== -1 && undirectedAdjList.Jenny.indexOf("Jeff") !== -1, "There should be an edge between <code>Jeff</code> and <code>Jenny</code>.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var undirectedAdjList = {
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,58 @@
---
id: 587d8256367417b2b2512c78
title: Adjacency Matrix
challengeType: 1
videoUrl: ''
localeTitle: Matriz de adjacência
---
## Description
<section id="description"> Outra maneira de representar um gráfico é colocá-lo em uma <dfn>matriz de adjacência</dfn> . Uma <dfn>matriz de adjacência</dfn> é uma <dfn>matriz</dfn> bidimensional (2D) onde cada matriz aninhada tem o mesmo número de elementos que a matriz externa. Em outras palavras, é uma matriz ou grade de números, onde os números representam as arestas. Zeros significa que não há vantagem ou relacionamento. <blockquote> 1 2 3 <br> ------ <br> 1 | 0 1 1 <br> 2 | 1 0 0 <br> 3 | 1 0 0 </blockquote> Acima está um gráfico muito simples, não direcionado, no qual você tem três nós, onde o primeiro nó está conectado ao segundo e terceiro nó. <strong>Nota</strong> : Os números na parte superior e esquerda da matriz são apenas rótulos para os nós. Abaixo está uma implementação JavaScript da mesma coisa. <blockquote> var adjMat = [ <br> [0, 1, 1] <br> [1, 0, 0] <br> [1, 0, 0] <br> ]; </blockquote> Ao contrário de uma lista de adjacências, cada &quot;linha&quot; da matriz deve ter o mesmo número de elementos que os nós no gráfico. Aqui temos uma matriz de três por três, o que significa que temos três nós em nosso gráfico. Um gráfico direcionado seria semelhante. Abaixo está um gráfico onde o primeiro nó tem uma borda apontando para o segundo nó e, em seguida, o segundo nó tem uma borda apontando para o terceiro nó. <blockquote> var adjMatDirected = [ <br> [0, 1, 0] <br> [0, 0, 1] <br> [0, 0, 0] <br> ]; </blockquote> Gráficos também podem ter <dfn>pesos</dfn> em suas bordas. Até agora, temos arestas <dfn>não ponderadas</dfn> onde apenas a presença e a falta de aresta é binária ( <code>0</code> ou <code>1</code> ). Você pode ter pesos diferentes dependendo do seu aplicativo. </section>
## Instructions
<section id="instructions"> Crie uma matriz de adjacência de um gráfico não direcionado com cinco nós. Essa matriz deve estar em uma matriz multidimensional. Esses cinco nós têm relações entre o primeiro e o quarto nó, o primeiro e o terceiro nó, o terceiro e o quinto nó e o quarto e o quinto nó. Todos os pesos de borda são um. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>undirectedAdjList</code> deve conter apenas cinco nós.
testString: 'assert((adjMatUndirected.length === 5) && adjMatUndirected.map(function(x) { return x.length === 5 }).reduce(function(a, b) { return a && b }) , "<code>undirectedAdjList</code> should only contain five nodes.");'
- text: Deve haver uma borda entre o primeiro e o quarto nó.
testString: 'assert((adjMatUndirected[0][3] === 1) && (adjMatUndirected[3][0] === 1), "There should be an edge between the first and fourth node.");'
- text: Deve haver uma borda entre o primeiro e o terceiro nó.
testString: 'assert((adjMatUndirected[0][2] === 1) && (adjMatUndirected[2][0] === 1), "There should be an edge between the first and third node.");'
- text: Deve haver uma borda entre o terceiro e o quinto nó.
testString: 'assert((adjMatUndirected[2][4] === 1) && (adjMatUndirected[4][2] === 1), "There should be an edge between the third and fifth node.");'
- text: Deve haver uma borda entre o quarto e o quinto nó.
testString: 'assert((adjMatUndirected[3][4] === 1) && (adjMatUndirected[4][3] === 1), "There should be an edge between the fourth and fifth node.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var adjMatUndirected = [
];
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,76 @@
---
id: 587d825c367417b2b2512c90
title: Breadth-First Search
challengeType: 1
videoUrl: ''
localeTitle: Primeira pesquisa
---
## Description
<section id="description"> Até agora, aprendemos diferentes maneiras de criar representações de gráficos. E agora? Uma questão natural a ter é quais são as distâncias entre dois nós no gráfico? Digite os <dfn>algoritmos de percurso de gráfico</dfn> . <dfn>Algoritmos de passagem</dfn> são algoritmos para atravessar ou visitar nós em um gráfico. Um tipo de algoritmo de travessia é o algoritmo de pesquisa em amplitude. Esse algoritmo começa em um nó, primeiro visita todos os seus vizinhos que estão a uma distância de distância e depois visita cada um dos vizinhos. Visualmente, isso é o que o algoritmo está fazendo. <img class="img-responsive" src="https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966"> Para implementar esse algoritmo, você precisará inserir uma estrutura de gráfico e um nó no qual deseja iniciar. Primeiro, você deve estar ciente das distâncias do nó inicial. Isso você vai querer começar todas as suas distâncias inicialmente um grande número, como o <code>Infinity</code> . Isso fornece uma referência para o caso em que um nó pode não estar acessível a partir do seu nó inicial. Em seguida, você vai querer ir do nó inicial para seus vizinhos. Estes vizinhos estão a uma distância de distância e neste ponto você deve adicionar uma unidade de distância às distâncias que você está acompanhando. Por último, uma estrutura de dados importante que ajudará a implementar o algoritmo de pesquisa de largura única é a fila. Esta é uma matriz onde você pode adicionar elementos a uma extremidade e remover elementos da outra extremidade. Isso também é conhecido como uma estrutura de dados <dfn>FIFO</dfn> ou <dfn>First-In-First-Out</dfn> . </section>
## Instructions
<section id="instructions"> Escreva uma função <code>bfs()</code> que usa um gráfico de matriz de adjacência (uma matriz bidimensional) e uma raiz de rótulo de nó como parâmetros. O rótulo do nó será apenas o valor inteiro do nó entre <code>0</code> e <code>n - 1</code> , onde <code>n</code> é o número total de nós no gráfico. Sua função produzirá um par de valores-chave do objeto JavaScript com o nó e sua distância da raiz. Se o nó não puder ser alcançado, ele deverá ter uma distância do <code>Infinity</code> . </section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>1</code> deve retornar <code>{0: 1, 1: 0, 2: 1, 3: 2}</code>'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; var results = bfs(graph, 1); return isEquivalent(results, {0: 1, 1: 0, 2: 1, 3: 2})})(), "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: 2}</code>");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> com um nó inicial de <code>1</code> deve retornar <code>{0: 1, 1: 0, 2: 1, 3: Infinity}</code>'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; var results = bfs(graph, 1); return isEquivalent(results, {0: 1, 1: 0, 2: 1, 3: Infinity})})(), "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: Infinity}</code>");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>0</code> deve retornar <code>{0: 0, 1: 1, 2: 2, 3: 3}</code>'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1, 2: 2, 3: 3})})(), "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1, 2: 2, 3: 3}</code>");'
- text: 'O gráfico de entrada <code>[[0, 1], [1, 0]]</code> com um nó inicial de <code>0</code> deve retornar <code>{0: 0, 1: 1}</code>'
testString: 'assert((function() { var graph = [[0, 1], [1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1})})(), "The input graph <code>[[0, 1], [1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1}</code>");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function bfs(graph, root) {
// Distance object returned
var nodesLen = {};
return nodesLen;
};
var exBFSGraph = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
];
console.log(bfs(exBFSGraph, 3));
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,74 @@
---
id: 587d8257367417b2b2512c7c
title: Check if an Element is Present in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Verificar se um elemento está presente em uma árvore de pesquisa binária
---
## Description
<section id="description"> Agora que temos uma noção geral do que é uma árvore de pesquisa binária, vamos falar sobre isso com um pouco mais de detalhes. As árvores de pesquisa binária fornecem tempo logarítmico para as operações comuns de pesquisa, inserção e exclusão no caso médio e tempo linear no pior dos casos. Por que é isso? Cada uma dessas operações básicas nos obriga a encontrar um item na árvore (ou no caso de inserção para encontrar onde ele deve ir) e por causa da estrutura em árvore em cada nó pai que estamos ramificando para a esquerda ou direita e efetivamente excluindo metade do tamanho da árvore restante. Isso torna a pesquisa proporcional ao logaritmo do número de nós na árvore, o que cria um tempo logarítmico para essas operações no caso médio. Ok, mas e o pior dos casos? Bem, considere a construção de uma árvore a partir dos seguintes valores, adicionando-os da esquerda para a direita: <code>10</code> , <code>12</code> , <code>17</code> , <code>25</code> . Seguindo nossas regras para uma árvore de pesquisa binária, adicionaremos <code>12</code> à direita de <code>10</code> , <code>17</code> à direita desta e <code>25</code> à direita desta. Agora nossa árvore se assemelha a uma lista encadeada e atravessá-la para encontrar <code>25</code> exigiria que percorrêssemos todos os itens de maneira linear. Assim, o tempo linear no pior dos casos. O problema aqui é que a árvore está desequilibrada. Veremos um pouco mais sobre o que isso significa nos desafios a seguir. Instruções: Neste desafio, vamos criar um utilitário para a nossa árvore. Escreva um método <code>isPresent</code> que <code>isPresent</code> um valor inteiro como entrada e retorne um valor booleano para a presença ou ausência desse valor na árvore de pesquisa binária. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>isPresent</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.isPresent == "function")})(), "The binary search tree has a method called <code>isPresent</code>.");'
- text: O método <code>isPresent</code> verifica corretamente a presença ou ausência de elementos adicionados à árvore.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.isPresent !== "function") { return false; }; test.add(4); test.add(7); test.add(411); test.add(452); return ( test.isPresent(452) && test.isPresent(411) && test.isPresent(7) && !test.isPresent(100) ); })(), "The <code>isPresent</code> method correctly checks for the presence or absence of elements added to the tree.");'
- text: <code>isPresent</code> manipula casos em que a árvore está vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.isPresent !== "function") { return false; }; return test.isPresent(5) == false; })(), "<code>isPresent</code> handles cases where the tree is empty.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,89 @@
---
id: 587d8255367417b2b2512c75
title: Create a Circular Queue
challengeType: 1
videoUrl: ''
localeTitle: Criar uma fila circular
---
## Description
<section id="description"> Neste desafio você estará criando uma Fila Circular. Uma fila circular é basicamente uma fila que grava no final de uma coleção e começa a escrever no próprio início da coleção. Este é o tipo de estrutura de dados tem algumas aplicações úteis em determinadas 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 simplesmente começam a substituir os dados antigos. Uma boa maneira de ilustrar esse conceito é com uma matriz: <blockquote> [1, 2, 3, 4, 5] <br> ^ Leia @ 0 <br> ^ Escreva @ 0 </blockquote> Aqui, a leitura e a gravação estão na posição <code>0</code> . Agora a fila recebe 3 novos registros <code>a</code> , <code>b</code> e <code>c</code> . Nossa fila agora parece com: <blockquote> [a, b, c, 4, 5] <br> ^ Leia @ 0 <br> ^ Escreva @ 3 </blockquote> Como o cabeçote de leitura lê, ele pode remover valores ou mantê-los: <blockquote> [nulo, nulo, nulo, 4, 5] <br> ^ Leia @ 3 <br> ^ Escreva @ 3 </blockquote> Quando a gravação chega ao final da matriz, volta ao início: <blockquote> [f, null, null, d, e] <br> ^ Leia @ 3 <br> ^ Escreva @ 1 </blockquote> Essa abordagem requer uma quantidade constante de memória, mas permite que arquivos de tamanho muito maior sejam processados. Instruções: Neste desafio, vamos implementar uma fila circular. A fila circular deve fornecer métodos de <code>enqueue</code> e de <code>dequeue</code> que permitem ler e gravar na fila. A classe em si também deve aceitar um número inteiro que você possa usar para especificar o tamanho da fila ao criá-la. Nós escrevemos a versão inicial desta classe para você no editor de código. Quando você enfileira itens na fila, o ponteiro de gravação deve avançar e retornar ao início assim que chegar ao final da fila. Da mesma forma, o ponteiro de leitura deve avançar conforme você desencaixa itens. O ponteiro de escrita não deve passar pelo ponteiro de leitura (nossa classe não permitirá que você sobrescreva dados que você ainda não tenha lido) e o ponteiro de leitura não deve ser capaz de avançar dados passados que você escreveu. Além disso, o método de <code>enqueue</code> deve retornar o item que você enfileirou se tiver êxito e, caso contrário, retornará <code>null</code> . Da mesma forma, quando você desenfileirar um item, ele deve ser retornado e, se não for possível, você deve retornar <code>null</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: O método de <code>enqueue</code> adiciona itens à fila circular.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); var print = test.print(); return print[0] === 17 && print[1] === 32 && print[2] === 591; })(), "The <code>enqueue</code> method adds items to the circular queue.");'
- text: Você não pode enfileirar itens após o ponteiro de leitura.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); test.enqueue(13); test.enqueue(25); test.enqueue(59); var print = test.print(); return print[0] === 17 && print[1] === 32 && print[2] === 591; })(), "You cannot enqueue items past the read pointer.");'
- text: O método de <code>dequeue</code> retira itens da fila.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); return test.dequeue() === 17 && test.dequeue() === 32 && test.dequeue() === 591; })(), "The <code>dequeue</code> method dequeues items from the queue.");'
- text: 'Depois que um item é desenfileirado, sua posição na fila deve ser redefinida como <code>null</code> .'
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(672); test.dequeue(); test.dequeue(); var print = test.print(); return print[0] === null && print[1] === null && print[2] === 672; })(), "After an item is dequeued its position in the queue should be reset to <code>null</code>.");'
- text: A tentativa de desenfileirar após o ponteiro de gravação retorna <code>null</code> e não avança o ponteiro de gravação.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); return test.dequeue() === 17 && test.dequeue() === 32 && test.dequeue() === 591 && test.dequeue() === null && test.dequeue() === null && test.dequeue() === null && test.dequeue() === null && test.enqueue(100) === 100 && test.dequeue() === 100; })(), "Trying to dequeue past the write pointer returns <code>null</code> and does not advance the write pointer.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
class CircularQueue {
constructor(size) {
this.queue = [];
this.read = 0;
this.write = 0;
this.max = size - 1;
while (size > 0) {
this.queue.push(null);
size--;
}
}
print() {
return this.queue;
}
enqueue(item) {
// Only change code below this line
// Only change code above this line
}
dequeue() {
// Only change code below this line
// Only change code above this line
}
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,81 @@
---
id: 587d825a367417b2b2512c87
title: Create a Doubly Linked List
challengeType: 1
videoUrl: ''
localeTitle: Criar uma lista duplamente vinculada
---
## Description
<section id="description"> Todas as listas vinculadas que criamos até agora são listas vinculadas individualmente. Aqui, criaremos uma <dfn>lista duplamente vinculada</dfn> . Como o nome indica, os nós em uma lista duplamente vinculada têm referências ao nó seguinte e anterior na lista. Isso nos permite percorrer a lista em ambas as direções, mas também requer mais memória a ser usada, porque cada nó deve conter uma referência adicional ao nó anterior na lista. </section>
## Instructions
<section id="instructions"> Nós fornecemos um objeto <code>Node</code> e iniciamos o nosso <code>DoublyLinkedList</code> . Vamos adicionar dois métodos à nossa lista duplamente vinculada chamada <code>add</code> e <code>remove</code> . O <code>add</code> método deve adicionar o elemento dado à lista, enquanto a <code>remove</code> método deve remover todas as ocorrências de um determinado elemento da lista. Tenha cuidado para lidar com possíveis casos de borda ao escrever esses métodos, como exclusões para o primeiro ou último elemento. Além disso, remover qualquer item em uma lista vazia deve retornar <code>null</code> . </section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados DoublyLinkedList existe.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; return (typeof test == "object")})(), "The DoublyLinkedList data structure exists.");'
- text: O DoublyLinkedList possui um método chamado add.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; if (test.add == undefined) { return false; }; return (typeof test.add == "function")})(), "The DoublyLinkedList has a method called add.");'
- text: O DoublyLinkedList possui um método chamado remove.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; if (test.remove == undefined) { return false; }; return (typeof test.remove == "function")})(), "The DoublyLinkedList has a method called remove.");'
- text: Remover um item de uma lista vazia retorna null.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; return (test.remove(100) == null); })(), "Removing an item from an empty list returns null.");'
- text: O método add adiciona itens à lista.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; test.add(5); test.add(6); test.add(723); return (test.print().join("") == "56723"); })(), "The add method adds items to the list.");'
- text: Cada nó mantém o controle do nó anterior.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; test.add(50); test.add(68); test.add(73); return (test.printReverse().join("") == "736850"); })(), "Each node keeps track of the previous node.");'
- text: O primeiro item pode ser removido da lista.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; test.add(25); test.add(35); test.add(60); test.remove(25); return ( test.print().join("") == "3560" ) })(), "The first item can be removed from the list.");'
- text: O último item pode ser removido da lista.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; test.add(25); test.add(35); test.add(60); test.remove(60); return ( test.print().join("") == "2535" ) })(), "The last item can be removed from the list.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
this.head = null;
this.tail = null;
// change code below this line
// change code above this line
};
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,90 @@
---
id: 587d825b367417b2b2512c8e
title: Create a Hash Table
challengeType: 1
videoUrl: ''
localeTitle: Criar uma tabela de hash
---
## Description
<section id="description"> Neste desafio, aprenderemos sobre tabelas de hash. Uma tabela de hash é usada para implementar matrizes associativas ou mapeamentos de pares de valores-chave, como os objetos e mapas que acabamos de estudar. Um objeto JavaScript poderia ser implementado como uma tabela de hash, por exemplo (sua implementação real dependerá do ambiente em que está sendo executado). A forma como uma tabela de hash funciona é que ela recebe uma entrada de chave e coloca essa chave em uma forma determinística para algum valor numérico. Este valor numérico é então usado como a chave real pela qual o valor associado é armazenado. Então, se você tentar acessar a mesma chave novamente, a função de hashing processará a chave, retornará o mesmo resultado numérico, que será usado para procurar o valor associado. Isso fornece tempo de pesquisa O (n) muito eficiente, em média. As tabelas de hash podem ser implementadas como matrizes com funções hash produzindo índices de matriz dentro de um intervalo especificado. Nesse método, a escolha do tamanho da matriz é importante, assim como a função hash. Por exemplo, e se a função hashing produzir o mesmo valor para duas chaves diferentes? Isso é chamado de colisão. Uma maneira de lidar com colisões é apenas armazenar os dois pares de valores-chave nesse índice. Em seguida, após a consulta de qualquer um deles, você terá que percorrer o intervalo de itens para encontrar a chave que está procurando. Uma boa função hash minimiza as colisões para manter um tempo de busca eficiente. Aqui, não nos preocuparemos com os detalhes de hash ou implementação de tabela de hash, vamos apenas tentar ter uma noção geral de como eles funcionam. Instruções: Vamos criar a funcionalidade básica de uma tabela de hash. Criamos uma função ingênua de hash para você usar. Você pode passar um valor de string para o hash da função e ele retornará um valor com hash que você pode usar como chave para armazenamento. Armazene itens com base nesse valor com hash no objeto this.collection. Crie estes três métodos: adicionar, remover e pesquisar. O primeiro deve aceitar um par de valores-chave para adicionar à tabela de hash. O segundo deve remover um par de valores-chave quando passar uma chave. O terceiro deve aceitar uma chave e retornar o valor associado ou nulo se a chave não estiver presente. Certifique-se de escrever seu código para contabilizar colisões! </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados HashTable existe.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; return (typeof test === "object")})(), "The HashTable data structure exists.");'
- text: O HashTable tem um método add.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; return ((typeof test.add) === "function")})(), "The HashTable has an add method.");'
- text: O HashTable tem um método remove.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; return ((typeof test.remove) === "function")})(), "The HashTable has an remove method.");'
- text: O HashTable tem um método de pesquisa.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; return ((typeof test.lookup) === "function")})(), "The HashTable has an lookup method.");'
- text: O método add adiciona pares de valores de chave e o método de pesquisa retorna os valores associados a uma determinada chave.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; test.add("key", "value"); return (test.lookup("key") === "value")})(), "The add method adds key value pairs and the lookup method returns the values associated with a given key.");'
- text: O método remove aceita uma chave como entrada e remove o par de valores de chaves associados.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; test.add("key", "value"); test.remove("key"); return (test.lookup("key") === null)})(), "The remove method accepts a key as input and removes the associated key value pair.");'
- text: Itens são adicionados usando a função hash.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; called = 0; test.add("key1","value1"); test.add("key2","value2"); test.add("key3","value3"); return (called === 3)})(), "Items are added using the hash function.");'
- text: A tabela de hash lida com colisões.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; called = 0; test.add("key1","value1"); test.add("1key","value2"); test.add("ke1y","value3"); return (test.lookup("key1") === "value1" && test.lookup("1key") == "value2" && test.lookup("ke1y") == "value3")})(), "The hash table handles collisions.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var called = 0;
var hash = (string) => {
called++;
var hash = 0;
for (var i = 0; i < string.length; i++) { hash += string.charCodeAt(i); }
return hash;
};
var HashTable = function() {
this.collection = {};
// change code below this line
// change code above this line
};
```
</div>
### Before Test
<div id='js-setup'>
```js
var called = 0;
var hash = (string) => {
called++;
var hash = 0;
for (var i = 0; i < string.length; i++) { hash += string.charCodeAt(i); };
return hash;
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,77 @@
---
id: 587d8251367417b2b2512c62
title: Create a Linked List Class
challengeType: 1
videoUrl: ''
localeTitle: Criar uma classe de lista vinculada
---
## Description
<section id="description"> Vamos criar uma classe de <code>linked list</code> . Cada lista encadeada deve começar com algumas propriedades básicas: uma <code>head</code> (o primeiro item na sua lista) e uma <code>length</code> (número de itens na sua lista). Às vezes, você verá implementações de listas vinculadas que incorporam uma <code>tail</code> para o último elemento da lista, mas, por enquanto, vamos continuar com essas duas. Sempre que adicionamos um elemento à lista vinculada, nossa propriedade <code>length</code> deve ser incrementada em um. Nós queremos ter uma maneira de adicionar itens à nossa lista vinculada, então o primeiro método que vamos criar é o método <code>add</code> . Se a nossa lista estiver vazia, adicionar um elemento à nossa lista encadeada é bastante simples: apenas envolvemos esse elemento em uma classe <code>Node</code> e atribuímos esse nó à <code>head</code> de nossa lista encadeada. Mas e se a nossa lista já tiver um ou mais membros? Como adicionamos um elemento à lista? Lembre-se de que cada nó em uma lista vinculada possui uma propriedade <code>next</code> . Para adicionar um nó à lista, encontre o último nó na lista e aponte a <code>next</code> propriedade do último nó em nosso novo nó. (Dica: você sabe que chegou ao final de uma lista vinculada quando a <code>next</code> propriedade de um nó é <code>null</code> .) </section>
## Instructions
<section id="instructions"> Escreva um método add que atribua o primeiro nó que você envia para a lista vinculada ao <code>head</code> ; depois disso, sempre que adicionar um nó, cada nó deve ser referenciado pela <code>next</code> propriedade do nó anterior. Nota A <code>length</code> da sua lista deve aumentar em um sempre que um elemento é adicionado à lista vinculada. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>LinkedList</code> deve ter um método <code>add</code> .
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.add === "function")}()), "Your <code>LinkedList</code> class should have a <code>add</code> method.");'
- text: Sua classe <code>LinkedList</code> deve atribuir <code>head</code> ao primeiro nó adicionado.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); return test.head().element === "cat"}()), "Your <code>LinkedList</code> class should assign <code>head</code> to the first node added.");'
- text: O <code>node</code> anterior na sua classe <code>LinkedList</code> deve ter referência ao nó mais novo criado.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); return test.head().next.element === "dog"}()), "The previous <code>node</code> in your <code>LinkedList</code> class should have reference to the newest node created.");'
- text: O <code>size</code> da sua classe <code>LinkedList</code> deve ser igual à quantidade de nós na lista vinculada.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); return test.size() === 2}()), "The <code>size</code> of your <code>LinkedList</code> class should equal the amount of nodes in the linked list.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.head = function(){
return head;
};
this.size = function(){
return length;
};
this.add = function(element){
// Only change code below this line
// Only change code above this line
};
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,66 @@
---
id: 8d5823c8c441eddfaeb5bdef
title: Create a Map Data Structure
challengeType: 1
videoUrl: ''
localeTitle: Criar uma estrutura de dados do mapa
---
## Description
<section id="description"> Os próximos desafios cobrirão mapas e tabelas de hash. Mapas são estruturas de dados que armazenam pares de valores-chave. Em JavaScript, eles estão disponíveis para nós como objetos. Mapas fornecem pesquisa rápida de itens armazenados com base em valores-chave e são estruturas de dados muito comuns e úteis. Instruções: Vamos praticar um pouco criando nosso próprio mapa. Como os objetos JavaScript fornecem uma estrutura de mapa muito mais eficiente do que qualquer coisa que possamos escrever aqui, isso se destina principalmente a um exercício de aprendizado. No entanto, os objetos JavaScript nos fornecem apenas determinadas operações. E se quiséssemos definir operações personalizadas? Use o objeto <code>Map</code> fornecido aqui como um wrapper em torno de um <code>object</code> JavaScript. Crie os seguintes métodos e operações no objeto Map: <ul><li> <code>add</code> aceita um par de <code>key, value</code> para adicionar ao mapa. </li><li> <code>remove</code> aceita uma chave e remove a <code>key, value</code> associada <code>key, value</code> par de <code>key, value</code> </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>verdadeiro</dfn> se a chave existir ou <dfn>falso,</dfn> se isso não acontece. </li><li> <code>values</code> retorna uma matriz 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></section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados do mapa existe.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; return (typeof test == "object")})(), "The Map data structure exists.");'
- text: 'O objeto Map possui os seguintes métodos: add, remove, get, tem, valores, clear e size.'
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; return (typeof test.add == "function" && typeof test.remove == "function" && typeof test.get == "function" && typeof test.has == "function" && typeof test.values == "function" && typeof test.clear == "function" && typeof test.size == "function")})(), "The Map object has the following methods: add, remove, get, has, values, clear, and size.");'
- text: O método add adiciona itens ao mapa.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; test.add(5,6); test.add(2,3); test.add(2,5); return (test.size() == 2)})(), "The add method adds items to the map.");'
- text: O método has retorna true para itens adicionados e false para itens ausentes.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; test.add("test","value"); return (test.has("test") && !test.has("false"))})(), "The has method returns true for added items and false for absent items.");'
- text: O método get aceita as chaves como entrada e retorna os valores associados.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; test.add("abc","def"); return (test.get("abc") == "def")})(), "The get method accepts keys as input and returns the associated values.");'
- text: O método values retorna todos os valores armazenados no mapa como strings em uma matriz.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; test.add("a","b"); test.add("c","d"); test.add("e","f"); var vals = test.values(); return (vals.indexOf("b") != -1 && vals.indexOf("d") != -1 && vals.indexOf("f") != -1)})(), "The values method returns all the values stored in the map as strings in an array.");'
- text: O método clear esvazia o mapa e o método size retorna o número de itens presentes no mapa.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; test.add("b","b"); test.add("c","d"); test.remove("asdfas"); var init = test.size(); test.clear(); return (init == 2 && test.size() == 0)})(), "The clear method empties the map and the size method returns the number of items present in the map.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Map = function() {
this.collection = {};
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,70 @@
---
id: 587d8255367417b2b2512c74
title: Create a Priority Queue Class
challengeType: 1
videoUrl: ''
localeTitle: Criar uma classe de fila de prioridade
---
## Description
<section id="description"> Neste desafio você estará criando uma Fila de Prioridades. Uma Fila Prioritária é um tipo especial de Fila no qual os itens podem ter informações adicionais que especificam sua prioridade. Isso poderia ser simplesmente representado com um inteiro. A prioridade do item substituirá a ordem de veiculação para determinar se os itens da sequência são retirados da fila. Se um item com uma prioridade mais alta for enfileirado após os itens com prioridade mais baixa, o item com prioridade mais alta será retirado antes de todos os outros. Por exemplo, vamos imaginar que temos uma fila de prioridades com três itens: <code>[[&#39;kitten&#39;, 2], [&#39;dog&#39;, 2], [&#39;rabbit&#39;, 2]]</code> Aqui o segundo valor (um inteiro) representa a prioridade do item. . Se enfileirarmos <code>[&#39;human&#39;, 1]</code> com uma prioridade de <code>1</code> (assumindo que prioridades mais baixas recebem precedência), ele seria o primeiro item a ser retirado. A coleção seria assim: <code>[[&#39;human&#39;, 1], [&#39;kitten&#39;, 2], [&#39;dog&#39;, 2], [&#39;rabbit&#39;, 2]]</code> . Nós começamos a escrever um <code>PriorityQueue</code> no editor de código. Você precisará adicionar um método de <code>enqueue</code> para adicionar itens com prioridade, um método de <code>dequeue</code> para remover itens, um método de <code>size</code> para retornar o número de itens na fila, um método de <code>front</code> para retornar o elemento na frente da fila e finalmente, um método <code>isEmpty</code> que retornará <code>true</code> se a fila estiver vazia ou <code>false</code> se não estiver. O <code>enqueue</code> deve aceitar itens com o formato mostrado acima ( <code>[&#39;human&#39;, 1]</code> ), em que <code>1</code> representa a prioridade. O <code>dequeue</code> deve retornar apenas o item atual, não sua prioridade. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Queue</code> deve ter um método de <code>enqueue</code> .
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.enqueue === "function")}()), "Your <code>Queue</code> class should have a <code>enqueue</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método de <code>Queue</code> <code>dequeue</code> .
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.dequeue === "function")}()), "Your <code>Queue</code> class should have a <code>dequeue</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método de <code>size</code> .
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.size === "function")}()), "Your <code>Queue</code> class should have a <code>size</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método <code>isEmpty</code> .
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.isEmpty === "function")}()), "Your <code>Queue</code> class should have an <code>isEmpty</code> method.");'
- text: 'Seu PriorityQueue deve controlar corretamente o número atual de itens usando o método de <code>size</code> , à medida que os itens são enfileirados e retirados.'
testString: 'assert((function(){var test = new PriorityQueue(); test.enqueue(["David Brown", 2]); test.enqueue(["Jon Snow", 1]); var size1 = test.size(); test.dequeue(); var size2 = test.size(); test.enqueue(["A", 3]); test.enqueue(["B", 3]); test.enqueue(["C", 3]); return (size1 === 2 && size2 === 1 && test.size() === 4)}()), "Your PriorityQueue should correctly keep track of the current number of items using the <code>size</code> method as items are enqueued and dequeued.");'
- text: O método <code>isEmpty</code> deve retornar <code>true</code> quando a fila estiver vazia.
testString: 'assert((function(){var test = new PriorityQueue(); test.enqueue(["A", 1]); test.enqueue(["B", 1]); test.dequeue(); var first = test.isEmpty(); test.dequeue(); return (!first && test.isEmpty()); }()), "The <code>isEmpty</code> method should return <code>true</code> when the queue is empty.");'
- text: 'A fila de prioridade deve retornar itens com prioridade mais alta antes dos itens com prioridade mais baixa e retornar os itens na ordem de primeiro a sair, caso contrário.'
testString: 'assert((function(){var test = new PriorityQueue(); test.enqueue(["A", 5]); test.enqueue(["B", 5]); test.enqueue(["C", 5]); test.enqueue(["D", 3]); test.enqueue(["E", 1]); test.enqueue(["F", 7]); var result = []; result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); return result.join("") === "EDABCF";}()), "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.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
console.log(this.collection);
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,74 @@
---
id: 587d8250367417b2b2512c60
title: Create a Queue Class
challengeType: 1
videoUrl: ''
localeTitle: Crie uma classe de fila
---
## Description
<section id="description"> Como pilhas, as filas são uma coleção de elementos. Mas, ao contrário das pilhas, as filas seguem o princípio FIFO (First-In First-Out). Os elementos adicionados a uma fila são colocados na cauda ou no final da fila, e somente o elemento na frente da fila pode ser removido. Poderíamos usar uma matriz para representar uma fila, mas, assim como as pilhas, queremos limitar a quantidade de controle que temos sobre nossas filas. Os dois métodos principais de uma classe de fila são o enfileiramento e o método de desenfileiramento. O método de enfileiramento envia um elemento para o final da fila, e o método de desenfileiramento remove e retorna o elemento na frente da fila. Outros métodos úteis são os métodos front, size e isEmpty. Instruções Escreva um método de enfileiramento que empurre um elemento para o final da fila, um método de desenfileiramento que remova e retorne o elemento frontal, um método frontal que nos permita ver o elemento frontal, um método de tamanho que mostre o comprimento e um método isEmpty. para verificar se a fila está vazia. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Queue</code> deve ter um método de <code>enqueue</code> .
testString: 'assert((function(){var test = new Queue(); return (typeof test.enqueue === "function")}()), "Your <code>Queue</code> class should have a <code>enqueue</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método de <code>Queue</code> <code>dequeue</code> .
testString: 'assert((function(){var test = new Queue(); return (typeof test.dequeue === "function")}()), "Your <code>Queue</code> class should have a <code>dequeue</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método <code>front</code> .
testString: 'assert((function(){var test = new Queue(); return (typeof test.front === "function")}()), "Your <code>Queue</code> class should have a <code>front</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método de <code>size</code> .
testString: 'assert((function(){var test = new Queue(); return (typeof test.size === "function")}()), "Your <code>Queue</code> class should have a <code>size</code> method.");'
- text: Sua classe <code>Queue</code> deve ter um método <code>isEmpty</code> .
testString: 'assert((function(){var test = new Queue(); return (typeof test.isEmpty === "function")}()), "Your <code>Queue</code> class should have an <code>isEmpty</code> method.");'
- text: O método de <code>dequeue</code> deve remover e retornar o elemento frontal da fila
testString: 'assert((function(){var test = new Queue(); test.enqueue("Smith"); return (test.dequeue() === "Smith")}()), "The <code>dequeue</code> method should remove and return the front element of the queue");'
- text: O método <code>front</code> deve retornar o valor do elemento frontal da fila
testString: 'assert((function(){var test = new Queue(); test.enqueue("Smith"); test.enqueue("John"); return (test.front() === "Smith")}()), "The <code>front</code> method should return value of the front element of the queue");'
- text: O método de <code>size</code> deve retornar o comprimento da fila
testString: 'assert((function(){var test = new Queue(); test.enqueue("Smith"); return (test.size() === 1)}()), "The <code>size</code> method should return the length of the queue");'
- text: O método <code>isEmpty</code> deve retornar <code>false</code> se houver elementos na fila
testString: 'assert((function(){var test = new Queue(); test.enqueue("Smith"); return !(test.isEmpty())}()), "The <code>isEmpty</code> method should return <code>false</code> if there are elements in the queue");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Queue () {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,69 @@
---
id: 8d1323c8c441eddfaeb5bdef
title: Create a Set Class
challengeType: 1
videoUrl: ''
localeTitle: Criar uma classe de conjunto
---
## Description
<section id="description"> Nos próximos exercícios, vamos criar uma função para emular uma estrutura de dados chamada &quot;Set&quot;. Um conjunto é como uma matriz, mas não pode conter valores duplicados. O uso típico de um conjunto é simplesmente verificar a presença de um item. Isso pode ser implementado com um objeto, por exemplo: <blockquote> var set = new Object (); <br> set.foo = true; <br> // Veja se foo existe em nosso conjunto: <br> console.log (set.foo) // true </blockquote> Nos próximos exercícios, vamos construir um conjunto completo a partir do zero. Para este exercício, crie uma função que irá adicionar um valor à nossa coleção de conjuntos, desde que o valor ainda não exista no conjunto. Por exemplo: <blockquote> this.add = function (element) { <br> // algum código para agregar valor ao conjunto <br> } </blockquote> A função deve retornar <code>true</code> se o valor for adicionado com sucesso e, caso contrário, <code>false</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método <code>add</code> .
testString: 'assert((function(){var test = new Set(); return (typeof test.add === "function")}()), "Your <code>Set</code> class should have an <code>add</code> method.");'
- text: Seu método <code>add</code> não deve adicionar valores duplicados.
testString: 'assert((function(){var test = new Set(); test.add("a"); test.add("b"); test.add("a"); var vals = test.values(); return (vals[0] === "a" && vals[1] === "b" && vals.length === 2)}()), "Your <code>add</code> method should not add duplicate values.");'
- text: Seu método <code>add</code> deve retornar <code>true</code> quando um valor for adicionado com sucesso.
testString: 'assert((function(){var test = new Set(); var result = test.add("a"); return (result != undefined) && (result === true);}()), "Your <code>add</code> method should return <code>true</code> when a value has been successfully added.");'
- text: Seu método <code>add</code> deve retornar <code>false</code> quando um valor duplicado é adicionado.
testString: 'assert((function(){var test = new Set(); test.add("a"); var result = test.add("a"); return (result != undefined) && (result === false);}()), "Your <code>add</code> method should return <code>false</code> when a duplicate value is added.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold our set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,74 @@
---
id: 587d8250367417b2b2512c5f
title: Create a Stack Class
challengeType: 1
videoUrl: ''
localeTitle: Crie uma classe de pilha
---
## Description
<section id="description"> Na última seção, falamos sobre o que é uma pilha e como podemos usar uma matriz para representar uma pilha. Nesta seção, criaremos nossa própria classe de pilha. Embora você possa usar matrizes para criar pilhas, às vezes é melhor limitar a quantidade de controle que temos com nossas pilhas. Além do método <code>push</code> e <code>pop</code> , as pilhas possuem outros métodos úteis. Vamos adicionar um método <code>peek</code> , <code>isEmpty</code> e <code>clear</code> a nossa classe stack. Instruções Escreva um método <code>push</code> que empurre um elemento para o topo da pilha, um método <code>pop</code> que remova o elemento na parte superior da pilha, um método de <code>peek</code> que examine o primeiro elemento na pilha, um método <code>isEmpty</code> que verifique se o elemento pilha está vazia e um método <code>clear</code> que remove todos os elementos da pilha. Normalmente as pilhas não têm isso, mas adicionamos um método auxiliar de <code>print</code> que o console registra na coleção. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Stack</code> deve ter um método <code>push</code> .
testString: 'assert((function(){var test = new Stack(); return (typeof test.push === "function")}()), "Your <code>Stack</code> class should have a <code>push</code> method.");'
- text: Sua classe <code>Stack</code> deve ter um método <code>pop</code> .
testString: 'assert((function(){var test = new Stack(); return (typeof test.pop === "function")}()), "Your <code>Stack</code> class should have a <code>pop</code> method.");'
- text: Sua classe <code>Stack</code> deve ter um método de <code>peek</code> .
testString: 'assert((function(){var test = new Stack(); return (typeof test.peek === "function")}()), "Your <code>Stack</code> class should have a <code>peek</code> method.");'
- text: Sua classe <code>Stack</code> deve ter um método <code>isEmpty</code> .
testString: 'assert((function(){var test = new Stack(); return (typeof test.isEmpty === "function")}()), "Your <code>Stack</code> class should have a <code>isEmpty</code> method.");'
- text: Sua classe <code>Stack</code> deve ter um método <code>clear</code> .
testString: 'assert((function(){var test = new Stack(); return (typeof test.clear === "function")}()), "Your <code>Stack</code> class should have a <code>clear</code> method.");'
- text: O método <code>peek</code> deve retornar o elemento principal da pilha
testString: 'assert((function(){var test = new Stack(); test.push("CS50"); return (test.peek() === "CS50")}()), "The <code>peek</code> method should return the top element of the stack");'
- text: O método <code>pop</code> deve remover e retornar o elemento principal da pilha
testString: 'assert((function(){var test = new Stack(); test.push("CS50"); return (test.pop() === "CS50");}()), "The <code>pop</code> method should remove and return the top element of the stack");'
- text: O método <code>isEmpty</code> deve retornar true se uma pilha não contiver nenhum elemento
testString: 'assert((function(){var test = new Stack(); return test.isEmpty()}()), "The <code>isEmpty</code> method should return true if a stack does not contain any elements");'
- text: O método <code>clear</code> deve remover todos os elementos da pilha
testString: 'assert((function(){var test = new Stack(); test.push("CS50"); test.clear(); return (test.isEmpty())}()), "The <code>clear</code> method should remove all element from the stack");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Stack() {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,72 @@
---
id: 587d8259367417b2b2512c84
title: Create a Trie Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Criar uma árvore de pesquisa Trie
---
## Description
<section id="description"> Aqui vamos nos mover a partir de árvores de busca binária e dar uma olhada em outro tipo de estrutura de árvore chamada trie. A trie é uma árvore de pesquisa ordenada geralmente usada para armazenar cadeias de caracteres, ou matrizes mais genericamente associativas ou conjuntos de dados dinâmicos nos quais as chaves são cadeias de caracteres. Eles são muito bons em armazenar conjuntos de dados quando muitas chaves terão prefixos sobrepostos, por exemplo, todas as palavras em um dicionário. Ao contrário de uma árvore binária, os nós não estão associados a valores reais. Em vez disso, o caminho para um nó representa uma chave específica. Por exemplo, se quiséssemos armazenar o código da string em um trie, teríamos quatro nós, um para cada letra: c - o - d - e. Seguir esse caminho por todos esses nós criará o código como uma string - esse caminho é a chave que armazenamos. Então, se quiséssemos adicionar a codificação de string, ela compartilharia os três primeiros nós do código antes de ramificar depois do d. Desta forma, grandes conjuntos de dados podem ser armazenados de forma compacta. Além disso, a pesquisa pode ser muito rápida, pois é 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ê deve ter adivinhado no exemplo acima, alguns metadados são comumente armazenados em nós que contêm o fim de uma chave, de modo que, em travessias posteriores, essa chave ainda possa ser recuperada. Por exemplo, se adicionarmos códigos em nosso exemplo acima, precisaríamos de alguma forma de saber que o código e representa o final de uma chave que foi inserida anteriormente. Caso contrário, essas informações seriam efetivamente perdidas quando adicionarmos códigos. Instruções: Vamos criar um trie para armazenar palavras. Ele aceita palavras através de um método add e as armazena em uma estrutura de dados trie. Ele também nos permitirá consultar se uma determinada string é uma palavra com um método isWord, e recuperar todas as palavras inseridas na trie com um método print. isWord deve retornar um valor booleano e imprimir deve retornar uma matriz de todas essas palavras como valores de string. Para que possamos verificar se essa estrutura de dados está implementada corretamente, fornecemos uma estrutura de nó para cada nó na árvore. Cada nó será um objeto com uma propriedade keys, que é um objeto Map do JavaScript. Isto irá conter as letras individuais que são chaves válidas de cada nó. Também criamos uma propriedade final nos nós que podem ser configurados como true se o nó representar a terminação de uma palavra. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: O Trie tem um método add.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== "undefined") { test = new Trie() } else { return false; }; return (typeof test.add == "function") }()), "The Trie has an add method.");'
- text: O Trie tem um método de impressão.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== "undefined") { test = new Trie() } else { return false; }; return (typeof test.print == "function") }()), "The Trie has a print method.");'
- text: O Trie tem um método isWord.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== "undefined") { test = new Trie() } else { return false; }; return (typeof test.isWord == "function") }()), "The Trie has an isWord method.");'
- text: O método print retorna todos os itens adicionados ao trie como strings em um array.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== "undefined") { test = new Trie() } else { return false; }; test.add("jump"); test.add("jumps"); test.add("jumped"); test.add("house"); test.add("mouse"); var added = test.print(); return (added.indexOf("jump") != -1 && added.indexOf("jumps") != -1 && added.indexOf("jumped") != -1 && added.indexOf("house") != -1 && added.indexOf("mouse") != -1 && added.length == 5); }()), "The print method returns all items added to the trie as strings in an array.");'
- text: O método isWord retorna true apenas para palavras adicionadas ao trie e false para todas as outras palavras.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== "undefined") { test = new Trie() } else { return false; }; test.add("hop"); test.add("hops"); test.add("hopped"); test.add("hoppy"); test.add("hope"); return (test.isWord("hop") && !test.isWord("ho") && test.isWord("hopped") && !test.isWord("hopp") && test.isWord("hoppy") && !test.isWord("hoping")); }()), "The isWord method returns true only for words added to the trie and false for all other words.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var Node = function() {
this.keys = new Map();
this.end = false;
this.setEnd = function() {
this.end = true;
};
this.isEnd = function() {
return this.end;
};
};
var Trie = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,52 @@
---
id: 587d825b367417b2b2512c8d
title: Create an ES6 JavaScript Map
challengeType: 1
videoUrl: ''
localeTitle: Crie um mapa JavaScript ES6
---
## Description
<section id="description"> A nova versão do JavaScript nos fornece um objeto Map embutido que fornece grande parte da funcionalidade que escrevemos à mão no último desafio. Esse objeto Map, embora semelhante aos objetos JavaScript comuns, fornece algumas funcionalidades úteis que faltam aos objetos normais. Por exemplo, um mapa ES6 rastreia a ordem de inserção dos itens que são adicionados a ele. Aqui está uma visão geral mais completa de seus métodos: <code>.has(key)</code> retorna true ou false com base na presença de uma chave <code>.get(key)</code> retorna o valor associado a uma chave <code>.set(key, value)</code> define uma nova chave, par de valores <code>.delete(key)</code> remove uma chave, o par de valores <code>.clear()</code> remove todos os pares de chave e valor <code>.entries()</code> retorna uma matriz de todas as chaves na ordem de inserção <code>.values()</code> retorna uma matriz de todos os valores na inserção Instruções do pedido: Defina um objeto JavaScript Map e atribua a ele uma variável chamada myMap. Adicione a chave, par de valores <code>freeCodeCamp</code> , <code>Awesome!</code> para isso. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: O objeto myMap existe.
testString: 'assert(typeof myMap === "object", "The myMap object exists.");'
- text: 'myMap contém o par de valores-chave <code>freeCodeCamp</code> , <code>Awesome!</code> .'
testString: 'assert(myMap.get("freeCodeCamp") === "Awesome!", "myMap contains the key value pair <code>freeCodeCamp</code>, <code>Awesome!</code>.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// change code below this line
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,58 @@
---
id: 587d8254367417b2b2512c70
title: Create and Add to Sets in ES6
challengeType: 1
videoUrl: ''
localeTitle: Criar e adicionar a conjuntos no ES6
---
## Description
undefined
## Instructions
<section id="instructions"> Para este exercício, retorne um conjunto com os seguintes valores: <code>1, 2, 3, &#39;Taco&#39;, &#39;Cat&#39;, &#39;Awesome&#39;</code> </section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Seu <code>Set</code> deve conter apenas os valores <code>1, 2, 3, Taco, Cat, Awesome</code> .'
testString: 'assert(function(){var test = checkSet(); return (test.size == 6) && test.has(1) && test.has(2) && test.has(3) && test.has("Taco") && test.has("Cat") && test.has("Awesome");}, "Your <code>Set</code> should only contain the values <code>1, 2, 3, Taco, Cat, Awesome</code>.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet() {
var set = new Set([1, 2, 3, 3, 2, 1, 2, 3, 1]);
// change code below this line
// change code above this line
console.log(set);
return set;
}
checkSet();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,76 @@
---
id: 587d8258367417b2b2512c80
title: Delete a Leaf Node in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Excluir um nó de folha em uma árvore de pesquisa binária
---
## Description
<section id="description"> Este é o primeiro de três desafios em que implementaremos uma operação mais difícil em árvores de pesquisa binária: exclusão. A exclusão é difícil porque a remoção de nós quebra os links na árvore. Esses links devem ser cuidadosamente restabelecidos para garantir que a estrutura da árvore binária seja mantida. Para algumas exclusões, isso significa que a árvore deve ser reorganizada. Em geral, você encontrará um dos três casos ao tentar excluir um nó: Nó Folha: O destino a excluir tem zero filhos. Um filho: o destino a excluir tem apenas um filho. Dois Filhos: O alvo a deletar tem dois nós filhos. Remover um nó de folha é fácil, nós simplesmente o removemos. Excluir um nó com um filho também é relativamente fácil, basta removê-lo e vinculá-lo ao filho do nó que excluímos. A remoção de um nó com dois filhos é mais difícil, no entanto, porque isso cria dois nós-filhos que precisam ser reconectados à árvore pai. Vamos ver como lidar com este caso no terceiro desafio. Além disso, você precisa estar ciente de alguns casos extremos ao manipular a exclusão. E se a árvore estiver vazia? E se o nó a excluir for o nó raiz? E se houver apenas dois elementos na árvore? Por enquanto, vamos lidar com o primeiro caso em que excluímos um nó de folha. Instruções: Crie um método em nossa árvore binária chamada <code>remove</code> . Vamos construir a lógica para nossa operação de exclusão aqui. Primeiro, você desejará 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, <code>remove</code> deve retornar <code>null</code> . Agora, se o nó de destino for um nó folha sem filhos, a referência pai a ele deverá ser definida como <code>null</code> . Isso 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ó de destino possui, pois isso determinará em qual caso nossa exclusão pertence. Vamos lidar com o segundo e terceiro casos nos próximos desafios. Boa sorte! </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>remove</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == "function")})(), "The binary search tree has a method called <code>remove</code>.");'
- text: Tentar remover um elemento que não existe retorna <code>null</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; return (test.remove(100) == null); })(), "Trying to remove an element that does not exist returns <code>null</code>.");'
- text: 'Se o nó raiz não tiver filhos, a exclusão definirá a raiz como <code>null</code> .'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(500); test.remove(500); return (test.inorder() == null); })(), "If the root node has no children, deleting it sets the root to <code>null</code>.");'
- text: A <code>remove</code> método remove nós folha da árvore
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (test.inorder().join("") == "567"); })(), "The <code>remove</code> method removes leaf nodes from the tree");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// case 1: target has no children, change code below this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,121 @@
---
id: 587d8258367417b2b2512c81
title: Delete a Node with One Child in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Excluir um nó com um filho em uma árvore de pesquisa binária
---
## Description
<section id="description"> Agora que podemos deletar nós de folha vamos para o segundo caso: deletar um nó com um filho. Para este caso, digamos que temos uma árvore com os seguintes nós 1 - 2 - 3, onde 1 é a raiz. Para deletar 2, nós simplesmente precisamos fazer a referência correta em 1 ponto para 3. Mais geralmente para deletar um nó com apenas um filho, nós fazemos a referência do pai do nó o próximo nó na árvore. Instruções: Fornecemos algum código em nosso método <code>remove</code> que realiza as tarefas do último desafio. Encontramos o destino para excluir 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 único filho é uma ramificação esquerda ou direita na árvore e, em seguida, definir a referência correta no pai para apontar para esse nó. Além disso, vamos considerar o caso em que o destino é o nó raiz (isso significa que o nó pai será <code>null</code> ). Sinta-se à vontade para substituir todo o código inicial com o seu próprio, desde que ele passe nos testes. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>remove</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == "function")})(), "The binary search tree has a method called <code>remove</code>.");'
- text: Tentar remover um elemento que não existe retorna <code>null</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; return (test.remove(100) == null); })(), "Trying to remove an element that does not exist returns <code>null</code>.");'
- text: 'Se o nó raiz não tiver filhos, a exclusão definirá a raiz como <code>null</code> .'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(500); test.remove(500); return (test.inorder() == null); })(), "If the root node has no children, deleting it sets the root to <code>null</code>.");'
- text: A <code>remove</code> método remove nós folha da árvore
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (test.inorder().join("") == "567"); })(), "The <code>remove</code> method removes leaf nodes from the tree");'
- text: A <code>remove</code> método remove os nós com uma criança.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(-1); test.add(3); test.add(7); test.add(16); test.remove(16); test.remove(7); test.remove(3); return (test.inorder().join("") == "-1"); })(), "The <code>remove</code> method removes nodes with one child.");'
- text: Remover a raiz de uma árvore com dois nós define o segundo como raiz.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(15); test.add(27); test.remove(15); return (test.inorder().join("") == "27"); })(), "Removing the root in a tree with two nodes sets the second to be the root.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.remove = function(value) {
if (this.root === null) {
return null;
}
var target;
var parent = null;
// find the target value and its parent
(function findValue(node = this.root) {
if (value == node.value) {
target = node;
} else if (value < node.value && node.left !== null) {
parent = node;
return findValue(node.left);
} else if (value < node.value && node.left === null) {
return null;
} else if (value > node.value && node.right !== null) {
parent = node;
return findValue(node.right);
} else {
return null;
}
}).bind(this)();
if (target === null) {
return null;
}
// count the children of the target to delete
var children = (target.left !== null ? 1 : 0) + (target.right !== null ? 1 : 0);
// case 1: target has no children
if (children === 0) {
if (target == this.root) {
this.root = null;
}
else {
if (parent.left == target) {
parent.left = null;
} else {
parent.right = null;
}
}
}
// case 2: target has one child, change code below this line
};
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,139 @@
---
id: 587d8258367417b2b2512c82
title: Delete a Node with Two Children in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Excluir um nó com dois filhos em uma árvore de pesquisa binária
---
## Description
<section id="description"> A remoção de nós que possuem 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 de árvore original. Como podemos reconectá-los? Um método é encontrar o menor valor na subárvore direita do nó de destino e substituir o nó de destino por esse valor. Selecionar a substituição dessa maneira garante que ela seja maior que cada nó na subárvore esquerda, ela se torna o novo pai, mas também menos que cada nó na subárvore direita, ele se torna o novo pai de. Uma vez feita a substituição, o nó de substituição deve ser removido da subárvore direita. Até mesmo essa operação é complicada, porque a substituição pode ser uma folha ou ela mesma pode ser a mãe de uma subárvore direita. Se for uma folha, devemos remover a referência de seus pais para ela. Caso contrário, deve ser o filho certo do alvo. Nesse caso, devemos substituir o valor de destino pelo valor de substituição e fazer com que o destino faça referência ao filho certo da substituição. Instruções: Vamos terminar nosso método <code>remove</code> manipulando o terceiro caso. Nós fornecemos alguns códigos novamente para os dois primeiros casos. Adicione algum código agora para manipular nós de destino com dois filhos. Quaisquer casos de limites a ter em conta? E se a árvore tiver apenas três nós? Quando terminar, isso concluirá nossa operação de exclusão para árvores de pesquisa binária. Bom trabalho, este é um problema muito difícil! </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>remove</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == "function")})(), "The binary search tree has a method called <code>remove</code>.");'
- text: Tentar remover um elemento que não existe retorna <code>null</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == "function") ? (test.remove(100) == null) : false})(), "Trying to remove an element that does not exist returns <code>null</code>.");'
- text: 'Se o nó raiz não tiver filhos, a exclusão definirá a raiz como <code>null</code> .'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; test.add(500); test.remove(500); return (typeof test.remove == "function") ? (test.inorder() == null) : false})(), "If the root node has no children, deleting it sets the root to <code>null</code>.");'
- text: A <code>remove</code> método remove nós folha da árvore
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (typeof test.remove == "function") ? (test.inorder().join("") == "567") : false})(), "The <code>remove</code> method removes leaf nodes from the tree");'
- text: A <code>remove</code> método remove os nós com uma criança.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(-1); test.add(3); test.add(7); test.add(16); test.remove(16); test.remove(7); test.remove(3); return (test.inorder().join("") == "-1"); })(), "The <code>remove</code> method removes nodes with one child.");'
- text: Remover a raiz de uma árvore com dois nós define o segundo como raiz.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(15); test.add(27); test.remove(15); return (test.inorder().join("") == "27"); })(), "Removing the root in a tree with two nodes sets the second to be the root.");'
- text: 'A <code>remove</code> método remove os nós com dois filhos, mantendo a estrutura de árvore de busca binária.'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(1); test.add(4); test.add(3); test.add(7); test.add(9); test.add(11); test.add(14); test.add(15); test.add(19); test.add(50); test.remove(9); if (!test.isBinarySearchTree()) { return false; }; test.remove(11); if (!test.isBinarySearchTree()) { return false; }; test.remove(14); if (!test.isBinarySearchTree()) { return false; }; test.remove(19); if (!test.isBinarySearchTree()) { return false; }; test.remove(3); if (!test.isBinarySearchTree()) { return false; }; test.remove(50); if (!test.isBinarySearchTree()) { return false; }; test.remove(15); if (!test.isBinarySearchTree()) { return false; }; return (test.inorder().join("") == "147"); })(), "The <code>remove</code> method removes nodes with two children while maintaining the binary search tree structure.");'
- text: A raiz pode ser removida em uma árvore de três nós.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== "function") { return false; }; test.add(100); test.add(50); test.add(300); test.remove(100); return (test.inorder().join("") == 50300); })(), "The root can be removed on a tree of three nodes.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.remove = function(value) {
if (this.root === null) {
return null;
}
var target;
var parent = null;
// find the target value and its parent
(function findValue(node = this.root) {
if (value == node.value) {
target = node;
} else if (value < node.value && node.left !== null) {
parent = node;
return findValue(node.left);
} else if (value < node.value && node.left === null) {
return null;
} else if (value > node.value && node.right !== null) {
parent = node;
return findValue(node.right);
} else {
return null;
}
}).bind(this)();
if (target === null) {
return null;
}
// count the children of the target to delete
var children = (target.left !== null ? 1 : 0) + (target.right !== null ? 1 : 0);
// case 1: target has no children
if (children === 0) {
if (target == this.root) {
this.root = null;
}
else {
if (parent.left == target) {
parent.left = null;
} else {
parent.right = null;
}
}
}
// case 2: target has one child
else if (children == 1) {
var newChild = (target.left !== null) ? target.left : target.right;
if (parent === null) {
target.value = newChild.value;
target.left = null;
target.right = null;
} else if (newChild.value < parent.value) {
parent.left = newChild;
} else {
parent.right = newChild;
}
target = null;
}
// case 3: target has two children, change code below this line
};
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,73 @@
---
id: 587d825d367417b2b2512c96
title: Depth-First Search
challengeType: 1
videoUrl: ''
localeTitle: Pesquisa de Profundidade-Primeiro
---
## Description
<section id="description"> Semelhante à <dfn>pesquisa em largura</dfn> , aqui aprenderemos sobre outro algoritmo de travessia de gráfico chamado <dfn>de busca em profundidade</dfn> . Enquanto a pesquisa por largura inicial pesquisa comprimentos de aresta incrementais longe do nó de origem, <dfn>a pesquisa em profundidade</dfn> primeiro desce um caminho de arestas o máximo possível. Uma vez que atinja uma extremidade de um caminho, a pesquisa retrocederá até o último nó com um caminho de borda não visitado e continuará pesquisando. Visualmente, isso é o que o algoritmo está fazendo, onde o nó superior é o ponto inicial da pesquisa. <img class="img-responsive" src="https://camo.githubusercontent.com/aaad9e39961daf34d967c616edeb50abf3bf1235/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37662f44657074682d46697273742d5365617263682e676966"> Uma saída simples desse algoritmo é uma lista de nós que podem ser alcançados de um determinado nó. Portanto, ao implementar esse algoritmo, você precisará acompanhar os nós que você visita. </section>
## Instructions
<section id="instructions"> Escreva uma função <code>dfs()</code> que tenha um <code>graph</code> matriz de adjacência não <code>graph</code> e uma <code>root</code> rótulo de nó como parâmetros. O rótulo do nó será apenas o valor numérico do nó entre <code>0</code> e <code>n - 1</code> , onde <code>n</code> é o número total de nós no gráfico. Sua função deve produzir uma matriz de todos os nós acessíveis pela <code>root</code> . </section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>1</code> deve retornar uma matriz com <code>0</code> , <code>1</code> , <code>2</code> e <code>3</code> .'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 1);})(), [0, 1, 2, 3], "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return an array with <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code>.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>1</code> deve retornar um array com quatro elementos.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 1);})().length === 4, "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return an array with four elements.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> com um nó inicial de <code>3</code> deve retornar um array com <code>3</code> .'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; return dfs(graph, 3);})(), [3], "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>3</code> should return an array with <code>3</code>.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> com um nó inicial de <code>3</code> deve retornar um array com um elemento.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; return dfs(graph, 3);})().length === 1, "The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>3</code> should return an array with one element.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>3</code> deve retornar um array com <code>2</code> e <code>3</code> .'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 3);})(), [2, 3], "The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>3</code> should return an array with <code>2</code> and <code>3</code>.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>3</code> deve retornar um array com dois elementos.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 3);})().length === 2, "The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>3</code> should return an array with two elements.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>0</code> deve retornar uma matriz com <code>0</code> e <code>1</code> .'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 0);})(), [0, 1], "The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return an array with <code>0</code> and <code>1</code>.");'
- text: 'O gráfico de entrada <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> com um nó inicial de <code>0</code> deve retornar um array com dois elementos.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 0);})().length === 2, "The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return an array with two elements.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function dfs(graph, root) {
}
var exDFSGraph = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
];
console.log(dfs(exDFSGraph, 3));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,82 @@
---
id: 587d8257367417b2b2512c7d
title: Find the Minimum and Maximum Height of a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Encontre a altura mínima e máxima de uma árvore de pesquisa binária
---
## Description
<section id="description"> No último desafio, descrevemos um cenário em que uma árvore pode se desequilibrar. Para entender o conceito de equilíbrio, vamos dar uma olhada em outra propriedade da árvore: altura. Altura em uma árvore representa a distância do nó raiz a qualquer nó de folha fornecido. Caminhos diferentes em uma estrutura de árvore altamente ramificada podem ter diferentes alturas, mas para uma determinada árvore haverá uma altura mínima e máxima. Se a árvore estiver balanceada, esses valores serão diferenciados no máximo por um. Isso significa que, em uma árvore balanceada, todos os nós foliares existem dentro do mesmo nível ou, se não estiverem no mesmo nível, estão no máximo um nível à parte. A propriedade do equilíbrio é importante para as árvores porque é o que determina a eficiência das operações das árvores. Como explicamos no último desafio, enfrentamos a pior complexidade do tempo para árvores altamente desequilibradas. Árvores de autoequilíbrio são comumente usadas para explicar esse problema em árvores com conjuntos de dados dinâmicos. Exemplos comuns incluem árvores AVL, árvores vermelhas e pretas e árvores B. Todas essas árvores contêm lógica interna adicional que reequilibra a árvore quando inserções ou exclusões criam um estado de desequilíbrio. Nota: Uma propriedade semelhante à altura é depth, que se refere a quanto um determinado nó é do nó raiz. Instruções: Escreva dois métodos para nossa árvore binária: <code>findMinHeight</code> e <code>findMaxHeight</code> . Esses métodos devem retornar um valor inteiro para a altura mínima e máxima dentro de uma determinada árvore binária, respectivamente. Se o nó estiver vazio, vamos atribuir uma altura de <code>-1</code> (esse é o caso base). Finalmente, adicione um terceiro método <code>isBalanced</code> que retorna <code>true</code> ou <code>false</code> dependendo se a árvore está balanceada ou não. Você pode usar os dois primeiros métodos que acabou de escrever para determinar isso. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>findMinHeight</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMinHeight == "function")})(), "The binary search tree has a method called <code>findMinHeight</code>.");'
- text: A árvore de pesquisa binária tem um método chamado <code>findMaxHeight</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMaxHeight == "function")})(), "The binary search tree has a method called <code>findMaxHeight</code>.");'
- text: A árvore de pesquisa binária tem um método chamado <code>isBalanced</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.isBalanced == "function")})(), "The binary search tree has a method called <code>isBalanced</code>.");'
- text: O método <code>findMinHeight</code> retorna a altura mínima da árvore.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMinHeight !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return (test.findMinHeight() == 1); })(), "The <code>findMinHeight</code> method returns the minimum height of the tree.");'
- text: O método <code>findMaxHeight</code> retorna a altura máxima da árvore.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMaxHeight !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return (test.findMaxHeight() == 5); })(), "The <code>findMaxHeight</code> method returns the maximum height of the tree.");'
- text: Uma árvore vazia retorna uma altura de <code>-1</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMaxHeight !== "function") { return false; }; return (test.findMaxHeight() == -1); })(), "An empty tree returns a height of <code>-1</code>.");'
- text: O método <code>isBalanced</code> retorna true se a árvore for uma árvore de pesquisa binária balanceada.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.isBalanced !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return test.isBalanced(); })(), "The <code>isBalanced</code> method returns true if the tree is a balanced binary search tree.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,78 @@
---
id: 587d8256367417b2b2512c7a
title: Find the Minimum and Maximum Value in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Encontre o valor mínimo e máximo em uma árvore de pesquisa binária
---
## Description
<section id="description"> Esta série de desafios introduzirá a estrutura de dados da árvore. As árvores são uma estrutura de dados importante e versátil na ciência da computação. É claro, o nome deles vem do fato de que, quando visualizados, eles se parecem muito com as árvores com as quais estamos familiarizados no mundo natural. Uma estrutura de dados em árvore começa com um nó, geralmente chamado de raiz, e daqui ramifica-se para 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 no topo; você pode pensar nisso como uma árvore natural virada de cabeça para baixo. Primeiro, vamos descrever algumas terminologias comuns que encontraremos com as árvores. O nó raiz é o topo da árvore. Pontos de dados na árvore são chamados nós. Os nós com ramificações que levam a outros nós são referidos como o pai do nó ao qual o desvio leva (o filho). Outros termos familiares mais complicados se aplicam como você poderia esperar. Uma subárvore refere-se a todos os descendentes de um nó específico, ramos podem ser referidos como arestas e nós de folha são nós no final da árvore que não têm filhos. Finalmente, observe que as árvores são estruturas de dados inerentemente recursivas. Ou seja, quaisquer filhos de um nó são pais de sua própria subárvore e assim por diante. A natureza recursiva das árvores é importante para entender ao projetar algoritmos para operações de árvore comuns. Para começar, discutiremos um tipo específico de árvore, a árvore binária. Na verdade, discutiremos uma árvore binária em particular, uma árvore de busca binária. Vamos descrever o que isso significa. Enquanto a estrutura de dados em árvore pode ter qualquer número de ramificações em um único nó, uma árvore binária pode ter apenas duas ramificações para cada nó. Além disso, uma árvore de pesquisa binária é ordenada com relação às subárvores filho, de modo que o valor de cada nó na subárvore esquerda seja menor ou igual ao valor do nó pai, e o valor de cada nó na subárvore direita seja maior que ou igual ao valor do nó pai. É muito útil visualizar essa relação para entender melhor: <div style="width: 100%; display: flex; justify-content: center; align-items: center;"><img style="width: 100%; max-width: 350px;" src="https://user-images.githubusercontent.com/18563015/32136009-1e665d98-bbd6-11e7-9133-63184f9f9182.png"></div> Agora, esse relacionamento ordenado é muito fácil de ver. Observe que cada valor à esquerda de 8, o nó raiz, é menor que 8 e todo valor à direita é maior que 8. Observe também que essa relação também se aplica a cada uma das subárvores. Por exemplo, o primeiro filho à esquerda é uma subárvore. 3 é o nó pai, e tem exatamente dois nós filhos - pelas regras que governam as árvores de busca binária, sabemos sem sequer ver que o filho esquerdo deste nó (e qualquer um de seus filhos) será menor que 3, e o direito filho (e qualquer um de seus filhos) será maior que 3 (mas também menor que o valor de raiz da estrutura) e assim por diante. As árvores de pesquisa binária são estruturas de dados muito comuns e úteis, pois fornecem tempo logarítmico, no caso médio, para várias operações comuns, como pesquisa, inserção e exclusão. Instruções: vamos começar simples. Definimos o esqueleto de uma estrutura de árvore 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 para a esquerda e para a direita. Estas serão atribuídas subtrees filho, se existirem. Em nossa árvore de pesquisa binária, defina dois métodos, <code>findMin</code> e <code>findMax</code> . Esses métodos devem retornar os valores mínimo e máximo mantidos na árvore de pesquisa binária (não se preocupe em adicionar valores à árvore por enquanto, adicionamos alguns em segundo plano). Se você ficar preso, reflita sobre a invariante que deve ser verdadeira para árvores de busca binária: cada subárvore esquerda é menor ou igual a seu pai e cada subárvore direita é maior que ou igual a seu pai. Digamos também que nossa árvore só pode armazenar valores inteiros. Se a árvore estiver vazia, o método deve retornar <code>null</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>findMin</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMin == "function")})(), "The binary search tree has a method called <code>findMin</code>.");'
- text: A árvore de pesquisa binária tem um método chamado <code>findMax</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMax == "function")})(), "The binary search tree has a method called <code>findMax</code>.");'
- text: O método <code>findMin</code> retorna o valor mínimo na árvore de pesquisa binária.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMin !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return test.findMin() == 1; })(), "The <code>findMin</code> method returns the minimum value in the binary search tree.");'
- text: O método <code>findMax</code> retorna o valor máximo na árvore de pesquisa binária.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMax !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return test.findMax() == 87; })(), "The <code>findMax</code> method returns the maximum value in the binary search tree.");'
- text: Os <code>findMin</code> e <code>findMax</code> métodos retornam <code>null</code> para uma árvore vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMin !== "function") { return false; }; if (typeof test.findMax !== "function") { return false; }; return (test.findMin() == null && test.findMax() == null) })(), "The <code>findMin</code> and <code>findMax</code> methods return <code>null</code> for an empty tree.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,72 @@
---
id: 587d825b367417b2b2512c8c
title: Implement Heap Sort with a Min Heap
challengeType: 1
videoUrl: ''
localeTitle: Implementar a ordenação de heap com uma pilha mínima
---
## Description
<section id="description"> Agora que podemos adicionar e remover elementos, vamos ver alguns dos heaps de aplicativos que podem ser usados. Heaps são comumente usados para implementar filas de prioridade porque eles sempre armazenam um item de maior ou menor valor na primeira posição. Além disso, eles são usados para implementar um algoritmo de classificação chamado heap sort. Vamos ver como fazer isso aqui. A classificação de heap usa um heap mínimo, o contrário de um heap máximo. Um heap mínimo sempre armazena o elemento de menor valor na posição raiz. Ordenação de heap funciona tomando uma matriz não classificada, adicionando cada item na matriz em um heap mínimo e, em seguida, extrair cada item fora do heap min em uma nova matriz. A estrutura de heap min garante que o novo array conterá os itens originais no mínimo para o maior pedido. Este é um dos algoritmos de ordenação mais eficientes, com desempenho médio e pior de O (nlog (n)). Instruções: Vamos implementar a classificação de heap com um heap mínimo. Sinta-se à vontade para adaptar seu código de heap máximo aqui. Crie um objeto MinHeap com métodos de inserção, remoção e classificação. O método de classificação deve retornar uma matriz de todos os elementos no heap min classificados do menor para o maior. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados MinHeap existe.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== "undefined") { test = new MinHeap() }; return (typeof test == "object")})(), "The MinHeap data structure exists.");'
- text: MinHeap tem um método chamado insert.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== "undefined") { test = new MinHeap() } else { return false; }; return (typeof test.insert == "function")})(), "MinHeap has a method called insert.");'
- text: MinHeap tem um método chamado remover.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== "undefined") { test = new MinHeap() } else { return false; }; return (typeof test.remove == "function")})(), "MinHeap has a method called remove.");'
- text: MinHeap tem um método chamado sort.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== "undefined") { test = new MinHeap() } else { return false; }; return (typeof test.sort == "function")})(), "MinHeap has a method called sort.");'
- text: O método de classificação retorna uma matriz contendo todos os itens adicionados ao heap min na ordem classificada.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== "undefined") { test = new MinHeap() } else { return false; }; test.insert(3); test.insert(12); test.insert(5); test.insert(10); test.insert(1); test.insert(27); test.insert(42); test.insert(57); test.insert(5); var result = test.sort(); return (isSorted(result)); })(), "The sort method returns an array containing all items added to the min heap in sorted order.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// check if array is sorted
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
}
// generate a randomly filled array
var array = new Array();
(function createArray(size = 5) {
array.push(+(Math.random() * 100).toFixed(0));
return (size > 1) ? createArray(size - 1) : undefined;
})(25);
var MinHeap = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,59 @@
---
id: 587d8256367417b2b2512c79
title: Incidence Matrix
challengeType: 1
videoUrl: ''
localeTitle: Matriz de Incidência
---
## Description
<section id="description"> Ainda outra maneira de representar um gráfico é colocá-lo em uma <dfn>matriz de incidência.</dfn> Uma <dfn>matriz de incidência</dfn> é uma <dfn>matriz</dfn> bidimensional (2D). De um modo geral, uma matriz de incidência relaciona duas classes diferentes de objetos entre suas duas dimensões. Este tipo de matriz é semelhante a uma matriz de adjacência. No entanto, as linhas e colunas significam outra coisa aqui. Nos gráficos, temos arestas e nós. Estas serão nossas &quot;duas classes diferentes de objetos&quot;. Essa matriz terá as linhas como os nós e as colunas como as arestas. Isso significa que podemos ter um número ímpar de linhas e colunas. Cada coluna representará uma borda exclusiva. Além disso, cada borda conecta 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 está um gráfico de 3 nós com uma borda entre o nó 1 e o nó 3. <blockquote> 1 <br> --- <br> 1 | 1 <br> 2 | 0 <br> 3 | 1 </blockquote> Aqui está um exemplo de uma <code>incidence matrix</code> 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> Abaixo está uma implementação JavaScript da mesma coisa. <blockquote> var incMat = [ <br> [0, 1, 1, 1], <br> [1, 1, 0, 0], <br> [1, 0, 0, 1] <br> [0, 0, 1, 0] <br> ]; </blockquote> Para fazer um gráfico direcionado, use <code>-1</code> para uma aresta deixando um determinado nó e <code>1</code> para uma aresta entrando em um nó. <blockquote> var incMatDirected = [ <br> [0, -1, 1, -1] <br> [-1, 1, 0, 0], <br> [1, 0, 0, 1] <br> [0, 0, -1, 0] <br> ]; </blockquote> Gráficos também podem ter <dfn>pesos</dfn> em suas bordas. Até agora, temos arestas <dfn>não ponderadas</dfn> onde apenas a presença e a falta de aresta é binária ( <code>0</code> ou <code>1</code> ). Você pode ter pesos diferentes dependendo do seu aplicativo. Um peso diferente é representado como números maiores que 1. </section>
## Instructions
<section id="instructions"> Crie uma matriz de incidência de um gráfico não direcionado com cinco nós e quatro arestas. Essa matriz deve estar em uma matriz multidimensional. Esses cinco nós têm relacionamentos após os relacionamentos. A primeira aresta está entre o primeiro e o segundo nó. A segunda aresta fica entre o segundo e o terceiro nó. A terceira borda está entre o terceiro e o quinto nó. E quatro arestas estão entre o quarto e o segundo nó. Todos os pesos das arestas são um e a ordem das arestas é importante. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>incMatUndirected</code> deve conter apenas cinco nós.
testString: 'assert((incMatUndirected.length === 5) && incMatUndirected.map(function(x) { return x.length === 4 }).reduce(function(a, b) { return a && b }) , "<code>incMatUndirected</code> should only contain five nodes.");'
- text: Deve haver uma primeira borda entre o primeiro e o segundo nó.
testString: 'assert((incMatUndirected[0][0] === 1) && (incMatUndirected[1][0] === 1), "There should be a first edge between the first and second node.");'
- text: Deve haver uma segunda borda entre o segundo e o terceiro nó.
testString: 'assert((incMatUndirected[1][1] === 1) && (incMatUndirected[2][1] === 1), "There should be a second edge between the second and third node.");'
- text: Deve haver uma terceira borda entre o terceiro e o quinto nó.
testString: 'assert((incMatUndirected[2][2] === 1) && (incMatUndirected[4][2] === 1), "There should be a third edge between the third and fifth node.");'
- text: Deve haver uma quarta borda entre o segundo e o quarto nó.
testString: 'assert((incMatUndirected[1][3] === 1) && (incMatUndirected[3][3] === 1), "There should be a fourth edge between the second and fourth node.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var incMatUndirected = [
];
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,59 @@
---
id: 587d825a367417b2b2512c8a
title: Insert an Element into a Max Heap
challengeType: 1
videoUrl: ''
localeTitle: Inserir um elemento em um heap máximo
---
## Description
<section id="description"> Agora vamos passar para outra estrutura de dados de árvore, o heap binário. Um heap binário é uma árvore binária parcialmente ordenada que satisfaz a propriedade heap. A propriedade heap especifica um relacionamento entre os nós pai e filho. Você pode ter um heap máximo, no qual todos os nós pai são maiores ou iguais a seus nós filhos ou um heap mínimo, em que o inverso é verdadeiro. Os montes 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 será preenchido da esquerda para a direita. Enquanto heaps binários podem ser implementados como estruturas de árvore com nós que contêm referências esquerda e direita, a ordenação parcial de acordo com a propriedade heap nos permite representar o heap com um array. O relacionamento pai-filho é o que nos interessa e, com aritmética simples, podemos calcular os filhos de qualquer pai e pai de qualquer nó filho. Por exemplo, considere esta representação de array de um heap mininário binário: <code>[ 6, 22, 30, 37, 63, 48, 42, 76 ]</code> O nó raiz é o primeiro elemento, 6. Seus filhos são 22 e 30. Se olharmos no relacionamento entre os índices de matriz desses valores, para o índice i, os filhos são 2 * i + 1 e 2 * i + 2. Similarmente, o elemento no índice 0 é o pai desses dois filhos nos índices 1 e 2. Mais geralmente, podemos encontrar o pai de um nó em qualquer índice com o seguinte: (i - 1) / 2. Esses padrões permanecerão verdadeiros conforme a árvore binária cresce para qualquer tamanho. Finalmente, podemos fazer um pequeno ajuste para tornar essa aritmética ainda mais fácil, ignorando o primeiro elemento da matriz. Isso cria o seguinte relacionamento para qualquer elemento em um determinado índice i: Exemplo Array representação: <code>[ null, 6, 22, 30, 37, 63, 48, 42, 76 ]</code> Filho de um elemento: i * 2 Filho direito de um elemento : i * 2 + 1 O pai de um elemento: i / 2 Depois de enrolar a cabeça na matemática, usar uma representação de matriz é muito útil porque os locais dos nós podem ser rapidamente determinados com essa aritmética e o uso de memória é diminuído porque você não precisa manter referências a nós filhos. Instruções: Aqui vamos criar um heap máximo. Comece apenas criando um método de inserção que adicione elementos ao nosso heap. Durante a inserção, é importante sempre manter a propriedade heap. Para um heap máximo, isso significa que o elemento raiz deve sempre ter o maior valor na árvore e que todos os nós pai devem ser maiores que seus filhos. Para uma implementação de matriz de uma pilha, isso geralmente é realizado em três etapas: Adicione o novo elemento ao final da matriz. Se o elemento for maior que seus pais, troque-os. Continue comutando até que o novo elemento seja menor que seu pai ou você alcance a raiz da árvore. Por fim, adicione um método de impressão que retorne uma matriz de todos os itens que foram adicionados ao heap. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados MaxHeap existe.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() }; return (typeof test == "object")})(), "The MaxHeap data structure exists.");'
- text: MaxHeap tem um método chamado insert.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; return (typeof test.insert == "function")})(), "MaxHeap has a method called insert.");'
- text: MaxHeap tem um método chamado print.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; return (typeof test.print == "function")})(), "MaxHeap has a method called print.");'
- text: O método insert adiciona elementos de acordo com a propriedade heap máximo.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; test.insert(50); test.insert(100); test.insert(700); test.insert(32); test.insert(51); let result = test.print(); return ((result.length == 5) ? result[0] == 700 : result[1] == 700) })(), "The insert method adds elements according to the max heap property.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var MaxHeap = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,74 @@
---
id: 587d8259367417b2b2512c83
title: Invert a Binary Tree
challengeType: 1
videoUrl: ''
localeTitle: Inverta uma árvore binária
---
## Description
<section id="description"> Aqui vamos criar uma função para inverter uma árvore binária. Dada uma árvore binária, queremos produzir uma nova árvore que seja equivalente à imagem espelhada dessa árvore. Executar uma travessia dentro da ordem em uma árvore invertida irá explorar os nós na ordem reversa quando comparado com a travessia dentro da árvore original. Escreva um método para fazer isso chamado <code>invert</code> em nossa árvore binária. Chamar esse método deve inverter a estrutura da árvore atual. Idealmente, gostaríamos de fazer isso no local em tempo linear. Ou seja, apenas visitamos cada nó uma vez e modificamos a estrutura de árvore existente à medida que avançamos, sem usar nenhuma memória adicional. Boa sorte! </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>invert</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.invert == "function")})(), "The binary search tree has a method called <code>invert</code>.");'
- text: O método <code>invert</code> inverte corretamente a estrutura da árvore.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.invert !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); test.invert(); return test.inorder().join("") == "877345348741"; })(), "The <code>invert</code> method correctly inverts the tree structure.");'
- text: Inverter uma árvore vazia retorna <code>null</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.invert !== "function") { return false; }; return (test.invert() == null); })(), "Inverting an empty tree returns <code>null</code>.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,56 @@
---
id: 587d8250367417b2b2512c5e
title: Learn how a Stack Works
challengeType: 1
videoUrl: ''
localeTitle: Aprenda como funciona uma pilha
---
## Description
<section id="description"> Você provavelmente está familiarizado com a pilha de livros em sua mesa. Você provavelmente usou o recurso de desfazer de um editor de texto. Você provavelmente também está acostumado a apertar o botão Voltar do seu telefone para voltar para a visualização anterior no seu aplicativo. Você sabe o que todos eles têm em comum? Todos eles armazenam os dados de uma maneira que você possa percorrer para trás. O livro mais alto na pilha foi o que foi colocado lá por último. Se você remover o livro do topo de sua pilha, exporia o livro que foi colocado antes do último livro e assim por diante. Se você pensar sobre isso, em todos os exemplos acima, você está recebendo o tipo de serviço <dfn>Last-In-First-Out</dfn> . Vamos tentar imitar isso com o nosso código. Esse esquema de armazenamento de dados é chamado de <dfn>pilha</dfn> . Em particular, nós teríamos que implementar o método <code>push()</code> que empurra objetos JavaScript no topo da pilha; e o método <code>pop()</code> , que remove o objeto JavaScript que está no topo da pilha no momento atual. </section>
## Instructions
<section id="instructions"> Aqui temos uma pilha de trabalhos de casa representados como um array: <code>&quot;BIO12&quot;</code> está na base, e <code>&quot;PSY44&quot;</code> está no topo da pilha. Modifique a matriz dada e trate-a como uma <code>stack</code> usando os métodos JavaScript mencionados acima. Remova o elemento superior <code>&quot;PSY44&quot;</code> da pilha. Em seguida, adicione <code>&quot;CS50&quot;</code> para ser o novo elemento superior da pilha. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>homeworkStack</code> deve conter apenas 4 elementos.
testString: 'assert(homeworkStack.length === 4, "<code>homeworkStack</code> should only contain 4 elements.");'
- text: O último elemento no <code>homeworkStack</code> <code>&quot;CS50&quot;</code> deve ser <code>&quot;CS50&quot;</code> .
testString: 'assert(homeworkStack[3] === "CS50", "The last element in <code>homeworkStack</code> should be <code>"CS50"</code>.");'
- text: <code>homeworkStack</code> <code>&quot;PSY44&quot;</code> não deve conter <code>&quot;PSY44&quot;</code> .
testString: 'assert(homeworkStack.indexOf("PSY44") === -1, "<code>homeworkStack</code> should not contain <code>"PSY44"</code>.");'
- text: A declaração inicial <code>homeworkStack</code> não deve ser alterada.
testString: 'assert(code.match(/=/g).length === 1 && /homeworkStack\s*=\s*\["BIO12"\s*,\s*"HIS80"\s*,\s*"MAT122"\s*,\s*"PSY44"\]/.test(code), "The initial declaration of the <code>homeworkStack</code> should not be changed.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var homeworkStack = ["BIO12","HIS80","MAT122","PSY44"];
// Only change code below this line
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,110 @@
---
id: 587d8254367417b2b2512c6e
title: Perform a Difference on Two Sets of Data
challengeType: 1
videoUrl: ''
localeTitle: Realize uma diferença em dois conjuntos de dados
---
## Description
<section id="description"> Neste exercício, vamos realizar uma diferença em dois conjuntos de dados. Vamos criar um método na nossa estrutura de dados <code>Set</code> chamada <code>difference</code> . Uma diferença de conjuntos deve comparar dois conjuntos e retornar os itens presentes no primeiro conjunto que estão ausentes no segundo. Este método deve ter outro <code>Set</code> como argumento e retornar a <code>difference</code> dos dois conjuntos. Por exemplo, se <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> e <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , a diferença de setA e setB é: <code>setA.difference(setB) = [&#39;c&#39;]</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método de <code>difference</code> .
testString: 'assert(function(){var test = new Set(); return (typeof test.difference === "function")}, "Your <code>Set</code> class should have a <code>difference</code> method.");'
- text: A coleção adequada foi retornada
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add("a"); setA.add("b"); setA.add("c"); setB.add("c"); setB.add("d"); var differenceSetAB = setA.difference(setB); return (differenceSetAB.size() === 2) && (differenceSetAB.values() === [ "a", "b" ])}, "The proper collection was returned");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// this method will return the intersection of two sets as a new set
this.intersection = function(otherSet) {
var intersectionSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e){
if(otherSet.has(e)){
intersectionSet.add(e);
}
});
return intersectionSet;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,129 @@
---
id: 587d8254367417b2b2512c6f
title: Perform a Subset Check on Two Sets of Data
challengeType: 1
videoUrl: ''
localeTitle: Executar uma verificação de subconjunto em dois conjuntos de dados
---
## Description
<section id="description"> Neste exercício, vamos realizar um teste de subconjunto em dois conjuntos de dados. Vamos criar um método na nossa estrutura de dados <code>Set</code> chamado <code>subset</code> . Isto irá comparar o primeiro conjunto, contra o segundo e se o primeiro conjunto estiver totalmente contido dentro do Segundo, então ele retornará verdadeiro. Por exemplo, se <code>setA = [&#39;a&#39;,&#39;b&#39;]</code> e <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]</code> , o subconjunto de setA e setB é: <code>setA.subset(setB)</code> deve ser <code>true</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método de <code>union</code> .
testString: 'assert(function(){var test = new Set(); return (typeof test.subset === "function")}, "Your <code>Set</code> class should have a <code>union</code> method.");'
- text: O primeiro Set () estava contido no segundo Set
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add("a"); setB.add("b"); setB.add("c"); setB.add("a"); setB.add("d"); var subsetSetAB = setA.subset(setB);return (subsetSetAB === true)}, "The first Set() was contained in the second Set");'
- text: '<code>[&quot;a&quot;, &quot;b&quot;].subset([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;])</code> deve retornar <code>true</code> &quot;)'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add("a"); setA.add("b"); setB.add("a"); setB.add("b"); setB.add("c"); setB.add("d"); var subsetSetAB = setA.subset(setB); return (subsetSetAB === true)}, "<code>["a", "b"].subset(["a", "b", "c", "d"])</code> should return <code>true</code>");'
- text: '<code>[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;].subset([&quot;a&quot;, &quot;b&quot;])</code> deve retornar <code>false</code> &quot;)'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add("a"); setA.add("b"); setA.add("c"); setB.add("a"); setB.add("b"); var subsetSetAB = setA.subset(setB); return (subsetSetAB === false)}, "<code>["a", "b", "c"].subset(["a", "b"])</code> should return <code>false</code>");'
- text: '<code>[].subset([])</code> deve retornar <code>true</code>'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); var subsetSetAB = setA.subset(setB); return (subsetSetAB === true)}, "<code>[].subset([])</code> should return <code>true</code>");'
- text: '<code>[&quot;a&quot;, &quot;b&quot;].subset([&quot;c&quot;, &quot;d&quot;])</code> deve retornar <code>false</code> &quot;)'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add("a"); setA.add("b"); setB.add("c"); setB.add("d"); var subsetSetAB = setA.subset(setB); return (subsetSetAB === false)}, "<code>["a", "b"].subset(["c", "d"])</code> should return <code>false</code>");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// this method will return the intersection of two sets as a new set
this.intersection = function(otherSet) {
var intersectionSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e){
if(otherSet.has(e)){
intersectionSet.add(e);
}
});
return intersectionSet;
};
// this method will return the difference of two sets as a new set
this.difference = function(otherSet) {
var differenceSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e){
if(!otherSet.has(e)){
differenceSet.add(e);
}
});
return differenceSet;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,87 @@
---
id: 587d8253367417b2b2512c6c
title: Perform a Union on Two Sets
challengeType: 1
videoUrl: ''
localeTitle: Executar uma união em dois conjuntos
---
## Description
<section id="description"> Neste exercício, vamos realizar uma união em dois conjuntos de dados. Vamos criar um método na nossa estrutura de dados <code>Set</code> chamada <code>union</code> . Este método deve ter outro <code>Set</code> como argumento e retornar a <code>union</code> dos dois conjuntos, excluindo quaisquer valores duplicados. Por exemplo, se <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> e <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , a união de setA e setB é: <code>setA.union(setB) = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método de <code>union</code> .
testString: 'assert((function(){var test = new Set(); return (typeof test.union === "function")})(), "Your <code>Set</code> class should have a <code>union</code> method.");'
- text: A coleção adequada foi retornada
testString: 'assert((function(){var setA = new Set(); var setB = new Set(); setA.add("a"); setA.add("b"); setA.add("c"); setB.add("c"); setB.add("d"); var unionSetAB = setA.union(setB); var final = unionSetAB.values(); return (final.indexOf("a") !== -1 && final.indexOf("b") !== -1 && final.indexOf("c") !== -1 && final.indexOf("d") !== -1 && final.length === 4)})(), "The proper collection was returned");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the set
this.size = function() {
return collection.length;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,99 @@
---
id: 587d8253367417b2b2512c6d
title: Perform an Intersection on Two Sets of Data
challengeType: 1
videoUrl: ''
localeTitle: Realizar uma interseção em dois conjuntos de dados
---
## Description
<section id="description"> Neste exercício, vamos realizar uma interseção em dois conjuntos de dados. Vamos criar um método na nossa estrutura de dados <code>Set</code> chamada <code>intersection</code> . Uma interseção de conjuntos representa todos os valores comuns a dois ou mais conjuntos. Este método deve ter outro <code>Set</code> como argumento e retornar a <code>intersection</code> dos dois conjuntos. Por exemplo, se <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> e <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , a interseção de setA e setB é: <code>setA.intersection(setB) = [&#39;a&#39;, &#39;b&#39;]</code> . </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método de <code>intersection</code> .
testString: 'assert(function(){var test = new Set(); return (typeof test.intersection === "function")}, "Your <code>Set</code> class should have a <code>intersection</code> method.");'
- text: A coleção adequada foi retornada
testString: 'assert(function(){ var setA = new Set(); var setB = new Set(); setA.add("a"); setA.add("b"); setA.add("c"); setB.add("c"); setB.add("d"); var intersectionSetAB = setA.intersection(setB); return (intersectionSetAB.size() === 1 && intersectionSetAB.values()[0] === "c")}, "The proper collection was returned");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,61 @@
---
id: 587d825b367417b2b2512c8b
title: Remove an Element from a Max Heap
challengeType: 1
videoUrl: ''
localeTitle: Remover um elemento de um heap máximo
---
## Description
<section id="description"> Agora que podemos adicionar elementos à nossa pilha, vamos ver como podemos remover elementos. A remoção e a inserção de elementos requerem lógica semelhante. Em um heap máximo, você geralmente deseja remover o maior valor, portanto, isso envolve simplesmente extraí-lo da raiz de nossa árvore. Isso vai quebrar a propriedade heap da nossa árvore, então devemos restabelecê-la de alguma forma. Normalmente, para um heap máximo, isso é feito da seguinte maneira: Mova o último elemento do heap para a posição raiz. Se um dos filhos da raiz for maior que ele, troque a raiz pelo filho de maior valor. Continue trocando até que o pai seja maior que os dois filhos ou você alcance o último nível na árvore. Instruções: Adicione um método ao nosso heap máximo chamado remove. Esse método deve retornar o maior valor que foi adicionado ao nosso heap máximo e removê-lo do heap. Ele também deve reordenar o heap para que a propriedade heap seja mantida. Depois de remover um elemento, o próximo elemento remanescente no heap deve se tornar a raiz. Adicione seu método de inserção novamente aqui também. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados MaxHeap existe.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() }; return (typeof test == "object")})(), "The MaxHeap data structure exists.");'
- text: MaxHeap tem um método chamado print.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; return (typeof test.print == "function")})(), "MaxHeap has a method called print.");'
- text: MaxHeap tem um método chamado insert.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; return (typeof test.insert == "function")})(), "MaxHeap has a method called insert.");'
- text: MaxHeap tem um método chamado remover.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; return (typeof test.remove == "function")})(), "MaxHeap has a method called remove.");'
- text: 'O método remove remove o maior elemento do heap máximo, mantendo a propriedade heap máximo.'
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() } else { return false; }; test.insert(30); test.insert(300); test.insert(500); test.insert(10); let result = []; result.push(test.remove()); result.push(test.remove()); result.push(test.remove()); result.push(test.remove()); return (result.join("") == "5003003010") })(), "The remove method removes the greatest element from the max heap while maintaining the max heap property.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var MaxHeap = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,111 @@
---
id: 587d8251367417b2b2512c65
title: Remove Elements from a Linked List by Index
challengeType: 1
videoUrl: ''
localeTitle: Remover elementos de uma lista vinculada por índice
---
## Description
<section id="description"> Antes de passarmos para outra estrutura de dados, vamos obter alguns dos últimos passos de prática com listas vinculadas. Vamos escrever um método <code>removeAt</code> que remova o <code>element</code> em um determinado <code>index</code> . O método deve ser chamado de <code>removeAt(index)</code> . Para remover um <code>element</code> em um determinado <code>index</code> , precisaremos manter uma contagem em execução de cada nó à medida que nos movemos ao longo da lista vinculada. Uma técnica comum usada para percorrer os elementos de uma lista vinculada envolve um <dfn>&#39;runner&#39;</dfn> ou sentinel que &#39;aponta&#39; nos nós que seu código está comparando. No nosso caso, a partir da <code>head</code> da nossa lista, começamos com um <code>currentIndex</code> variável que começa em <code>0</code> . O <code>currentIndex</code> deve incrementar em um para cada nó que passamos. Assim como nosso método <code>remove(element)</code> , precisamos ter cuidado para não deixar o restante da nossa lista órfão quando removemos o nó em nosso método removeAt (index). Mantemos nossos nós contíguos, certificando-nos de que o nó que tenha referência ao nó removido tenha uma referência ao próximo nó. </section>
## Instructions
<section id="instructions"> Escreva um <code>removeAt(index)</code> que remova e retorne um nó em um determinado <code>index</code> . O método deve retornar <code>null</code> se o <code>index</code> fornecido for negativo ou maior que ou igual ao <code>length</code> da lista vinculada. Nota Lembre-se de manter a contagem do <code>currentIndex</code> . </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>LinkedList</code> deve ter um método <code>removeAt</code> .
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.removeAt === "function")}()), "Your <code>LinkedList</code> class should have a <code>removeAt</code> method.");'
- text: Seu método <code>removeAt</code> deve reduzir o <code>length</code> da lista vinculada
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); test.removeAt(1); return test.size() === 2}()), "Your <code>removeAt</code> method should reduce the <code>length</code> of the linked list");'
- text: Seu método <code>removeAt</code> também deve retornar o elemento do nó removido.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); return test.removeAt(1) === "dog"}()), "Your <code>removeAt</code> method should also return the element of the removed node.");'
- text: Seu método <code>removeAt</code> também deve retornar <code>null</code> se o índice fornecido for menor que <code>0</code>
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); return (test.removeAt(-1) === null)}()), "Your <code>removeAt</code> method should also return <code>null</code> if the given index is less than <code>0</code>");'
- text: Seu método <code>removeAt</code> também deve retornar <code>null</code> se o índice fornecido for igual ou maior que o <code>length</code> da lista vinculada.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); return (test.removeAt(3) === null)}()), "Your <code>removeAt</code> method should also return <code>null</code> if the given index is equal or more than the <code>length</code> of the linked list.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){ // {1}
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
var currentNode = head;
var previousNode;
if(currentNode.element === element){
head = currentNode.next;
} else {
while(currentNode.element !== element) {
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = currentNode.next;
}
length --;
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,94 @@
---
id: 587d8251367417b2b2512c63
title: Remove Elements from a Linked List
challengeType: 1
videoUrl: ''
localeTitle: Remover elementos de uma lista vinculada
---
## Description
<section id="description"> O próximo método importante que qualquer implementação de uma lista vinculada precisará é um método <code>remove</code> . Esse método deve pegar o elemento que queremos remover como argumento e, em seguida, pesquisar a lista para localizar e remover o nó que contém esse elemento. Sempre que removemos um nó de uma lista vinculada, é importante que não tornemos o restante da lista acidentalmente órfão. Lembre-se de que a <code>next</code> propriedade de cada nó aponta para o nó que o segue na lista. Se estamos removendo o elemento do meio, digamos, que vai querer se certificar de que temos uma ligação a partir do nó anterior desse elemento <code>next</code> propriedade para o elemento do meio <code>next</code> da propriedade (que é o próximo nó na lista!) Isto pode parecer realmente confuso, então vamos voltar ao exemplo da linha de conga, então temos um bom modelo conceitual. Imagine-se em uma fila de conga, e a pessoa diretamente à sua frente deixa a linha. A pessoa que acabou de sair da linha não tem mais as mãos em ninguém na fila - e você não tem mais as mãos na pessoa que saiu. Você dá um passo à frente e coloca as mãos na próxima pessoa que vê. Se o elemento que desejamos remover é o elemento <code>head</code> , reatribuímos a <code>head</code> ao segundo nó da lista encadeada. </section>
## Instructions
<section id="instructions"> Escreva um método <code>remove</code> que use um elemento e remova-o da lista vinculada. Nota O <code>length</code> da lista deve diminuir em um a cada vez que um elemento é removido da lista vinculada. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>LinkedList</code> deve ter um método <code>remove</code> .
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.remove === "function")}()), "Your <code>LinkedList</code> class should have a <code>remove</code> method.");'
- text: Seu método <code>remove</code> deve reatribuir a <code>head</code> para o segundo nó quando o primeiro nó for removido.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.remove("cat"); return test.head().element === "dog"}()), "Your <code>remove</code> method should reassign <code>head</code> to the second node when the first node is removed.");'
- text: Seu método <code>remove</code> deve diminuir o <code>length</code> da lista vinculada em um para cada nó removido.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.remove("cat"); return test.size() === 1})(), "Your <code>remove</code> method should decrease the <code>length</code> of the linked list by one for every node removed.");'
- text: Seu método <code>remove</code> deve reatribuir a referência do nó anterior do nó removido à <code>next</code> referência do nó removido.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog");test.add("kitten"); test.remove("dog"); return test.head().next.element === "kitten"})(), "Your <code>remove</code> method should reassign the reference of the previous node of the removed node to the removed node&apos;s <code>next</code> reference.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
// Only change code below this line
// Only change code above this line
};
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,75 @@
---
id: 587d8253367417b2b2512c6b
title: Remove from a Set
challengeType: 1
videoUrl: ''
localeTitle: Remover de um conjunto
---
## Description
<section id="description"> Neste exercício, vamos criar uma função de exclusão para o nosso conjunto. A função deve ser nomeada <code>this.remove</code> . Esta função deve aceitar um valor e verificar se existe no conjunto. Em caso afirmativo, remova esse valor do conjunto e retorne true. Caso contrário, retorne falso. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método <code>remove</code> .
testString: 'assert((function(){var test = new Set(); return (typeof test.remove === "function")}()), "Your <code>Set</code> class should have a <code>remove</code> method.");'
- text: Seu método <code>remove</code> só deve remover itens que estão presentes no conjunto.
testString: 'assert.deepEqual((function(){var test = new Set(); test.add("a");test.add("b");test.remove("c"); return test.values(); })(), ["a", "b"], "Your <code>remove</code> method should only remove items that are present in the set.");'
- text: Seu método <code>remove</code> deve remover o item fornecido do conjunto.
testString: 'assert((function(){var test = new Set(); test.add("a");test.add("b");test.remove("a"); var vals = test.values(); return (vals[0] === "b" && vals.length === 1)}()), "Your <code>remove</code> method should remove the given item from the set.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,55 @@
---
id: 587d8254367417b2b2512c71
title: Remove items from a set in ES6
challengeType: 1
videoUrl: ''
localeTitle: Remover itens de um conjunto no ES6
---
## Description
<section id="description"> Vamos praticar itens de remoção de um conjunto ES6 usando o método <code>delete</code> . Primeiro, crie um conjunto ES6 <code>var set = new Set([1,2,3]);</code> Agora, remova um item do seu conjunto com o método de <code>delete</code> . <blockquote> set.delete (1); <br> console.log ([... set]) // deve retornar [2, 3] <blockquote></blockquote></blockquote></section>
## Instructions
<section id="instructions"> Agora, crie um conjunto com os números inteiros 1, 2, 3, 4 e 5. Remova os valores 2 e 5 e, em seguida, retorne o conjunto. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Seu conjunto deve conter os valores 1, 3 e 4'
testString: 'assert(function(){var test = checkSet(); return test.has(1) && test.has(3) && test.has(4) && test.size === 3}, "Your Set should contain the values 1, 3, & 4");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet(){
var set = //Create a set with values 1, 2, 3, 4, & 5
//Remove the value 2
//Remove the value 5
//Return the set
return set;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,78 @@
---
id: 587d825a367417b2b2512c88
title: Reverse a Doubly Linked List
challengeType: 1
videoUrl: ''
localeTitle: Reverse uma lista duplamente vinculada
---
## Description
<section id="description"> Vamos criar mais um método para nossa lista duplamente vinculada chamada reverse, que inverte a lista no lugar. Uma vez que o método é executado, a cabeça deve apontar para a cauda anterior e a cauda deve apontar para a cabeça anterior. Agora, se atravessarmos a lista da cabeça para a cauda, devemos encontrar os nós em ordem inversa em relação à lista original. Tentando reverter uma lista vazia deve retornar null. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados DoublyLinkedList existe.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; return (typeof test == "object")})(), "The DoublyLinkedList data structure exists.");'
- text: O DoublyLinkedList possui um método chamado add.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; if (test.add == undefined) { return false; }; return (typeof test.add == "function")})(), "The DoublyLinkedList has a method called add.");'
- text: O DoublyLinkedList tem um método chamado reverso.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; if (test.reverse == undefined) { return false; }; return (typeof test.reverse == "function")})(), "The DoublyLinkedList has a method called reverse.");'
- text: Invertendo uma lista vazia retorna null.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; return (test.reverse() == null); })(), "Reversing an empty list returns null.");'
- text: O método inverso inverte a lista.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; test.add(58); test.add(61); test.add(32); test.reverse(); return (test.print().join("") == "326158"); })(), "The reverse method reverses the list.");'
- text: As referências seguinte e anterior são mantidas corretamente quando uma lista é invertida.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; test.add(11); test.add(22); test.add(33); test.reverse(); return (test.printReverse().join("") == "112233"); })(), "The next and previous references are correctly maintained when a list is reversed.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
this.head = null;
this.tail = null;
// change code below this line
// change code above this line
};
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,111 @@
---
id: 587d8251367417b2b2512c64
title: Search within a Linked List
challengeType: 1
videoUrl: ''
localeTitle: Pesquisar em uma lista vinculada
---
## Description
<section id="description"> Vamos adicionar alguns métodos mais úteis à nossa classe de lista vinculada. Não seria útil se pudéssemos dizer se a nossa lista estava vazia ou não, como nas nossas classes <code>Stack</code> e <code>Queue</code> ? Também devemos encontrar elementos específicos em nossa lista vinculada. Atravessar estruturas de dados é algo com o qual você vai querer praticar bastante! Vamos criar um método <code>indexOf</code> que <code>indexOf</code> um <code>element</code> como argumento e retorne o <code>index</code> desse elemento na lista vinculada. Se o elemento não for encontrado na lista vinculada, retorne <code>-1</code> . Vamos também implementar um método que faça o oposto: um método <code>elementAt</code> que usa um <code>index</code> como um argumento e retorna o <code>element</code> no <code>index</code> fornecido. Se nenhum <code>element</code> for encontrado, retorne <code>undefined</code> . </section>
## Instructions
<section id="instructions"> Escreva um método <code>isEmpty</code> que verifique se a lista vinculada está vazia, um método <code>indexOf</code> que retorna o <code>index</code> de um determinado elemento e um <code>elementAt</code> que retorna um <code>element</code> em um determinado <code>index.</code> </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>LinkedList</code> deve ter um método <code>indexOf</code> .
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.indexOf === "function")}()), "Your <code>LinkedList</code> class should have a <code>indexOf</code> method.");'
- text: Sua classe <code>LinkedList</code> deve ter um método <code>elementAt</code> .
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.elementAt === "function")}()), "Your <code>LinkedList</code> class should have a <code>elementAt</code> method.");'
- text: Seu método de <code>size</code> deve retornar o tamanho da lista vinculada
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); return test.size() === 3}()), "Your <code>size</code> method should return the length of the linked list");'
- text: Seu método <code>indexOf</code> deve retornar o índice do elemento especificado.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); return test.indexOf("kitten") === 2}()), "Your <code>indexOf</code> method should return the index of the given element.");'
- text: Seu método <code>elementAt</code> deve retornar no elemento em um determinado índice.
testString: 'assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("kitten"); return test.elementAt(1) === "dog"}()), "Your <code>elementAt</code> method should return at element at a given index.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){ // {1}
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
var currentNode = head;
var previousNode;
if(currentNode.element === element){
head = currentNode.next;
} else {
while(currentNode.element !== element) {
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = currentNode.next;
}
length --;
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,82 @@
---
id: 8d1923c8c441eddfaeb5bdef
title: Size of the Set
challengeType: 1
videoUrl: ''
localeTitle: Tamanho do conjunto
---
## Description
<section id="description"> Neste exercício, vamos criar uma função de tamanho para o nosso conjunto. Essa função deve ser nomeada <code>this.size</code> e deve retornar o tamanho da coleção. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Sua classe <code>Set</code> deve ter um método de <code>size</code> .
testString: 'assert((function(){var test = new Set(); return (typeof test.size === "function")}()), "Your <code>Set</code> class should have a <code>size</code> method.");'
- text: O método de <code>size</code> deve retornar o número de elementos na coleção.
testString: 'assert((function(){var test = new Set(); test.add("a");test.add("b");test.remove("a");return (test.size() === 1)}()), "The <code>size</code> method should return the number of elements in the collection.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,54 @@
---
id: 587d8253367417b2b2512c6a
title: Typed Arrays
challengeType: 1
videoUrl: ''
localeTitle: Matrizes digitadas
---
## Description
<section id="description"> Arrays são objetos JavaScript que podem conter muitos elementos diferentes. <code>var complexArr = [1, 5, &quot;2&quot;, &quot;Word&quot;, {&quot;name&quot;: &quot;James&quot;}];</code> Basicamente, o que acontece em segundo plano é que o seu navegador irá fornecer automaticamente a quantidade certa de espaço de memória para esse array. Ele também será alterado conforme necessário, se você adicionar ou remover dados. No entanto, no mundo de alto desempenho e diferentes tipos de elementos, às vezes você precisa ser mais específico sobre a quantidade de memória que é dada a um array. <dfn>Matrizes digitadas</dfn> são a resposta para esse problema. Agora você pode dizer quanta memória deseja dar a um array. Abaixo está uma visão geral básica dos diferentes tipos de matrizes disponíveis e o tamanho em bytes para cada elemento nessa matriz. <table class="table table-striped"><tbody><tr><th> Tipo </th><th> Cada tamanho de 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> Existem duas maneiras de criar esses tipos de matrizes. Uma maneira é criá-lo diretamente. Abaixo está como criar um <code>Int16Array</code> 3 comprimentos. <blockquote> var i8 = novo Int16Array (3); <br> console.log (i8); <br> // Retorna [0, 0, 0] </blockquote> Você também pode criar um <dfn>buffer</dfn> para atribuir quantos dados (em bytes) você deseja que o array ocupe. <strong>Nota</strong> <br> Para criar matrizes tipadas usando buffers, você precisa atribuir o número de bytes para ser um múltiplo dos bytes listados acima. <blockquote> // Cria o mesmo array Int16Array de forma diferente <br> var byteSize = 6; // Precisa ser múltiplo de 2 <br> var buffer = new ArrayBuffer (byteSize); <br> var i8View = new Int16Array (buffer); <br> buffer.byteLength; // Retorna 6 <br> i8View.byteLength; // Retorna 6 <br> console.log (i8View); // Retorna [0, 0, 0] </blockquote> <dfn>Os buffers</dfn> são objetos de finalidade geral que apenas transportam dados. Você não pode acessá-los normalmente. Para acessá-los, você precisa primeiro criar uma <dfn>visão</dfn> . <blockquote> i8View [0] = 42; <br> console.log (i8View); // Retorna [42, 0, 0] </blockquote> <strong>Nota</strong> <br> Matrizes tipadas não possuem alguns dos métodos que os arrays tradicionais têm como <code>.pop()</code> ou <code>.push()</code> . Matrizes digitadas também falham em <code>Array.isArray()</code> que verifica se algo é uma matriz. Embora mais simples, isso pode ser uma vantagem para mecanismos JavaScript menos sofisticados implementá-los. </section>
## Instructions
<section id="instructions"> Primeiro, crie um <code>buffer</code> com 64 bytes. Em seguida, crie uma matriz digitada <code>Int32Array</code> com uma exibição chamada <code>i32View</code> . </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Seu <code>buffer</code> deve ter 64 bytes de tamanho.
testString: 'assert(buffer.byteLength === 64, "Your <code>buffer</code> should be 64 bytes large.");'
- text: Sua visão do <code>i32View</code> do seu buffer deve ter 64 bytes de tamanho.
testString: 'assert(i32View.byteLength === 64, "Your <code>i32View</code> view of your buffer should be 64 bytes large.");'
- text: Sua visão do <code>i32View</code> do seu buffer deve ter 16 elementos de comprimento.
testString: 'assert(i32View.length === 16, "Your <code>i32View</code> view of your buffer should be 16 elements long.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var buffer;
var i32View;
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,57 @@
---
id: 587d8255367417b2b2512c72
title: Use .has and .size on an ES6 Set
challengeType: 1
videoUrl: ''
localeTitle: Use .has e .size em um conjunto ES6
---
## Description
<section id="description"> Vamos examinar os métodos .has e .size disponíveis no objeto Conjunto ES6. Primeiro, crie um conjunto ES6 <code>var set = new Set([1,2,3]);</code> O método .has verificará se o valor está contido no conjunto. <code>var hasTwo = set.has(2);</code> O método .size retornará um inteiro representando o tamanho do Set <code>var howBig = set.size;</code> </section>
## Instructions
<section id="instructions"> Neste exercício, passaremos um array e um valor para a função checkSet (). Sua função deve criar um conjunto ES6 a partir do argumento da matriz. Encontre se o conjunto contém o argumento de valor. Encontre o tamanho do conjunto. E retorne esses dois valores em uma matriz. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>checkSet([4, 5, 6], 3)</code> deve retornar [false, 3]'
testString: 'assert(function(){var test = checkSet([4,5,6], 3); test === [ false, 3 ]}, "<code>checkSet([4, 5, 6], 3)</code> should return [ false, 3 ]");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet(arrToBeSet, checkValue){
// change code below this line
// change code above this line
}
checkSet([ 1, 2, 3], 2); // Should return [ true, 3 ]
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,80 @@
---
id: 587d8258367417b2b2512c7f
title: Use Breadth First Search in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Use a primeira pesquisa em largura em uma árvore de pesquisa binária
---
## Description
<section id="description"> Aqui introduziremos outro método de travessia de árvore: pesquisa em largura. Em contraste com os métodos de pesquisa em profundidade do último desafio, a pesquisa em amplitude explora todos os nós em um determinado nível dentro de uma árvore antes de continuar para o próximo nível. Normalmente, as filas são utilizadas como estruturas de dados auxiliares no projeto de algoritmos de pesquisa em amplitude. Neste método, começamos adicionando o nó raiz a uma fila. Em seguida, iniciamos um loop no qual desenfileiramos o primeiro item da fila, o adicionamos a uma nova matriz e, em seguida, inspecionamos suas subárvores secundárias. Se seus filhos não forem nulos, eles serão enfileirados. Esse processo continua até que a fila esteja vazia. Instruções: Vamos criar um método de pesquisa <code>levelOrder</code> em nossa árvore chamada <code>levelOrder</code> . Esse método deve retornar uma matriz contendo os valores de todos os nós da árvore, explorados de uma maneira abrangente. Certifique-se de retornar os valores na matriz, não os próprios nós. Um nível deve ser percorrido da esquerda para a direita. Em seguida, vamos escrever um método semelhante chamado <code>reverseLevelOrder</code> que realiza a mesma pesquisa, mas na direção inversa (direita para esquerda) em cada nível. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>levelOrder</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.levelOrder == "function")})(), "The binary search tree has a method called <code>levelOrder</code>.");'
- text: A árvore de pesquisa binária tem um método chamado <code>reverseLevelOrder</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.reverseLevelOrder == "function")})(), "The binary search tree has a method called <code>reverseLevelOrder</code>.");'
- text: O método <code>levelOrder</code> retorna uma matriz dos valores do nó da árvore explorados em ordem de nível.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.levelOrder !== "function") { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.levelOrder().join("") == "719038102546"); })(), "The <code>levelOrder</code> method returns an array of the tree node values explored in level order.");'
- text: O método <code>reverseLevelOrder</code> retorna uma matriz dos valores do nó da árvore explorados na ordem inversa do nível.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.reverseLevelOrder !== "function") { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.reverseLevelOrder().join("") == "791108305264"); })(), "The <code>reverseLevelOrder</code> method returns an array of the tree node values explored in reverse level order.");'
- text: O método <code>levelOrder</code> retorna <code>null</code> para uma árvore vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.levelOrder !== "function") { return false; }; return (test.levelOrder() == null); })(), "The <code>levelOrder</code> method returns <code>null</code> for an empty tree.");'
- text: O método <code>reverseLevelOrder</code> retorna <code>null</code> para uma árvore vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.reverseLevelOrder !== "function") { return false; }; return (test.reverseLevelOrder() == null); })(), "The <code>reverseLevelOrder</code> method returns <code>null</code> for an empty tree.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,86 @@
---
id: 587d8257367417b2b2512c7e
title: Use Depth First Search in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: Use a primeira pesquisa de profundidade em uma árvore de pesquisa binária
---
## Description
<section id="description"> Sabemos como pesquisar uma árvore de pesquisa binária por um valor específico. Mas e se quisermos apenas explorar a árvore inteira? Ou se nós não temos uma árvore ordenada e precisamos apenas procurar por um valor? Aqui introduziremos alguns métodos de travessia de árvores que podem ser usados para explorar estruturas de dados de árvores. A primeira é a pesquisa em profundidade. Na pesquisa em profundidade, uma determinada subárvore é explorada o mais profundamente possível antes que a pesquisa continue em outra subárvore. Existem três maneiras pelas quais isso pode ser feito: Em ordem: Comece a pesquisa no nó mais à esquerda e termine no nó mais à direita. Pré-encomenda: explore todas as raízes antes das folhas. Pós-ordem: explore todas as folhas antes das raízes. Como você pode imaginar, você pode escolher diferentes métodos de busca, dependendo do tipo de dados que sua árvore está armazenando e do que você está procurando. Para uma árvore de pesquisa binária, uma passagem in-order retorna os nós na ordem classificada. Instruções: Aqui nós iremos criar estes três métodos de busca em nossa árvore de busca binária. A pesquisa em profundidade é uma operação inerentemente recursiva que continua a explorar outras subárvores, desde que os nós filhos estejam presentes. Depois de entender esse conceito básico, você pode simplesmente reorganizar a ordem na qual você explora os nós e subárvores para produzir qualquer uma das três pesquisas acima. Por exemplo, na pesquisa de pós-ordem, gostaríamos de recorrer a um nó de folha antes de começarmos a retornar qualquer um dos nós, enquanto que na pesquisa de pré-ordem, gostaríamos de retornar os nós primeiro e continuar recursando. descendo a árvore. Defina os métodos <code>inorder</code> , <code>preorder</code> e <code>postorder</code> na nossa árvore. Cada um desses métodos deve retornar uma matriz de itens que representam o percurso da árvore. Certifique-se de retornar os valores inteiros em cada nó da matriz, não os próprios nós. Finalmente, retorne <code>null</code> se a árvore estiver vazia. </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: A estrutura de dados <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado <code>inorder</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.inorder == "function")})(), "The binary search tree has a method called <code>inorder</code>.");'
- text: A árvore de pesquisa binária tem um método chamado <code>preorder</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.preorder == "function")})(), "The binary search tree has a method called <code>preorder</code>.");'
- text: A árvore de pesquisa binária tem um método chamado <code>postorder</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.postorder == "function")})(), "The binary search tree has a method called <code>postorder</code>.");'
- text: O método <code>inorder</code> retorna uma matriz dos valores do nó que resultam de um percurso inorder.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.inorder !== "function") { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.inorder().join("") == "012345678910"); })(), "The <code>inorder</code> method returns an array of the node values that result from an inorder traversal.");'
- text: O método <code>preorder</code> retorna uma matriz dos valores do nó que resultam de uma passagem de pré-ordem.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.preorder !== "function") { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.preorder().join("") == "710325469810"); })(), "The <code>preorder</code> method returns an array of the node values that result from a preorder traversal.");'
- text: O método <code>postorder</code> retorna uma matriz dos valores do nó que resultam de uma passagem de pós-ordem.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.postorder !== "function") { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.postorder().join("") == "024653181097"); })(), "The <code>postorder</code> method returns an array of the node values that result from a postorder traversal.");'
- text: O método <code>inorder</code> retorna <code>null</code> para uma árvore vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.inorder !== "function") { return false; }; return (test.inorder() == null); })(), "The <code>inorder</code> method returns <code>null</code> for an empty tree.");'
- text: O método de <code>preorder</code> retorna <code>null</code> para uma árvore vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.preorder !== "function") { return false; }; return (test.preorder() == null); })(), "The <code>preorder</code> method returns <code>null</code> for an empty tree.");'
- text: O método <code>postorder</code> retorna <code>null</code> para uma árvore vazia.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.postorder !== "function") { return false; }; return (test.postorder() == null); })(), "The <code>postorder</code> method returns <code>null</code> for an empty tree.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,53 @@
---
id: 587d8255367417b2b2512c73
title: Use Spread and Notes for ES5 Set() Integration
challengeType: 1
videoUrl: ''
localeTitle: Use Spread e Notes para Integração do Conjunto ES5 ()
---
## Description
<section id="description"> Você se lembra do operador do spread ES6 <code>...</code> ? <code>...</code> pode levar objetos iteráveis no ES6 e transformá-los em matrizes. Vamos criar um conjunto e verificar a função de propagação. <blockquote> var set = new Set ([1,2,3]); <br> var setToArr = [... set] <br> console.log (setToArr) // retorna [1, 2, 3] </blockquote></section>
## Instructions
<section id="instructions"> Neste exercício, passaremos um objeto set para a função <code>checkSet</code> . Deve retornar uma matriz contendo os valores do conjunto. Agora você aprendeu com sucesso como usar o objeto ES6 <code>Set()</code> , bom trabalho! </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Seu conjunto foi devolvido corretamente!
testString: 'assert(function(){var test = checkSet(new Set([1,2,3,4,5,6,7])); test === [ 1, 2, 3, 4, 5, 6, 7 ]}, "Your Set was returned correctly!");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet(set){
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -0,0 +1,62 @@
---
id: 587d8251367417b2b2512c61
title: Work with Nodes in a Linked List
challengeType: 1
videoUrl: ''
localeTitle: Trabalhar com nós em uma lista vinculada
---
## Description
<section id="description"> Outra estrutura de dados comum que você encontrará na ciência da computação é a <dfn>lista encadeada</dfn> . Uma lista encadeada é uma coleção linear de elementos de dados, chamados &#39;nós&#39;, cada um dos quais aponta para o próximo. Cada <dfn></dfn> de uma lista vinculada contém duas informações importantes: o próprio <code>element</code> e uma referência ao próximo <code>node</code> . Imagine que você está em uma fila de conga. Você tem as mãos na próxima pessoa na linha, e a pessoa atrás de você tem as mãos em você. Você pode ver a pessoa à sua frente, mas eles estão bloqueando a visão das outras pessoas à frente na fila. Um nó é como uma pessoa em uma fila de conga: eles sabem quem são e só podem ver a próxima pessoa na fila, mas não estão cientes das outras pessoas à frente ou atrás delas. </section>
## Instructions
<section id="instructions"> Em nosso editor de código, criamos dois nós, <code>Kitten</code> e <code>Puppy</code> , e conectamos manualmente o nó <code>Kitten</code> ao nó <code>Puppy</code> . Crie um nó <code>Cat</code> and <code>Dog</code> e adicione-os manualmente à linha. </section>
## Tests
<section id='tests'>
```yml
tests:
- text: Seu nó <code>Puppy</code> deve ter uma referência a um nó <code>Cat</code> .
testString: 'assert(Puppy.next.element === "Cat", "Your <code>Puppy</code> node should have a reference to a <code>Cat</code> node.");'
- text: Seu nó <code>Cat</code> deve ter uma referência a um nó <code>Dog</code> .
testString: 'assert(Cat.next.element === "Dog", "Your <code>Cat</code> node should have a reference to a <code>Dog</code> node.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Node = function(element){
this.element = element;
this.next = null;
};
var Kitten = new Node("Kitten");
var Puppy = new Node("Puppy");
Kitten.next = Puppy;
// only add code below this line
// test your code
console.log(Kitten.next);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>