fix(curriculum): fix challenges for russian language

This commit is contained in:
Valeriy S
2019-08-28 16:26:13 +03:00
committed by mrugesh
parent a17c3c44aa
commit 12f65a6742
1418 changed files with 39634 additions and 19395 deletions

View File

@@ -2,15 +2,18 @@
id: 587d8257367417b2b2512c7b
title: Add a New Element to a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301618
localeTitle: Добавление нового элемента в двоичное дерево поиска
---
## Description
<section id="description"> Теперь, когда у нас есть идея об основах, давайте напишем более сложный метод. В этой задаче мы создадим метод добавления новых значений в наше дерево двоичного поиска. Метод следует называть <code>add</code> и он должен принимать целочисленное значение для добавления в дерево. Позаботьтесь о сохранении инварианта двоичного дерева поиска: значение в каждом левом ребне должно быть меньше или равно родительскому значению, а значение в каждом правом дочернем случае должно быть больше или равно родительскому значению. Здесь давайте сделаем так, чтобы наше дерево не могло хранить повторяющиеся значения. Если мы попытаемся добавить значение, которое уже существует, метод должен вернуть значение <code>null</code> . В противном случае, если добавление будет успешным, <code>undefined</code> должен быть возвращен. Подсказка: деревья - это, естественно, рекурсивные структуры данных! </section>
<section id='description'>
Теперь, когда у нас есть идея об основах, давайте напишем более сложный метод. В этой задаче мы создадим метод добавления новых значений в наше дерево двоичного поиска. Метод следует называть <code>add</code> и он должен принимать целочисленное значение для добавления в дерево. Позаботьтесь о сохранении инварианта двоичного дерева поиска: значение в каждом левом ребне должно быть меньше или равно родительскому значению, а значение в каждом правом дочернем случае должно быть больше или равно родительскому значению. Здесь давайте сделаем так, чтобы наше дерево не могло хранить повторяющиеся значения. Если мы попытаемся добавить значение, которое уже существует, метод должен вернуть значение <code>null</code> . В противном случае, если добавление будет успешным, <code>undefined</code> должен быть возвращен. Подсказка: деревья - это, естественно, рекурсивные структуры данных!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Добавление нового элемента в двоичн
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: 'Двоичное дерево поиска имеет метод, называемый <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: Метод add добавляет элементы в соответствии с правилами двоичного дерева поиска.
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: 'Добавление элемента, который уже существует, возвращает <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>");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>add</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.add == 'function')})());
- text: The add method adds elements according to the binary search tree rules.
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()); })());
- text: Adding an element that already exists returns <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; })());
```
@@ -37,28 +40,71 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
isBinarySearchTree() {
if (this.root == null) {
return null;
} else {
var check = true;
function checkTree(node) {
if (node.left != null) {
var left = node.left;
if (left.value > node.value) {
check = false;
} else {
checkTree(left);
}
}
if (node.right != null) {
var right = node.right;
if (right.value < node.value) {
check = false;
} else {
checkTree(right);
}
}
}
checkTree(this.root);
return check;
}
}
};
BinarySearchTree.prototype = {
inOrder() {
if (!this.root) {
return null;
}
var result = new Array();
function traverseInOrder(node) {
node.left && traverseInOrder(node.left);
result.push(node.value);
node.right && traverseInOrder(node.right);
}
traverseInOrder(this.root);
return result;
}
};
```
</div>
@@ -69,6 +115,43 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.add = function(element) {
let current = this.root;
if (!current) {
this.root = new Node(element);
return;
} else {
const searchTree = function(current) {
if (current.value > element) {
if (current.left) {
//si existe
return searchTree(current.left);
} else {
current.left = new Node(element);
return;
}
} else if (current.value < element) {
if (current.right) {
return searchTree(current.right);
} else {
current.right = new Node(element);
return;
}
} else {
return null;
}
};
return searchTree(current);
}
};
}
```
</section>

View File

@@ -2,15 +2,19 @@
id: 587d8252367417b2b2512c67
title: Add Elements at a Specific Index in a Linked List
challengeType: 1
videoUrl: ''
forumTopicId: 301619
localeTitle: Добавить элементы по определенному индексу в связанном списке
---
## Description
<section id="description"> Давайте создадим метод addAt (index, element), который добавит элемент в данный индекс. Точно так же, как мы удаляем элементы с заданным индексом, нам нужно отслеживать currentIndex, когда мы пересекаем связанный список. Когда currentIndex соответствует указанному индексу, нам нужно переназначить следующее свойство предыдущего узла для ссылки на новый добавленный узел. И новый узел должен ссылаться на следующий узел в currentIndex. Возвращаясь к примеру линии conga, новый человек хочет присоединиться к линии, но он хочет присоединиться к середине. Вы находитесь в середине линии, поэтому вы отнимаете руки у человека впереди вас. Новый человек ходит и кладет руки на человека, которого вы когда-то держали, и теперь у вас есть руки на нового человека. Инструкции Создайте метод addAt (index, element), который добавляет элемент в данный индекс. Возвращает false, если элемент не может быть добавлен. Примечание. Не забудьте проверить, является ли данный индекс отрицательным или длиннее длины связанного списка. </section>
<section id='description'>
Давайте создадим метод addAt (index, element), который добавит элемент в данный индекс. Точно так же, как мы удаляем элементы с заданным индексом, нам нужно отслеживать currentIndex, когда мы пересекаем связанный список. Когда currentIndex соответствует указанному индексу, нам нужно переназначить следующее свойство предыдущего узла для ссылки на новый добавленный узел. И новый узел должен ссылаться на следующий узел в currentIndex. Возвращаясь к примеру линии conga, новый человек хочет присоединиться к линии, но он хочет присоединиться к середине. Вы находитесь в середине линии, поэтому вы отнимаете руки у человека впереди вас. Новый человек ходит и кладет руки на человека, которого вы когда-то держали, и теперь у вас есть руки на нового человека. Инструкции Создайте метод addAt (index, element), который добавляет элемент в данный индекс. Возвращает false, если элемент не может быть добавлен. Примечание. Не забудьте проверить, является ли данный индекс отрицательным или длиннее длины связанного списка.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Create an <code>addAt(index,element)</code> method that adds an element at a given index. Return false if an element could not be added.
<strong>Note:</strong> Remember to check if the given index is a negative or is longer than the length of the linked list.
</section>
## Tests
@@ -18,12 +22,12 @@ localeTitle: Добавить элементы по определенному
```yml
tests:
- text: 'Ваш метод <code>addAt</code> должен переназначить <code>head</code> на новый узел, если данный индекс равен 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: 'Ваш метод <code>addAt</code> должен увеличить длину связанного списка по одному для каждого нового узла, добавленного в связанный список.'
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: Метод <code>addAt</code> должен возвращать значение <code>false</code> если узел не смог быть добавлен.
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.");'
- text: Your <code>addAt</code> method should reassign <code>head</code> to the new node when the given index is 0.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.addAt(0,'cat'); return test.head().element === 'cat'}()));
- text: Your <code>addAt</code> method should increase the length of the linked list by one for each new node added to the linked list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.addAt(0,'cat'); return test.size() === 3}()));
- text: Your <code>addAt</code> method should return <code>false</code> if a node was unable to be added.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); return (test.addAt(4,'cat') === false); }()));
```
@@ -34,6 +38,54 @@ tests:
<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 {
var 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
function LinkedList() {
var length = 0;
@@ -67,25 +119,28 @@ function LinkedList() {
}
length++;
};
// Only change code below this line
// Only change code above this line
this.addAt = function (index, element) {
if (index > length || index < 0) {
return false;
}
var newNode = new Node(element);
var currentNode = head;
if (index === 0) {
head = newNode;
} else {
var previousNode = null;
var i = 0;
while (currentNode && i < index) {
previousNode = currentNode;
currentNode = currentNode.next;
i++;
}
previousNode.next = newNode;
}
newNode.next = currentNode;
length++;
}
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@@ -2,29 +2,33 @@
id: 587d8256367417b2b2512c77
title: Adjacency List
challengeType: 1
videoUrl: ''
forumTopicId: 301620
localeTitle: Список прилавков
---
## Description
<section id="description"> Графы могут быть представлены по-разному. Здесь мы описываем один способ, который называется <dfn>списком смежности</dfn> . Список смежности по существу представляет собой маркированный список, в котором левой стороной является узел, а правая сторона - список всех других узлов, к которым он подключен. Ниже приведен список смежности. <blockquote> Node1: Node2, Node3 <br> Node2: Node1 <br> Node3: Node1 </blockquote> Выше - неориентированный граф, потому что <code>Node1</code> подключен к <code>Node2</code> и <code>Node3</code> , и эта информация соответствует соединениям <code>Node2</code> и <code>Node3</code> . Список смежности для ориентированного графа будет означать, что каждая строка списка показывает направление. Если выше было указано, то <code>Node2: Node1</code> будет означать, что направленный край указывает от <code>Node2</code> на <code>Node1</code> . Мы можем представить неориентированный граф выше как список смежности, помещая его в объект JavaScript. <blockquote> var undirectedG = { <br> Node1: [&quot;Node2&quot;, &quot;Node3&quot;], <br> Node2: [&quot;Node1&quot;], <br> Node3: [&quot;Node1&quot;] <br> }; </blockquote> Это также можно более просто представить в виде массива, где узлы имеют только цифры, а не строковые метки. <blockquote> var unirectedGArr = [ <br> [1, 2], # Node1 <br> [0], # Node2 <br> [0] # Node3 <br> ]; </blockquote></section>
<section id='description'>
Графы могут быть представлены по-разному. Здесь мы описываем один способ, который называется <dfn>списком смежности</dfn> . Список смежности по существу представляет собой маркированный список, в котором левой стороной является узел, а правая сторона - список всех других узлов, к которым он подключен. Ниже приведен список смежности. <blockquote> Node1: Node2, Node3 <br> Node2: Node1 <br> Node3: Node1 </blockquote> Выше - неориентированный граф, потому что <code>Node1</code> подключен к <code>Node2</code> и <code>Node3</code> , и эта информация соответствует соединениям <code>Node2</code> и <code>Node3</code> . Список смежности для ориентированного графа будет означать, что каждая строка списка показывает направление. Если выше было указано, то <code>Node2: Node1</code> будет означать, что направленный край указывает от <code>Node2</code> на <code>Node1</code> . Мы можем представить неориентированный граф выше как список смежности, помещая его в объект JavaScript. <blockquote> var undirectedG = { <br> Node1: [&quot;Node2&quot;, &quot;Node3&quot;], <br> Node2: [&quot;Node1&quot;], <br> Node3: [&quot;Node1&quot;] <br> }; </blockquote> Это также можно более просто представить в виде массива, где узлы имеют только цифры, а не строковые метки. <blockquote> var unirectedGArr = [ <br> [1, 2], # Node1 <br> [0], # Node2 <br> [0] # Node3 <br> ]; </blockquote>
</section>
## Instructions
<section id="instructions"> Создайте социальную сеть как неориентированный граф с 4 узлами / людьми по имени <code>James</code> , <code>Jill</code> , <code>Jenny</code> и <code>Jeff</code> . Между Джеймсом и Джеффом, Джил и Дженни, Джеффом и Дженни. </section>
<section id='instructions'>
Создайте социальную сеть как неориентированный граф с 4 узлами / людьми по имени <code>James</code> , <code>Jill</code> , <code>Jenny</code> и <code>Jeff</code> . Между Джеймсом и Джеффом, Джил и Дженни, Джеффом и Дженни.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>undirectedAdjList</code> должен содержать только четыре узла.
testString: 'assert(Object.keys(undirectedAdjList).length === 4, "<code>undirectedAdjList</code> should only contain four nodes.");'
- text: Между <code>Jeff</code> и <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: Между <code>Jill</code> и <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: Между <code>Jeff</code> и <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>.");'
- text: <code>undirectedAdjList</code> should only contain four nodes.
testString: assert(Object.keys(undirectedAdjList).length === 4);
- text: There should be an edge between <code>Jeff</code> and <code>James</code>.
testString: assert(undirectedAdjList.James.indexOf("Jeff") !== -1 && undirectedAdjList.Jeff.indexOf("James") !== -1);
- text: There should be an edge between <code>Jill</code> and <code>Jenny</code>.
testString: assert(undirectedAdjList.Jill.indexOf("Jenny") !== -1 && undirectedAdjList.Jill.indexOf("Jenny") !== -1);
- text: There should be an edge between <code>Jeff</code> and <code>Jenny</code>.
testString: assert(undirectedAdjList.Jeff.indexOf("Jenny") !== -1 && undirectedAdjList.Jenny.indexOf("Jeff") !== -1);
```
@@ -36,21 +40,24 @@ tests:
<div id='js-seed'>
```js
var undirectedAdjList = {
};
var undirectedAdjList = {};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
var undirectedAdjList = {
James: ['Jeff'],
Jill: ['Jenny'],
Jenny: ['Jill', 'Jeff'],
Jeff: ['James', 'Jenny']
};
```
</section>

View File

@@ -2,31 +2,35 @@
id: 587d8256367417b2b2512c78
title: Adjacency Matrix
challengeType: 1
videoUrl: ''
forumTopicId: 301621
localeTitle: Матрица смежности
---
## Description
<section id="description"> Другим способом представления графика является его размещение в <dfn>матрице смежности</dfn> . Матрица <dfn>смежности</dfn> представляет собой двумерный (2D) массив, где каждый вложенный массив имеет такое же количество элементов, что и внешний массив. Другими словами, это матрица или сетка чисел, где числа представляют собой ребра. Нули означают, что нет границ или отношений. <blockquote> 1 2 3 <br> ------ <br> 1 | 0 1 1 <br> 2 | 1 0 0 <br> 3 | 1 0 0 </blockquote> Выше - очень простой, неориентированный граф, где у вас есть три узла, где первый узел подключен ко второму и третьему узлам. <strong>Примечание</strong> . Числа в верхней и левой частях матрицы являются только метками для узлов. Ниже приведена реализация JavaScript того же самого. <blockquote> var adjMat = [ <br> [0, 1, 1], <br> [1, 0, 0], <br> [1, 0, 0] <br> ]; </blockquote> В отличие от списка смежности, каждая «строка» матрицы должна иметь такое же количество элементов, что и узлы в графике. Здесь у нас есть три-три матрицы, что означает, что мы имеем три узла в нашем графике. Ориентированный граф будет похож. Ниже приведен график, в котором первый узел имеет ребро, указывающее на второй узел, а затем второй узел имеет ребро, указывающее на третий узел. <blockquote> var adjMatDirected = [ <br> [0, 1, 0], <br> [0, 0, 1], <br> [0, 0, 0] <br> ]; </blockquote> Графики также могут иметь <dfn>веса</dfn> по краям. До сих пор у нас есть <dfn>невзвешенные</dfn> края, где только наличие и отсутствие ребра двоично ( <code>0</code> или <code>1</code> ). Вы можете иметь разные веса в зависимости от вашего приложения. </section>
<section id='description'>
Другим способом представления графика является его размещение в <dfn>матрице смежности</dfn> . Матрица <dfn>смежности</dfn> представляет собой двумерный (2D) массив, где каждый вложенный массив имеет такое же количество элементов, что и внешний массив. Другими словами, это матрица или сетка чисел, где числа представляют собой ребра. Нули означают, что нет границ или отношений. <blockquote> 1 2 3 <br> ------ <br> 1 | 0 1 1 <br> 2 | 1 0 0 <br> 3 | 1 0 0 </blockquote> Выше - очень простой, неориентированный граф, где у вас есть три узла, где первый узел подключен ко второму и третьему узлам. <strong>Примечание</strong> . Числа в верхней и левой частях матрицы являются только метками для узлов. Ниже приведена реализация JavaScript того же самого. <blockquote> var adjMat = [ <br> [0, 1, 1], <br> [1, 0, 0], <br> [1, 0, 0] <br> ]; </blockquote> В отличие от списка смежности, каждая «строка» матрицы должна иметь такое же количество элементов, что и узлы в графике. Здесь у нас есть три-три матрицы, что означает, что мы имеем три узла в нашем графике. Ориентированный граф будет похож. Ниже приведен график, в котором первый узел имеет ребро, указывающее на второй узел, а затем второй узел имеет ребро, указывающее на третий узел. <blockquote> var adjMatDirected = [ <br> [0, 1, 0], <br> [0, 0, 1], <br> [0, 0, 0] <br> ]; </blockquote> Графики также могут иметь <dfn>веса</dfn> по краям. До сих пор у нас есть <dfn>невзвешенные</dfn> края, где только наличие и отсутствие ребра двоично ( <code>0</code> или <code>1</code> ). Вы можете иметь разные веса в зависимости от вашего приложения.
</section>
## Instructions
<section id="instructions"> Создайте матрицу смежности неориентированного графа с пятью узлами. Эта матрица должна быть в многомерном массиве. Эти пять узлов имеют отношения между первым и четвертым узлами, первым и третьим узлом, третьим и пятым узлами и четвертым и пятым узлами. Все весовые коэффициенты являются единичными. </section>
<section id='instructions'>
Создайте матрицу смежности неориентированного графа с пятью узлами. Эта матрица должна быть в многомерном массиве. Эти пять узлов имеют отношения между первым и четвертым узлами, первым и третьим узлом, третьим и пятым узлами и четвертым и пятым узлами. Все весовые коэффициенты являются единичными.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>undirectedAdjList</code> должен содержать только пять узлов.
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: Между первым и четвертым узлами должен быть край.
testString: 'assert((adjMatUndirected[0][3] === 1) && (adjMatUndirected[3][0] === 1), "There should be an edge between the first and fourth node.");'
- text: Между первым и третьим узлом должен быть край.
testString: 'assert((adjMatUndirected[0][2] === 1) && (adjMatUndirected[2][0] === 1), "There should be an edge between the first and third node.");'
- text: Между третьим и пятым узлами должен быть край.
testString: 'assert((adjMatUndirected[2][4] === 1) && (adjMatUndirected[4][2] === 1), "There should be an edge between the third and fifth node.");'
- text: Между четвертым и пятым узлом должен быть край.
testString: 'assert((adjMatUndirected[3][4] === 1) && (adjMatUndirected[4][3] === 1), "There should be an edge between the fourth and fifth node.");'
- text: <code>undirectedAdjList</code> should only contain five nodes.
testString: assert((adjMatUndirected.length === 5) && adjMatUndirected.map(function(x) { return x.length === 5 }).reduce(function(a, b) { return a && b }) );
- text: There should be an edge between the first and fourth node.
testString: assert((adjMatUndirected[0][3] === 1) && (adjMatUndirected[3][0] === 1));
- text: There should be an edge between the first and third node.
testString: assert((adjMatUndirected[0][2] === 1) && (adjMatUndirected[2][0] === 1));
- text: There should be an edge between the third and fifth node.
testString: assert((adjMatUndirected[2][4] === 1) && (adjMatUndirected[4][2] === 1));
- text: There should be an edge between the fourth and fifth node.
testString: assert((adjMatUndirected[3][4] === 1) && (adjMatUndirected[4][3] === 1));
```
@@ -38,21 +42,25 @@ tests:
<div id='js-seed'>
```js
var adjMatUndirected = [
];
var adjMatUndirected = [];
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
var adjMatUndirected = [
[0, 0, 1, 1, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 1, 1, 0]
];
```
</section>

View File

@@ -2,29 +2,33 @@
id: 587d825c367417b2b2512c90
title: Breadth-First Search
challengeType: 1
videoUrl: ''
forumTopicId: 301622
localeTitle: Поиск по ширине
---
## Description
<section id="description"> До сих пор мы изучили разные способы создания представлений графиков. Что теперь? Один естественный вопрос - какие расстояния между любыми двумя узлами графика? Введите <dfn>алгоритмы обхода графа</dfn> . <dfn>Алгоритмы</dfn> траверса - это алгоритмы для перемещения или посещения узлов в графе. Одним типом алгоритма обхода является алгоритм поиска ширины. Этот алгоритм начинается с одного узла, сначала посещает всех его соседей, которые находятся на одном крае, а затем переходит к каждому из своих соседей. Визуально это то, что делает алгоритм. <img class="img-responsive" src="https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966"> Чтобы реализовать этот алгоритм, вам нужно будет ввести структуру графика и узел, с которого вы хотите начать. Во-первых, вы хотите знать расстояния от стартового узла. Это вы хотите сначала начать все свои расстояния на некоторое количество, например <code>Infinity</code> . Это дает ссылку на случай, когда узел может быть недоступен из вашего стартового узла. Затем вы захотите перейти от стартового узла к своим соседям. Эти соседи находятся на одном крае, и в этот момент вы должны добавить одну единицу расстояния до расстояний, которые вы отслеживаете. Наконец, важной структурой данных, которая поможет реализовать алгоритм поиска по ширине, является очередь. Это массив, в котором вы можете добавлять элементы в один конец и удалять элементы с другого конца. Это также известно как структура данных <dfn>FIFO</dfn> или <dfn>First-In-First-Out</dfn> . </section>
<section id='description'>
До сих пор мы изучили разные способы создания представлений графиков. Что теперь? Один естественный вопрос - какие расстояния между любыми двумя узлами графика? Введите <dfn>алгоритмы обхода графа</dfn> . <dfn>Алгоритмы</dfn> траверса - это алгоритмы для перемещения или посещения узлов в графе. Одним типом алгоритма обхода является алгоритм поиска ширины. Этот алгоритм начинается с одного узла, сначала посещает всех его соседей, которые находятся на одном крае, а затем переходит к каждому из своих соседей. Визуально это то, что делает алгоритм. <img class="img-responsive" src="https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966"> Чтобы реализовать этот алгоритм, вам нужно будет ввести структуру графика и узел, с которого вы хотите начать. Во-первых, вы хотите знать расстояния от стартового узла. Это вы хотите сначала начать все свои расстояния на некоторое количество, например <code>Infinity</code> . Это дает ссылку на случай, когда узел может быть недоступен из вашего стартового узла. Затем вы захотите перейти от стартового узла к своим соседям. Эти соседи находятся на одном крае, и в этот момент вы должны добавить одну единицу расстояния до расстояний, которые вы отслеживаете. Наконец, важной структурой данных, которая поможет реализовать алгоритм поиска по ширине, является очередь. Это массив, в котором вы можете добавлять элементы в один конец и удалять элементы с другого конца. Это также известно как структура данных <dfn>FIFO</dfn> или <dfn>First-In-First-Out</dfn> .
</section>
## Instructions
<section id="instructions"> Напишите функцию <code>bfs()</code> которая принимает граф матрицы смежности (двумерный массив) и корень метки узла в качестве параметров. Метка узла будет просто целочисленным значением узла между <code>0</code> и <code>n - 1</code> , где <code>n</code> - общее количество узлов в графе. Ваша функция выведет пары ключ-значение объекта JavaScript с узлом и его удалением от корня. Если узел не может быть достигнут, он должен иметь расстояние до <code>Infinity</code> . </section>
<section id='instructions'>
Напишите функцию <code>bfs()</code> которая принимает граф матрицы смежности (двумерный массив) и корень метки узла в качестве параметров. Метка узла будет просто целочисленным значением узла между <code>0</code> и <code>n - 1</code> , где <code>n</code> - общее количество узлов в графе. Ваша функция выведет пары ключ-значение объекта JavaScript с узлом и его удалением от корня. Если узел не может быть достигнут, он должен иметь расстояние до <code>Infinity</code> .
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Входной график <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>1</code> должен возвращать <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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> с начальным узлом <code>1</code> должен возвращать <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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>0</code> должен возвращать <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: 'Входной график <code>[[0, 1], [1, 0]]</code> с начальным узлом <code>0</code> должен возвращать <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>");'
- text: '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>'
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})})());'
- text: '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>'
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})})());'
- text: '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>'
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})})());'
- text: '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>'
testString: 'assert((function() { var graph = [[0, 1], [1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1})})());'
```
@@ -55,12 +59,33 @@ console.log(bfs(exBFSGraph, 3));
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
// Source: http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html
function isEquivalent(a, b) {
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
return false;
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
```
</div>
@@ -71,6 +96,38 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function bfs(graph, root) {
// Distance object returned
var nodesLen = {};
// Set all distances to infinity
for (var i = 0; i < graph.length; i++) {
nodesLen[i] = Infinity;
}
nodesLen[root] = 0; // ...except root node
var queue = [root]; // Keep track of nodes to visit
var current; // Current node traversing
// Keep on going until no more nodes to traverse
while (queue.length !== 0) {
current = queue.shift();
// Get adjacent nodes from current node
var curConnected = graph[current]; // Get layer of edges from current
var neighborIdx = []; // List of nodes with edges
var idx = curConnected.indexOf(1); // Get first edge connection
while (idx !== -1) {
neighborIdx.push(idx); // Add to list of neighbors
idx = curConnected.indexOf(1, idx + 1); // Keep on searching
}
// Loop through neighbors and get lengths
for (var j = 0; j < neighborIdx.length; j++) {
// Increment distance for nodes traversed
if (nodesLen[neighborIdx[j]] === Infinity) {
nodesLen[neighborIdx[j]] = nodesLen[current] + 1;
queue.push(neighborIdx[j]); // Add new neighbors to queue
}
}
}
return nodesLen;
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8257367417b2b2512c7c
title: Check if an Element is Present in a Binary Search Tree
challengeType: 1
videoUrl: ''
localeTitle: 'Проверьте, присутствует ли элемент в дереве двоичного поиска'
forumTopicId: 301623
localeTitle: Проверьте, присутствует ли элемент в дереве двоичного поиска
---
## Description
<section id="description"> Теперь, когда у нас есть общее представление о том, какое бинарное дерево поиска давайте поговорим об этом чуть подробнее. Двоичные деревья поиска предоставляют логарифмическое время для общих операций поиска, вставки и удаления в среднем случае и линейного времени в худшем случае. Почему так? Каждая из этих основных операций требует от нас найти элемент в дереве (или в случае вставки, чтобы найти, куда он должен идти), и из-за древовидной структуры каждого родительского узла мы разветвляемся влево или вправо и фактически исключаем половину размера оставшегося дерева. Это делает поиск пропорциональным логарифму числа узлов в дереве, что создает логарифмическое время для этих операций в среднем случае. Хорошо, но как насчет худшего случая? Ну, подумайте о построении дерева из следующих значений, добавив их слева направо: <code>10</code> , <code>12</code> , <code>17</code> , <code>25</code> . Следуя нашим правилам для двоичного дерева поиска, мы добавим <code>12</code> справа от <code>10</code> , <code>17</code> справа от него и <code>25</code> справа от него. Теперь наше дерево напоминает связанный список и, пройдя его, чтобы найти <code>25</code> , потребовало бы, чтобы мы проходили все элементы линейным способом. Следовательно, линейное время в худшем случае. Проблема здесь в том, что дерево неуравновешено. Мы рассмотрим немного больше, что это означает в следующих задачах. Инструкции: В этой задаче мы создадим утилиту для нашего дерева. Напишите метод <code>isPresent</code> который принимает целочисленное значение в качестве входных данных и возвращает логическое значение для наличия или отсутствия этого значения в двоичном дереве поиска. </section>
<section id='description'>
Теперь, когда у нас есть общее представление о том, какое бинарное дерево поиска давайте поговорим об этом чуть подробнее. Двоичные деревья поиска предоставляют логарифмическое время для общих операций поиска, вставки и удаления в среднем случае и линейного времени в худшем случае. Почему так? Каждая из этих основных операций требует от нас найти элемент в дереве (или в случае вставки, чтобы найти, куда он должен идти), и из-за древовидной структуры каждого родительского узла мы разветвляемся влево или вправо и фактически исключаем половину размера оставшегося дерева. Это делает поиск пропорциональным логарифму числа узлов в дереве, что создает логарифмическое время для этих операций в среднем случае. Хорошо, но как насчет худшего случая? Ну, подумайте о построении дерева из следующих значений, добавив их слева направо: <code>10</code> , <code>12</code> , <code>17</code> , <code>25</code> . Следуя нашим правилам для двоичного дерева поиска, мы добавим <code>12</code> справа от <code>10</code> , <code>17</code> справа от него и <code>25</code> справа от него. Теперь наше дерево напоминает связанный список и, пройдя его, чтобы найти <code>25</code> , потребовало бы, чтобы мы проходили все элементы линейным способом. Следовательно, линейное время в худшем случае. Проблема здесь в том, что дерево неуравновешено. Мы рассмотрим немного больше, что это означает в следующих задачах. Инструкции: В этой задаче мы создадим утилиту для нашего дерева. Напишите метод <code>isPresent</code> который принимает целочисленное значение в качестве входных данных и возвращает логическое значение для наличия или отсутствия этого значения в двоичном дереве поиска.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
In this challenge, we will create a utility for our tree. Write a method <code>isPresent</code> which takes an integer value as input and returns a boolean value for the presence or absence of that value in the binary search tree.
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: 'Проверьте, присутствует ли элемент
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: 'Двоичное дерево поиска имеет метод, называемый <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: 'Метод <code>isPresent</code> корректно проверяет наличие или отсутствие элементов, добавленных в дерево.'
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> обрабатывает случаи, когда дерево пусто.'
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.");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>isPresent</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.isPresent == 'function')})());
- text: The <code>isPresent</code> method correctly checks for the presence or absence of elements added to the tree.
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) ); })());
- text: <code>isPresent</code> handles cases where the tree is empty.
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; })());
```
@@ -37,28 +40,57 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
}
};
```
</div>
@@ -69,6 +101,25 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
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.isPresent = function (value) {
var current = this.root
while (current) {
if (value === current.value) {
return true;
}
current = value < current.value ? current.left : current.right;
}
return false;
}
}
```
</section>

View File

@@ -2,15 +2,19 @@
id: 587d8255367417b2b2512c75
title: Create a Circular Queue
challengeType: 1
videoUrl: ''
forumTopicId: 301625
localeTitle: Создание круговой очереди
---
## Description
<section id="description"> В этом вызове вы создадите круговую очередность. Круговая очередь - это в основном очередь, которая записывает в конец коллекции, а затем начинает записывать себя в начале коллекции. Это тип структуры данных имеет некоторые полезные приложения в определенных ситуациях. Например, круговая очередь может использоваться для потоковой передачи. Как только очередь заполнена, новые мультимедийные данные просто начинают перезаписывать старые данные. Хорошим способом проиллюстрировать эту концепцию является массив: <blockquote> [1, 2, 3, 4, 5] <br> ^ Читать @ 0 <br> ^ Написать @ 0 </blockquote> Здесь чтение и запись находятся в положении <code>0</code> . Теперь очередь получает 3 новые записи <code>a</code> , <code>b</code> и <code>c</code> . Теперь наша очередь выглядит так: <blockquote> [a, b, c, 4, 5] <br> ^ Читать @ 0 <br> ^ Написать @ 3 </blockquote> Как читает читатель, он может удалить значения или сохранить их: <blockquote> [null, null, null, 4, 5] <br> ^ Читать @ 3 <br> ^ Написать @ 3 </blockquote> Когда запись достигает конца массива, он возвращается к началу: <blockquote> [f, null, null, d, e] <br> ^ Читать @ 3 <br> ^ Пишите @ 1 </blockquote> Этот подход требует постоянного объема памяти, но позволяет обрабатывать файлы большего размера. Инструкции: В этой задаче мы реализуем круговую очередь. Круговая очередь должна обеспечивать <code>enqueue</code> и <code>dequeue</code> методы , которые позволяют считывать и записывать данные в очередь. Сам класс должен также принять целое число, которое вы можете использовать, чтобы указать размер очереди при ее создании. Мы написали стартовую версию этого класса для вас в редакторе кода. Когда вы ставите объекты в очередь, указатель записи должен продвигаться вперед и возвращаться к началу, как только он достигнет конца очереди. Аналогично, указатель чтения должен продвигаться вперед при удалении элементов. Указателю записи не следует пропускать указатель чтения (наш класс не позволит вам перезаписывать данные, которые вы еще не читали), и указатель чтения не должен продвигать прошлые данные, которые вы написали. Кроме того, метод <code>enqueue</code> должен возвращать элемент, который вы указали, если он успешно и в противном случае возвращает <code>null</code> . Аналогичным образом, когда вы удаляете элемент, он должен быть возвращен, и если вы не можете удалить из очереди, вы должны вернуть <code>null</code> . </section>
<section id='description'>
В этом вызове вы создадите круговую очередность. Круговая очередь - это в основном очередь, которая записывает в конец коллекции, а затем начинает записывать себя в начале коллекции. Это тип структуры данных имеет некоторые полезные приложения в определенных ситуациях. Например, круговая очередь может использоваться для потоковой передачи. Как только очередь заполнена, новые мультимедийные данные просто начинают перезаписывать старые данные. Хорошим способом проиллюстрировать эту концепцию является массив: <blockquote> [1, 2, 3, 4, 5] <br> ^ Читать @ 0 <br> ^ Написать @ 0 </blockquote> Здесь чтение и запись находятся в положении <code>0</code> . Теперь очередь получает 3 новые записи <code>a</code> , <code>b</code> и <code>c</code> . Теперь наша очередь выглядит так: <blockquote> [a, b, c, 4, 5] <br> ^ Читать @ 0 <br> ^ Написать @ 3 </blockquote> Как читает читатель, он может удалить значения или сохранить их: <blockquote> [null, null, null, 4, 5] <br> ^ Читать @ 3 <br> ^ Написать @ 3 </blockquote> Когда запись достигает конца массива, он возвращается к началу: <blockquote> [f, null, null, d, e] <br> ^ Читать @ 3 <br> ^ Пишите @ 1 </blockquote> Этот подход требует постоянного объема памяти, но позволяет обрабатывать файлы большего размера. Инструкции: В этой задаче мы реализуем круговую очередь. Круговая очередь должна обеспечивать <code>enqueue</code> и <code>dequeue</code> методы , которые позволяют считывать и записывать данные в очередь. Сам класс должен также принять целое число, которое вы можете использовать, чтобы указать размер очереди при ее создании. Мы написали стартовую версию этого класса для вас в редакторе кода. Когда вы ставите объекты в очередь, указатель записи должен продвигаться вперед и возвращаться к началу, как только он достигнет конца очереди. Аналогично, указатель чтения должен продвигаться вперед при удалении элементов. Указателю записи не следует пропускать указатель чтения (наш класс не позволит вам перезаписывать данные, которые вы еще не читали), и указатель чтения не должен продвигать прошлые данные, которые вы написали. Кроме того, метод <code>enqueue</code> должен возвращать элемент, который вы указали, если он успешно и в противном случае возвращает <code>null</code> . Аналогичным образом, когда вы удаляете элемент, он должен быть возвращен, и если вы не можете удалить из очереди, вы должны вернуть <code>null</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
In this challenge we will implement a circular queue. The circular queue should provide `enqueue` and `dequeue` methods which allow you to read from and write to the queue. The class itself should also accept an integer argument which you can use to specify the size of the queue when created. We've written the starting version of this class for you in the code editor. When you enqueue items to the queue, the write pointer should advance forward and loop back to the beginning once it reaches the end of the queue. Likewise, the read pointer should advance forward as you dequeue items. The write pointer should not be allowed to move past the read pointer (our class won't let you overwrite data you haven't read yet) and the read pointer should not be able to advance past data you have written.
In addition, the `enqueue` method should return the item you enqueued if it is successful; otherwise it will return `null`. Similarly, when you dequeue an item, that item should be returned and if you cannot dequeue an item you should return `null`.
</section>
## Tests
@@ -18,16 +22,16 @@ localeTitle: Создание круговой очереди
```yml
tests:
- text: Метод <code>enqueue</code> добавляет элементы в круговую очередь.
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: Вы не можете выставлять объекты за указателем чтения.
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: Метод <code>dequeue</code> удаляет объекты из очереди.
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: 'После того, как элемент будет удален, его положение в очереди должно быть сброшено до <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: 'Пытаясь перечеркнуть указатель записи, возвращает значение <code>null</code> и не продвигает указатель записи.'
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.");'
- text: The <code>enqueue</code> method adds items to the circular queue.
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; })());
- text: You cannot enqueue items past the read pointer.
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; })());
- text: The <code>dequeue</code> method dequeues items from the queue.
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; })());
- text: After an item is dequeued its position in the queue should be reset to <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; })());
- text: Trying to dequeue past the write pointer returns <code>null</code> and does not advance the write pointer.
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; })());
```
@@ -51,14 +55,12 @@ class CircularQueue {
this.queue.push(null);
size--;
}
}
print() {
return this.queue;
}
enqueue(item) {
// Only change code below this line
@@ -76,14 +78,58 @@ class CircularQueue {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
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
console.log(this.write, this.max);
if (this.queue[this.write] === null) {
this.queue[this.write++] = item;
if (this.write > this.max) {
this.write = 0;
}
return item;
}
return null;
// Only change code above this line
}
dequeue() {
// Only change code below this line
if (this.queue[this.read] !== null) {
let item = this.queue[this.read];
this.queue[this.read++] = null;
if (this.read > this.max) {
this.read = 0;
}
return item;
}
return null;
// Only change code above this line
}
}
```
</section>

View File

@@ -2,37 +2,41 @@
id: 587d825a367417b2b2512c87
title: Create a Doubly Linked List
challengeType: 1
videoUrl: ''
forumTopicId: 301626
localeTitle: Создать двойной список
---
## Description
<section id="description"> Все связанные списки, которые мы создали до сих пор, представляют собой отдельные списки. Здесь мы создадим <dfn>двусвязный список</dfn> . Как следует из названия, узлы в двусвязном списке имеют ссылки на следующий и предыдущий узел в списке. Это позволяет нам перемещаться по списку в обоих направлениях, но для этого требуется больше памяти, потому что каждый узел должен содержать дополнительную ссылку на предыдущий узел в списке. </section>
<section id='description'>
Все связанные списки, которые мы создали до сих пор, представляют собой отдельные списки. Здесь мы создадим <dfn>двусвязный список</dfn> . Как следует из названия, узлы в двусвязном списке имеют ссылки на следующий и предыдущий узел в списке. Это позволяет нам перемещаться по списку в обоих направлениях, но для этого требуется больше памяти, потому что каждый узел должен содержать дополнительную ссылку на предыдущий узел в списке.
</section>
## Instructions
<section id="instructions"> Мы предоставили объект <code>Node</code> и запустили наш <code>DoublyLinkedList</code> . Давайте добавим два метода в наш дважды связанный список, называемый <code>add</code> и <code>remove</code> . <code>add</code> метод должен добавить данный элемент в список , а <code>remove</code> метод должен удалить все вхождения данного элемента в списке. Будьте внимательны при обработке этих возможных случаев, например, для удаления первого или последнего элемента. Кроме того, удаление любого элемента в пустом списке должно возвращать значение <code>null</code> . </section>
<section id='instructions'>
Мы предоставили объект <code>Node</code> и запустили наш <code>DoublyLinkedList</code> . Давайте добавим два метода в наш дважды связанный список, называемый <code>add</code> и <code>remove</code> . <code>add</code> метод должен добавить данный элемент в список , а <code>remove</code> метод должен удалить все вхождения данного элемента в списке. Будьте внимательны при обработке этих возможных случаев, например, для удаления первого или последнего элемента. Кроме того, удаление любого элемента в пустом списке должно возвращать значение <code>null</code> .
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Существует структура данных DoublyLinkedList.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; return (typeof test == "object")})(), "The DoublyLinkedList data structure exists.");'
- text: 'У DoublyLinkedList есть метод, называемый 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: 'У DoublyLinkedList есть метод, называемый 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: Удаление элемента из пустого списка возвращает 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: Метод добавления добавляет элементы в список.
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: Каждый узел отслеживает предыдущий узел.
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: Первый элемент можно удалить из списка.
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: Последний элемент можно удалить из списка.
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.");'
- text: The DoublyLinkedList data structure exists.
testString: assert((function() { var test = false; if (typeof DoublyLinkedList !== 'undefined') { test = new DoublyLinkedList() }; return (typeof test == 'object')})());
- text: The DoublyLinkedList has a method called 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')})());
- text: The DoublyLinkedList has a method called 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')})());
- text: Removing an item from an empty list returns null.
testString: assert((function() { var test = false; if (typeof DoublyLinkedList !== 'undefined') { test = new DoublyLinkedList() }; return (test.remove(100) == null); })());
- text: The add method adds items to the list.
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'); })());
- text: Each node keeps track of the previous node.
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'); })());
- text: The first item can be removed from the list.
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' ) })());
- text: The last item can be removed from the list.
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' ) })());
```
@@ -60,12 +64,41 @@ var DoublyLinkedList = function() {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
DoublyLinkedList.prototype = {
print() {
if (this.head == null) {
return null;
} else {
var result = new Array();
var node = this.head;
while (node.next != null) {
result.push(node.data);
node = node.next;
};
result.push(node.data);
return result;
};
},
printReverse() {
if (this.tail == null) {
return null;
} else {
var result = new Array();
var node = this.tail;
while (node.prev != null) {
result.push(node.data);
node = node.prev;
};
result.push(node.data);
return result;
};
}
};
```
</div>
@@ -78,4 +111,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,15 +2,19 @@
id: 587d825b367417b2b2512c8e
title: Create a Hash Table
challengeType: 1
videoUrl: ''
forumTopicId: 301627
localeTitle: Создание таблицы хешей
---
## Description
<section id="description"> В этой задаче мы узнаем о хэш-таблицах. Хэш-таблица используется для реализации ассоциативных массивов или сопоставлений пар ключ-значение, таких как объекты и Карты, которые мы только что изучали. Например, объект JavaScript может быть реализован как хэш-таблица (его фактическая реализация будет зависеть от среды, в которой он работает). Способ работы хеш-таблицы состоит в том, что он принимает ключевой ввод и делит этот ключ на некоторое числовое значение. Это числовое значение затем используется как фактический ключ, связанное значение сохраняется. Затем, если вы снова попытаетесь получить доступ к тому же ключу, хеширующая функция обработает ключ, вернет тот же числовой результат, который затем будет использоваться для поиска связанного значения. Это обеспечивает очень эффективное время поиска O (n) в среднем. Хэш-таблицы могут быть реализованы как массивы с хеш-функциями, производящими индексы массивов в заданном диапазоне. В этом методе выбор размера массива важен, как и функция хэширования. Например, что, если функция хэширования дает одно и то же значение для двух разных ключей? Это называется столкновением. Один из способов обработки коллизий - просто сохранить обе пары ключ-значение в этом индексе. Затем, после поиска либо, вам придется перебирать ведро предметов, чтобы найти ключ, который вы ищете. Хорошая функция хэширования минимизирует столкновения для поддержания эффективного времени поиска. Здесь мы не будем беспокоиться о деталях хэширования или реализации хеш-таблицы, мы просто попытаемся получить общее представление о том, как они работают. Инструкции: Давайте создадим базовую функциональность хеш-таблицы. Мы создали наивную функцию хэширования для вас. Вы можете передать строковое значение в хэш функции, и оно вернет хешированное значение, которое вы можете использовать в качестве ключа для хранения. Храните элементы на основе этого хешированного значения в объекте this.collection. Создайте эти три метода: добавьте, удалите и найдите. Первый должен принять пару значений ключа для добавления в хеш-таблицу. Второй должен удалить пару ключ-значение при передаче ключа. Третий должен принять ключ и вернуть связанное значение или null, если ключ отсутствует. Обязательно напишите свой код для учета конфликтов! </section>
<section id='description'>
В этой задаче мы узнаем о хэш-таблицах. Хэш-таблица используется для реализации ассоциативных массивов или сопоставлений пар ключ-значение, таких как объекты и Карты, которые мы только что изучали. Например, объект JavaScript может быть реализован как хэш-таблица (его фактическая реализация будет зависеть от среды, в которой он работает). Способ работы хеш-таблицы состоит в том, что он принимает ключевой ввод и делит этот ключ на некоторое числовое значение. Это числовое значение затем используется как фактический ключ, связанное значение сохраняется. Затем, если вы снова попытаетесь получить доступ к тому же ключу, хеширующая функция обработает ключ, вернет тот же числовой результат, который затем будет использоваться для поиска связанного значения. Это обеспечивает очень эффективное время поиска O (n) в среднем. Хэш-таблицы могут быть реализованы как массивы с хеш-функциями, производящими индексы массивов в заданном диапазоне. В этом методе выбор размера массива важен, как и функция хэширования. Например, что, если функция хэширования дает одно и то же значение для двух разных ключей? Это называется столкновением. Один из способов обработки коллизий - просто сохранить обе пары ключ-значение в этом индексе. Затем, после поиска либо, вам придется перебирать ведро предметов, чтобы найти ключ, который вы ищете. Хорошая функция хэширования минимизирует столкновения для поддержания эффективного времени поиска. Здесь мы не будем беспокоиться о деталях хэширования или реализации хеш-таблицы, мы просто попытаемся получить общее представление о том, как они работают. Инструкции: Давайте создадим базовую функциональность хеш-таблицы. Мы создали наивную функцию хэширования для вас. Вы можете передать строковое значение в хэш функции, и оно вернет хешированное значение, которое вы можете использовать в качестве ключа для хранения. Храните элементы на основе этого хешированного значения в объекте this.collection. Создайте эти три метода: добавьте, удалите и найдите. Первый должен принять пару значений ключа для добавления в хеш-таблицу. Второй должен удалить пару ключ-значение при передаче ключа. Третий должен принять ключ и вернуть связанное значение или null, если ключ отсутствует. Обязательно напишите свой код для учета конфликтов!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Let's create the basic functionality of a hash table. We've created a naive hashing function for you to use. You can pass a string value to the function <code>hash</code> and it will return a hashed value you can use as a key for storage. Store items based on this hashed value in the <code>this.collection</code> object. Create these three methods: <code>add</code>, <code>remove</code>, and <code>lookup</code>. The first should accept a key value pair to add to the hash table. The second should remove a key-value pair when passed a key. The third should accept a key and return the associated value or <code>null</code> if the key is not present.
Be sure to write your code to account for collisions!
</section>
## Tests
@@ -18,22 +22,22 @@ localeTitle: Создание таблицы хешей
```yml
tests:
- text: Структура данных HashTable существует.
testString: 'assert((function() { var test = false; if (typeof HashTable !== "undefined") { test = new HashTable() }; return (typeof test === "object")})(), "The HashTable data structure exists.");'
- text: В HashTable есть метод добавления.
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: У метода HashTable есть метод удаления.
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: У метода HashTable есть метод поиска.
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: 'Метод add добавляет пары ключевых значений, и метод поиска возвращает значения, связанные с данным ключом.'
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: Метод remove принимает ключ как ввод и удаляет связанную пару ключей.
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: Элементы добавляются с помощью хэш-функции.
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: Хэш-таблица обрабатывает конфликты.
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.");'
- text: The HashTable data structure exists.
testString: assert((function() { var test = false; if (typeof HashTable !== 'undefined') { test = new HashTable() }; return (typeof test === 'object')})());
- text: The HashTable has an add method.
testString: assert((function() { var test = false; if (typeof HashTable !== 'undefined') { test = new HashTable() }; return ((typeof test.add) === 'function')})());
- text: The HashTable has an remove method.
testString: assert((function() { var test = false; if (typeof HashTable !== 'undefined') { test = new HashTable() }; return ((typeof test.remove) === 'function')})());
- text: The HashTable has an lookup method.
testString: assert((function() { var test = false; if (typeof HashTable !== 'undefined') { test = new HashTable() }; return ((typeof test.lookup) === 'function')})());
- text: The add method adds key value pairs and the lookup method returns the values associated with a given key.
testString: assert((function() { var test = false; if (typeof HashTable !== 'undefined') { test = new HashTable() }; test.add('key', 'value'); return (test.lookup('key') === 'value')})());
- text: The remove method accepts a key as input and removes the associated key value pair.
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)})());
- text: Items are added using the hash function.
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)})());
- text: The hash table handles collisions.
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')})());
```
@@ -46,11 +50,13 @@ tests:
```js
var called = 0;
var hash = (string) => {
var hash = string => {
called++;
var hash = 0;
for (var i = 0; i < string.length; i++) { hash += string.charCodeAt(i); }
return hash;
var hashed = 0;
for (var i = 0; i < string.length; i++) {
hashed += string.charCodeAt(i);
}
return hashed;
};
var HashTable = function() {
this.collection = {};
@@ -62,23 +68,24 @@ var HashTable = function() {
</div>
### Before Test
### Before Tests
<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;
};
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
@@ -87,4 +94,5 @@ var HashTable = function() {
```js
// solution required
```
</section>

View File

@@ -2,29 +2,38 @@
id: 587d8251367417b2b2512c62
title: Create a Linked List Class
challengeType: 1
videoUrl: ''
forumTopicId: 301628
localeTitle: Создать класс связанного списка
---
## Description
undefined
<section id='description'>
Let's create a <code>linked list</code> class. Every linked list should start out with a few basic properties: a <code>head</code> (the first item in your list) and a <code>length</code> (number of items in your list). Sometimes you'll see implementations of linked lists that incorporate a <code>tail</code> for the last element of the list, but for now we'll just stick with these two. Whenever we add an element to the linked list, our <code>length</code> property should be incremented by one.
We'll want to have a way to add items to our linked list, so the first method we'll want to create is the <code>add</code> method.
If our list is empty, adding an element to our linked list is straightforward enough: we just wrap that element in a <code>Node</code> class, and we assign that node to the <code>head</code> of our linked list.
But what if our list already has one or more members? How do we add an element to the list? Recall that each node in a linked list has a <code>next</code> property. To add a node to the list, find the last node in the list, and point that last node's <code>next</code> property at our new node. (Hint: you know you've reached the end of a linked list when a node's <code>next</code> property is <code>null</code>.)
</section>
## Instructions
undefined
<section id='instructions'>
Write an add method that assigns the first node you push to the linked list to the <code>head</code>; after that, whenever adding a node, every node should be referenced by the previous node's <code>next</code> property.
Note
Your list's <code>length</code> should increase by one every time an element is added to the linked list.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Класс <code>LinkedList</code> должен иметь метод <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: Класс <code>LinkedList</code> должен назначить <code>head</code> первому добавленному узлу.
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: ''
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: <code>size</code> вашего класса <code>LinkedList</code> должен равняться количеству узлов в связанном списке.
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.");'
- text: Your <code>LinkedList</code> class should have a <code>add</code> method.
testString: assert((function(){var test = new LinkedList(); return (typeof test.add === 'function')}()));
- text: Your <code>LinkedList</code> class should assign <code>head</code> to the first node added.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); return test.head().element === 'cat'}()));
- text: The previous <code>node</code> in your <code>LinkedList</code> class should have reference to the newest node created.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); return test.head().next.element === 'dog'}()));
- text: The <code>size</code> of your <code>LinkedList</code> class should equal the amount of nodes in the linked list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); return test.size() === 2}()));
```
@@ -64,14 +73,46 @@ function LinkedList() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
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
if (head == null) {
head = new Node(element);
}
else {
let currentNode = head;
while (currentNode.next != null) {
// currentNode.next will be last node of linked list after loop
currentNode = currentNode.next;
}
currentNode.next = new Node(element);
}
length++;
// Only change code above this line
};
}
```
</section>

View File

@@ -2,15 +2,29 @@
id: 8d5823c8c441eddfaeb5bdef
title: Create a Map Data Structure
challengeType: 1
videoUrl: ''
forumTopicId: 301629
localeTitle: Создание структуры данных карты
---
## Description
<section id="description"> Следующие несколько проблем будут охватывать карты и хеш-таблицы. Карты - это структуры данных, в которых хранятся пары ключ-значение. В JavaScript они доступны для нас как объекты. Карты обеспечивают быстрый поиск сохраненных элементов на основе значений ключей и являются очень распространенными и полезными структурами данных. Инструкции: Давайте попробуем создать собственную карту. Поскольку объекты JavaScript обеспечивают гораздо более эффективную структуру карты, чем все, что мы могли бы здесь написать, это в первую очередь предназначено для обучения. Однако объекты JavaScript предоставляют нам определенные операции. Что, если мы хотим определить пользовательские операции? Используйте объект <code>Map</code> указанный здесь как обертка вокруг <code>object</code> JavaScript. Создайте следующие методы и операции над объектом Map: <ul><li> <code>add</code> принимает пару <code>key, value</code> для добавления на карту. </li><li> <code>remove</code> принимает ключ и удаляет связанную пару <code>key, value</code> </li><li> <code>get</code> принимает <code>key</code> и возвращает сохраненное <code>value</code> </li><li> <code>has</code> принимает <code>key</code> и возвращает <dfn>истину</dfn> , если ключ существует , или <dfn>ложь</dfn> , если она не делает. </li><li> <code>values</code> возвращают массив всех значений на карте </li><li> <code>size</code> возвращает количество элементов на карте </li><li> <code>clear</code> пустую карту </li></ul></section>
<section id='description'>
Следующие несколько проблем будут охватывать карты и хеш-таблицы. Карты - это структуры данных, в которых хранятся пары ключ-значение. В JavaScript они доступны для нас как объекты. Карты обеспечивают быстрый поиск сохраненных элементов на основе значений ключей и являются очень распространенными и полезными структурами данных. Инструкции: Давайте попробуем создать собственную карту. Поскольку объекты JavaScript обеспечивают гораздо более эффективную структуру карты, чем все, что мы могли бы здесь написать, это в первую очередь предназначено для обучения. Однако объекты JavaScript предоставляют нам определенные операции. Что, если мы хотим определить пользовательские операции? Используйте объект <code>Map</code> указанный здесь как обертка вокруг <code>object</code> JavaScript. Создайте следующие методы и операции над объектом Map: <ul><li> <code>add</code> принимает пару <code>key, value</code> для добавления на карту. </li><li> <code>remove</code> принимает ключ и удаляет связанную пару <code>key, value</code> </li><li> <code>get</code> принимает <code>key</code> и возвращает сохраненное <code>value</code> </li><li> <code>has</code> принимает <code>key</code> и возвращает <dfn>истину</dfn> , если ключ существует , или <dfn>ложь</dfn> , если она не делает. </li><li> <code>values</code> возвращают массив всех значений на карте </li><li> <code>size</code> возвращает количество элементов на карте </li><li> <code>clear</code> пустую карту </li></ul>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Let's get some practice creating our own map. Because JavaScript objects provide a much more efficient map structure than anything we could write here, this is intended primarily as a learning exercise. However, JavaScript objects only provide us with certain operations. What if we wanted to define custom operations?
Use the <code>Map</code> object provided here as a wrapper around a JavaScript <code>object</code>. Create the following methods and operations on the Map object:
<ul>
<li><code>add</code> accepts a <code>key, value</code> pair to add to the map.</li>
<li><code>remove</code> accepts a key and removes the associated <code>key, value</code> pair</li>
<li><code>get</code> accepts a <code>key</code> and returns the stored <code>value</code></li>
<li><code>has</code> accepts a <code>key</code> and returns <dfn>true</dfn> if the key exists or <dfn>false</dfn> if it doesn't.</li>
<li><code>values</code> returns an array of all the values in the map</li>
<li><code>size</code> returns the number of items in the map</li>
<li><code>clear</code> empties the map</li>
</ul>
</section>
## Tests
@@ -18,20 +32,20 @@ localeTitle: Создание структуры данных карты
```yml
tests:
- text: Структура данных карты существует.
testString: 'assert((function() { var test = false; if (typeof Map !== "undefined") { test = new Map() }; return (typeof test == "object")})(), "The Map data structure exists.");'
- text: 'Объект Map имеет следующие методы: добавление, удаление, получение, наличие, значения, очистка и размер.'
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: Метод добавления добавляет элементы к карте.
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: Метод has возвращает true для добавленных элементов и false для отсутствующих элементов.
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: Метод get принимает ключи как входные данные и возвращает связанные значения.
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: 'Метод values ​​возвращает все значения, хранящиеся на карте, в виде строк в массиве.'
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: 'Метод clear очищает карту, а метод size возвращает количество элементов, присутствующих на карте.'
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.");'
- text: The Map data structure exists.
testString: assert((function() { var test = false; if (typeof Map !== 'undefined') { test = new Map() }; return (typeof test == 'object')})());
- text: 'The Map object has the following methods: add, remove, get, has, values, clear, and 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')})());
- text: The add method adds items to the map.
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)})());
- text: The has method returns true for added items and false for absent items.
testString: assert((function() { var test = false; if (typeof Map !== 'undefined') { test = new Map() }; test.add('test','value'); return (test.has('test') && !test.has('false'))})());
- text: The get method accepts keys as input and returns the associated values.
testString: assert((function() { var test = false; if (typeof Map !== 'undefined') { test = new Map() }; test.add('abc','def'); return (test.get('abc') == 'def')})());
- text: The values method returns all the values stored in the map as strings in an array.
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)})());
- text: The clear method empties the map and the size method returns the number of items present in the map.
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)})());
```
@@ -53,8 +67,6 @@ var Map = function() {
</div>
</section>
## Solution
@@ -63,4 +75,5 @@ var Map = function() {
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8255367417b2b2512c74
title: Create a Priority Queue Class
challengeType: 1
videoUrl: ''
forumTopicId: 301630
localeTitle: Создание класса очереди приоритетов
---
## Description
<section id="description"> В этом вызове вы создадите очередь приоритетов. Приоритетная очередь - это особый тип очереди, в которой элементы могут иметь дополнительную информацию, которая определяет их приоритет. Это может быть просто представлено целым числом. Приоритет элемента переопределяет порядок размещения при определении элементов последовательности. Если элемент с более высоким приоритетом помещается в очередь после элементов с более низким приоритетом, элемент с более высоким приоритетом будет удален до всех остальных. Например, предположим, что у нас есть очередь приоритетов с тремя элементами: <code>[[&#39;kitten&#39;, 2], [&#39;dog&#39;, 2], [&#39;rabbit&#39;, 2]]</code> Здесь второе значение (целое число) представляет приоритет элемента , Если мы ставим в очередь <code>[&#39;human&#39;, 1]</code> с приоритетом <code>1</code> (при условии, что более низкие приоритеты заданы приоритетом), тогда это будет первый элемент, который будет удален. Коллекция понравится: <code>[[&#39;human&#39;, 1], [&#39;kitten&#39;, 2], [&#39;dog&#39;, 2], [&#39;rabbit&#39;, 2]]</code> . Мы начали писать <code>PriorityQueue</code> в редакторе кода. Вам нужно будет добавить метод <code>enqueue</code> для добавления элементов с приоритетом, метод <code>dequeue</code> для удаления элементов, метод <code>size</code> для возврата количества элементов в очереди, <code>front</code> метод для возврата элемента в передней части очереди и наконец, метод <code>isEmpty</code> , который вернет <code>true</code> если очередь пуста или <code>false</code> если это не так. <code>enqueue</code> должна принимать элементы с форматом, указанным выше ( <code>[&#39;human&#39;, 1]</code> ), где <code>1</code> представляет приоритет. <code>dequeue</code> должен возвращать только текущий элемент, а не его приоритет. </section>
<section id='description'>
В этом вызове вы создадите очередь приоритетов. Приоритетная очередь - это особый тип очереди, в которой элементы могут иметь дополнительную информацию, которая определяет их приоритет. Это может быть просто представлено целым числом. Приоритет элемента переопределяет порядок размещения при определении элементов последовательности. Если элемент с более высоким приоритетом помещается в очередь после элементов с более низким приоритетом, элемент с более высоким приоритетом будет удален до всех остальных. Например, предположим, что у нас есть очередь приоритетов с тремя элементами: <code>[[&#39;kitten&#39;, 2], [&#39;dog&#39;, 2], [&#39;rabbit&#39;, 2]]</code> Здесь второе значение (целое число) представляет приоритет элемента , Если мы ставим в очередь <code>[&#39;human&#39;, 1]</code> с приоритетом <code>1</code> (при условии, что более низкие приоритеты заданы приоритетом), тогда это будет первый элемент, который будет удален. Коллекция понравится: <code>[[&#39;human&#39;, 1], [&#39;kitten&#39;, 2], [&#39;dog&#39;, 2], [&#39;rabbit&#39;, 2]]</code> . Мы начали писать <code>PriorityQueue</code> в редакторе кода. Вам нужно будет добавить метод <code>enqueue</code> для добавления элементов с приоритетом, метод <code>dequeue</code> для удаления элементов, метод <code>size</code> для возврата количества элементов в очереди, <code>front</code> метод для возврата элемента в передней части очереди и наконец, метод <code>isEmpty</code> , который вернет <code>true</code> если очередь пуста или <code>false</code> если это не так. <code>enqueue</code> должна принимать элементы с форматом, указанным выше ( <code>[&#39;human&#39;, 1]</code> ), где <code>1</code> представляет приоритет. <code>dequeue</code> должен возвращать только текущий элемент, а не его приоритет.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Создание класса очереди приоритетов
```yml
tests:
- text: Класс <code>Queue</code> должен иметь метод <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: Класс <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: Класс <code>Queue</code> должен иметь метод <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: Класс <code>Queue</code> должен иметь метод <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: 'Ваш PriorityQueue должен правильно отслеживать текущее количество элементов, используя метод <code>size</code> поскольку элементы находятся в очереди и удалены.'
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: Метод <code>isEmpty</code> должен возвращать <code>true</code> когда очередь пуста.
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: Очередь приоритета должна возвращать элементы с более высоким приоритетом перед элементами с более низким приоритетом и возвращать элементы в порядке «первым в первом порядке» в противном случае.
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.");'
- text: Your <code>Queue</code> class should have a <code>enqueue</code> method.
testString: assert((function(){var test = new PriorityQueue(); return (typeof test.enqueue === 'function')}()));
- text: Your <code>Queue</code> class should have a <code>dequeue</code> method.
testString: assert((function(){var test = new PriorityQueue(); return (typeof test.dequeue === 'function')}()));
- text: Your <code>Queue</code> class should have a <code>size</code> method.
testString: assert((function(){var test = new PriorityQueue(); return (typeof test.size === 'function')}()));
- text: Your <code>Queue</code> class should have an <code>isEmpty</code> method.
testString: assert((function(){var test = new PriorityQueue(); return (typeof test.isEmpty === 'function')}()));
- text: Your PriorityQueue should correctly keep track of the current number of items using the <code>size</code> method as items are enqueued and dequeued.
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)}()));
- text: The <code>isEmpty</code> method should return <code>true</code> when the queue is empty.
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()); }()));
- text: 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.
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';}()));
```
@@ -57,14 +60,47 @@ function PriorityQueue () {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function PriorityQueue () {
this.collection = [];
this.printCollection = function(){
console.log(this.collection);
};
this.size = function() {
return this.collection.length;
};
this.isEmpty = function() {
return this.size() > 0 ? false : true;
};
this.enqueue = function (newitem) {
if (this.isEmpty()) {
return this.collection.push(newitem);
}
this.collection = this.collection.reverse();
var found_index = this.collection.findIndex(function (item) {
return newitem[1] >= item[1];
});
if (found_index === -1) {
this.collection.push(newitem);
} else {
this.collection.splice(found_index, 0, newitem);
}
this.collection = this.collection.reverse();
};
this.dequeue = function() {
if (!this.isEmpty()) {
return this.collection.shift()[0];
} else {
return 'The queue is empty.'
}
};
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8250367417b2b2512c60
title: Create a Queue Class
challengeType: 1
videoUrl: ''
forumTopicId: 301631
localeTitle: Создание класса очереди
---
## Description
<section id="description"> Как и стеки, очереди представляют собой набор элементов. Но, в отличие от стеков, очереди следуют принципу FIFO (First-In First-Out). Элементы, добавленные в очередь, помещаются в хвост или конец очереди, и только элемент в передней части очереди разрешен для удаления. Мы могли бы использовать массив для представления очереди, но точно так же, как стеки, мы хотим ограничить количество контроля над нашими очередями. Двумя основными методами класса очереди являются метод enqueue и dequeue. Метод enqueue подталкивает элемент к хвосту очереди, а метод dequeue удаляет и возвращает элемент в передней части очереди. Другими полезными методами являются методы front, size и isEmpty. Инструкции. Напишите метод enqueue, который подталкивает элемент к хвосту очереди, метод dequeue, который удаляет и возвращает передний элемент, передний метод, который позволяет нам видеть передний элемент, метод размера, который показывает длину, и метод isEmpty чтобы проверить, пуста ли очередь. </section>
<section id='description'>
Как и стеки, очереди представляют собой набор элементов. Но, в отличие от стеков, очереди следуют принципу FIFO (First-In First-Out). Элементы, добавленные в очередь, помещаются в хвост или конец очереди, и только элемент в передней части очереди разрешен для удаления. Мы могли бы использовать массив для представления очереди, но точно так же, как стеки, мы хотим ограничить количество контроля над нашими очередями. Двумя основными методами класса очереди являются метод enqueue и dequeue. Метод enqueue подталкивает элемент к хвосту очереди, а метод dequeue удаляет и возвращает элемент в передней части очереди. Другими полезными методами являются методы front, size и isEmpty. Инструкции. Напишите метод enqueue, который подталкивает элемент к хвосту очереди, метод dequeue, который удаляет и возвращает передний элемент, передний метод, который позволяет нам видеть передний элемент, метод размера, который показывает длину, и метод isEmpty чтобы проверить, пуста ли очередь.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write an <code>enqueue</code> method that pushes an element to the tail of the queue, a <code>dequeue</code> method that removes and returns the front element, a <code>front</code> method that lets us see the front element, a <code>size</code> method that shows the length, and an <code>isEmpty</code> method to check if the queue is empty.
</section>
## Tests
@@ -18,24 +21,24 @@ localeTitle: Создание класса очереди
```yml
tests:
- text: Класс <code>Queue</code> должен иметь метод <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: Класс <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: Класс <code>Queue</code> должен иметь <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: Класс <code>Queue</code> должен иметь метод <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: Класс <code>Queue</code> должен иметь метод <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: Метод <code>dequeue</code> должен удалять и возвращать передний элемент очереди
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: ''
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: Метод <code>size</code> должен возвращать длину очереди
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: Метод <code>isEmpty</code> должен возвращать <code>false</code> если в очереди есть элементы
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");'
- text: Your <code>Queue</code> class should have a <code>enqueue</code> method.
testString: assert((function(){var test = new Queue(); return (typeof test.enqueue === 'function')}()));
- text: Your <code>Queue</code> class should have a <code>dequeue</code> method.
testString: assert((function(){var test = new Queue(); return (typeof test.dequeue === 'function')}()));
- text: Your <code>Queue</code> class should have a <code>front</code> method.
testString: assert((function(){var test = new Queue(); return (typeof test.front === 'function')}()));
- text: Your <code>Queue</code> class should have a <code>size</code> method.
testString: assert((function(){var test = new Queue(); return (typeof test.size === 'function')}()));
- text: Your <code>Queue</code> class should have an <code>isEmpty</code> method.
testString: assert((function(){var test = new Queue(); return (typeof test.isEmpty === 'function')}()));
- text: The <code>dequeue</code> method should remove and return the front element of the queue
testString: assert((function(){var test = new Queue(); test.enqueue('Smith'); test.enqueue('John'); return (test.dequeue() === 'Smith')}()));
- text: The <code>front</code> method should return value of the front element of the queue
testString: assert((function(){var test = new Queue(); test.enqueue('Smith'); test.enqueue('John'); return (test.front() === 'Smith')}()));
- text: The <code>size</code> method should return the length of the queue
testString: assert((function(){var test = new Queue(); test.enqueue('Smith'); return (test.size() === 1)}()));
- text: The <code>isEmpty</code> method should return <code>false</code> if there are elements in the queue
testString: assert((function(){var test = new Queue(); test.enqueue('Smith'); return !(test.isEmpty())}()));
```
@@ -47,28 +50,53 @@ tests:
<div id='js-seed'>
```js
function Queue () {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
function Queue() {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
// Only change code above this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function Queue () {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
this.enqueue = function(item) {
collection.push(item);
}
this.dequeue = function() {
return collection.shift();
}
this.front = function() {
return collection[0];
}
this.size = function(){
return collection.length;
}
this.isEmpty = function() {
return collection.length === 0 ? true : false;
}
// Only change code above this line
}
```
</section>

View File

@@ -2,15 +2,21 @@
id: 8d1323c8c441eddfaeb5bdef
title: Create a Set Class
challengeType: 1
videoUrl: ''
forumTopicId: 301632
localeTitle: Создание набора классов
---
## Description
<section id="description"> В следующих нескольких упражнениях мы собираемся создать функцию для эмуляции структуры данных, называемой «Set». Набор подобен массиву, но он не может содержать повторяющиеся значения. Типичное использование набора - это просто проверить наличие предмета. Это может быть реализовано с помощью объекта, например: <blockquote> var set = new Object (); <br> set.foo = true; <br> // Смотрите, существует ли foo в нашем наборе: <br> console.log (set.foo) // true </blockquote> В следующих нескольких упражнениях мы создадим полнофункциональный набор с нуля. Для этого упражнения создайте функцию, которая добавит значение в нашу коллекцию наборов, если это значение еще не существует в наборе. Например: <blockquote> this.add = function (element) { <br> // некоторый код для добавления значения к набору <br> } </blockquote> Функция должна возвращать значение <code>true</code> если значение успешно добавлено, а <code>false</code> противном случае. </section>
<section id='description'>
В следующих нескольких упражнениях мы собираемся создать функцию для эмуляции структуры данных, называемой «Set». Набор подобен массиву, но он не может содержать повторяющиеся значения. Типичное использование набора - это просто проверить наличие предмета. Это может быть реализовано с помощью объекта, например: <blockquote> var set = new Object (); <br> set.foo = true; <br> // Смотрите, существует ли foo в нашем наборе: <br> console.log (set.foo) // true </blockquote> В следующих нескольких упражнениях мы создадим полнофункциональный набор с нуля. Для этого упражнения создайте функцию, которая добавит значение в нашу коллекцию наборов, если это значение еще не существует в наборе. Например: <blockquote> this.add = function (element) { <br> // некоторый код для добавления значения к набору <br> } </blockquote> Функция должна возвращать значение <code>true</code> если значение успешно добавлено, а <code>false</code> противном случае.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Create an <code>add</code> method that adds a unique value to the set collection and returns <code>true</code> if the value was successfully added and <code>false</code> otherwise.
Create a <code>remove</code> method that accepts a value and checks if it exists in the set. If it does, then this method should remove it from the set collection, and return <code>true</code>. Otherwise, it should return <code>false</code>.
Create a <code>size</code> method that returns the size of the set collection.
</section>
## Tests
@@ -18,14 +24,24 @@ localeTitle: Создание набора классов
```yml
tests:
- text: Класс <code>Set</code> должен иметь метод <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: Ваш метод <code>add</code> не должен добавлять повторяющиеся значения.
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: Ваш метод <code>add</code> должен возвращать <code>true</code> когда значение было успешно добавлено.
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: Метод <code>add</code> должен возвращать значение <code>false</code> при добавлении повторяющегося значения.
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.");'
- text: Your <code>Set</code> class should have an <code>add</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.add === 'function')}()));
- text: Your <code>add</code> method should not add duplicate values.
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)}()));
- text: Your <code>add</code> method should return <code>true</code> when a value has been successfully added.
testString: assert((function(){var test = new Set(); var result = test.add('a'); return (result != undefined) && (result === true);}()));
- text: Your <code>add</code> method should return <code>false</code> when a duplicate value is added.
testString: assert((function(){var test = new Set(); test.add('a'); var result = test.add('a'); return (result != undefined) && (result === false);}()));
- text: Your <code>Set</code> class should have a <code>remove</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.remove === 'function')}()));
- text: Your <code>remove</code> method should only remove items that are present in the set.
testString: assert.deepEqual((function(){var test = new Set(); test.add('a');test.add('b');test.remove('c'); return test.values(); })(), ['a', 'b']);
- text: Your <code>remove</code> method should remove the given item from the set.
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)}()));
- text: Your <code>Set</code> class should have a <code>size</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.size === 'function')}()));
- text: The <code>size</code> method should return the number of elements in the collection.
testString: assert((function(){var test = new Set(); test.add('a');test.add('b');test.remove('a');return (test.size() === 1)}()));
```
@@ -37,18 +53,27 @@ tests:
<div id='js-seed'>
```js
function Set() {
// the var collection will hold our set
var collection = [];
class Set {
constructor() {
// collection will hold our set
this.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);
};
has(element) {
return this.collection.indexOf(element) !== -1;
}
// this method will return all the values in the set
this.values = function() {
return collection;
};
values() {
return this.collection;
}
// change code below this line
// write your add method here
// write your remove method here
// write your size method here
// change code above this line
}
@@ -56,14 +81,42 @@ function Set() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
class Set {
constructor() {
this.collection = [];
}
has(element) {
return this.collection.indexOf(element) !== -1;
}
values() {
return this.collection;
}
add(element) {
if (!this.has(element)) {
this.collection.push(element);
return true;
} else {
return false;
}
}
remove(element) {
if (this.has(element)) {
let i = this.collection.indexOf(element);
this.collection.splice(i, 1);
return true;
}
return false;
}
size() {
return this.collection.length;
}
}
```
</section>

View File

@@ -2,15 +2,19 @@
id: 587d8250367417b2b2512c5f
title: Create a Stack Class
challengeType: 1
videoUrl: ''
forumTopicId: 301633
localeTitle: Создать класс стека
---
## Description
<section id="description"> В последнем разделе мы говорили о том, что такое стек и как мы можем использовать массив для представления стека. В этом разделе мы создадим собственный класс стека. Хотя вы можете использовать массивы для создания стеков, иногда лучше ограничивать количество контроля, которое у нас есть с нашими стопами. Помимо метода <code>push</code> и <code>pop</code> , у стеков есть и другие полезные методы. Давайте добавим <code>peek</code> , <code>isEmpty</code> и <code>clear</code> метод в наш класс стека. Инструкции Напишите метод <code>push</code> который подталкивает элемент к вершине стека, метод <code>pop</code> который удаляет элемент в верхней части стека, метод <code>peek</code> который смотрит на первый элемент в стеке, метод <code>isEmpty</code> который проверяет, стек пуст и <code>clear</code> метод, который удаляет все элементы из стека. Обычно у стеков это не так, но мы добавили метод вспомогательной <code>print</code> котором консоль регистрирует коллекцию. </section>
<section id='description'>
В последнем разделе мы говорили о том, что такое стек и как мы можем использовать массив для представления стека. В этом разделе мы создадим собственный класс стека. Хотя вы можете использовать массивы для создания стеков, иногда лучше ограничивать количество контроля, которое у нас есть с нашими стопами. Помимо метода <code>push</code> и <code>pop</code> , у стеков есть и другие полезные методы. Давайте добавим <code>peek</code> , <code>isEmpty</code> и <code>clear</code> метод в наш класс стека. Инструкции Напишите метод <code>push</code> который подталкивает элемент к вершине стека, метод <code>pop</code> который удаляет элемент в верхней части стека, метод <code>peek</code> который смотрит на первый элемент в стеке, метод <code>isEmpty</code> который проверяет, стек пуст и <code>clear</code> метод, который удаляет все элементы из стека. Обычно у стеков это не так, но мы добавили метод вспомогательной <code>print</code> котором консоль регистрирует коллекцию.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a <code>push</code> method that pushes an element to the top of the stack, a <code>pop</code> method that removes the element on the top of the stack, a <code>peek</code> method that looks at the first element in the stack, an <code>isEmpty</code> method that checks if the stack is empty, and a <code>clear</code> method that removes all elements from the stack.
Normally stacks don't have this, but we've added a <code>print</code> helper method that console logs the collection.
</section>
## Tests
@@ -18,24 +22,24 @@ localeTitle: Создать класс стека
```yml
tests:
- text: Класс <code>Stack</code> должен иметь метод <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: Класс <code>Stack</code> должен иметь метод <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: Класс <code>Stack</code> должен иметь метод <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: Класс <code>Stack</code> должен иметь метод <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: Класс <code>Stack</code> должен иметь <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: Метод <code>peek</code> должен возвращать верхний элемент стека
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: Метод <code>pop</code> должен удалить и вернуть верхний элемент стека
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: 'Метод <code>isEmpty</code> должен возвращать true, если стек не содержит элементов'
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: Метод <code>clear</code> должен удалить весь элемент из стека
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");'
- text: Your <code>Stack</code> class should have a <code>push</code> method.
testString: assert((function(){var test = new Stack(); return (typeof test.push === 'function')}()));
- text: Your <code>Stack</code> class should have a <code>pop</code> method.
testString: assert((function(){var test = new Stack(); return (typeof test.pop === 'function')}()));
- text: Your <code>Stack</code> class should have a <code>peek</code> method.
testString: assert((function(){var test = new Stack(); return (typeof test.peek === 'function')}()));
- text: Your <code>Stack</code> class should have a <code>isEmpty</code> method.
testString: assert((function(){var test = new Stack(); return (typeof test.isEmpty === 'function')}()));
- text: Your <code>Stack</code> class should have a <code>clear</code> method.
testString: assert((function(){var test = new Stack(); return (typeof test.clear === 'function')}()));
- text: The <code>peek</code> method should return the top element of the stack
testString: assert((function(){var test = new Stack(); test.push('CS50'); return (test.peek() === 'CS50')}()));
- text: The <code>pop</code> method should remove and return the top element of the stack
testString: assert((function(){var test = new Stack(); test.push('CS50'); return (test.pop() === 'CS50');}()));
- text: The <code>isEmpty</code> method should return true if a stack does not contain any elements
testString: assert((function(){var test = new Stack(); return test.isEmpty()}()));
- text: The <code>clear</code> method should remove all element from the stack
testString: assert((function(){var test = new Stack(); test.push('CS50'); test.clear(); return (test.isEmpty())}()));
```
@@ -48,27 +52,48 @@ tests:
```js
function Stack() {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
// Only change code above this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
class Stack {
constructor() {
this.collection = [];
}
print() {
console.log(this.collection);
}
push(val) {
this.collection.push(val);
}
pop() {
return this.collection.pop();
}
peek() {
return this.collection[this.collection.length - 1];
}
isEmpty() {
return this.collection.length === 0;
}
clear() {
return (this.collection.length = 0);
}
}
```
</section>

View File

@@ -2,15 +2,19 @@
id: 587d8259367417b2b2512c84
title: Create a Trie Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301634
localeTitle: Создание дерева поиска Trie
---
## Description
<section id="description"> Здесь мы перейдем от двоичных деревьев поиска и рассмотрим другой тип древовидной структуры, называемый trie. Trie - это упорядоченное дерево поиска, обычно используемое для хранения строк или более общих ассоциативных массивов или динамических наборов данных, в которых ключи являются строками. Они очень хороши в хранении наборов данных, когда многие ключи имеют перекрывающиеся префиксы, например, все слова в словаре. В отличие от двоичного дерева, узлы не связаны с фактическими значениями. Вместо этого путь к узлу представляет собой конкретный ключ. Например, если бы мы хотели сохранить строковый код в trie, у нас было бы четыре узла, по одному для каждой буквы: c - o - d - e. После этого пути через все эти узлы затем создадут код как строку - этот путь является ключом, который мы сохранили. Затем, если бы мы хотели добавить строковое кодирование, он разделил бы первые три узла кода, прежде чем разветвиться после d. Таким образом, большие наборы данных могут храниться очень компактно. Кроме того, поиск может быть очень быстрым, поскольку он фактически ограничен длиной строки, которую вы храните. Кроме того, в отличие от двоичных деревьев узел может хранить любое количество дочерних узлов. Как вы могли догадаться из приведенного выше примера, некоторые метаданные обычно хранятся в узлах, которые содержат конец ключа, так что на последующих обходах этот ключ все еще может быть восстановлен. Например, если мы добавили коды в наш пример выше, нам понадобится некоторый способ узнать, что e в коде представляет собой конец ключа, который был ранее введен. В противном случае эта информация будет эффективно потеряна при добавлении кодов. Инструкции: создадим три для хранения слов. Он будет принимать слова через метод добавления и хранить их в структуре данных trie. Это также позволит нам запросить, является ли данная строка словом с методом isWord и извлекает все слова, введенные в trie с помощью метода печати. isWord должен возвращать логическое значение, и print должен возвращать массив всех этих слов в виде строковых значений. Чтобы мы убедились, что эта структура данных реализована правильно, мы предоставили структуру узла для каждого узла в дереве. Каждый узел будет объектом с свойством keys, являющимся объектом JavaScript Map. Это будет содержать отдельные буквы, которые являются действительными ключами каждого узла. Мы также создали свойство конца на узлах, которое может быть установлено в true, если узел представляет собой завершение слова. </section>
<section id='description'>
Здесь мы перейдем от двоичных деревьев поиска и рассмотрим другой тип древовидной структуры, называемый trie. Trie - это упорядоченное дерево поиска, обычно используемое для хранения строк или более общих ассоциативных массивов или динамических наборов данных, в которых ключи являются строками. Они очень хороши в хранении наборов данных, когда многие ключи имеют перекрывающиеся префиксы, например, все слова в словаре. В отличие от двоичного дерева, узлы не связаны с фактическими значениями. Вместо этого путь к узлу представляет собой конкретный ключ. Например, если бы мы хотели сохранить строковый код в trie, у нас было бы четыре узла, по одному для каждой буквы: c - o - d - e. После этого пути через все эти узлы затем создадут код как строку - этот путь является ключом, который мы сохранили. Затем, если бы мы хотели добавить строковое кодирование, он разделил бы первые три узла кода, прежде чем разветвиться после d. Таким образом, большие наборы данных могут храниться очень компактно. Кроме того, поиск может быть очень быстрым, поскольку он фактически ограничен длиной строки, которую вы храните. Кроме того, в отличие от двоичных деревьев узел может хранить любое количество дочерних узлов. Как вы могли догадаться из приведенного выше примера, некоторые метаданные обычно хранятся в узлах, которые содержат конец ключа, так что на последующих обходах этот ключ все еще может быть восстановлен. Например, если мы добавили коды в наш пример выше, нам понадобится некоторый способ узнать, что e в коде представляет собой конец ключа, который был ранее введен. В противном случае эта информация будет эффективно потеряна при добавлении кодов. Инструкции: создадим три для хранения слов. Он будет принимать слова через метод добавления и хранить их в структуре данных trie. Это также позволит нам запросить, является ли данная строка словом с методом isWord и извлекает все слова, введенные в trie с помощью метода печати. isWord должен возвращать логическое значение, и print должен возвращать массив всех этих слов в виде строковых значений. Чтобы мы убедились, что эта структура данных реализована правильно, мы предоставили структуру узла для каждого узла в дереве. Каждый узел будет объектом с свойством keys, являющимся объектом JavaScript Map. Это будет содержать отдельные буквы, которые являются действительными ключами каждого узла. Мы также создали свойство конца на узлах, которое может быть установлено в true, если узел представляет собой завершение слова.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Let's create a trie to store words. It will accept words through an <code>add</code> method and store these in a trie data structure. It will also allow us to query if a given string is a word with an <code>isWord</code> method, and retrieve all the words entered into the trie with a <code>print</code> method. <code>isWord</code> should return a boolean value and print should return an array of all these words as string values.
In order for us to verify that this data structure is implemented correctly, we've provided a <code>Node</code> structure for each node in the tree. Each node will be an object with a <code>keys</code> property which is a JavaScript Map object. This will hold the individual letters that are valid keys of each node. We've also created an <code>end</code> property on the nodes that can be set to <code>true</code> if the node represents the termination of a word.
</section>
## Tests
@@ -18,16 +22,16 @@ localeTitle: Создание дерева поиска Trie
```yml
tests:
- text: У Trie есть метод добавления.
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: Метод Trie имеет метод печати.
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: У Trie есть метод 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: 'Метод print возвращает все элементы, добавленные в trie как строки в массиве.'
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: 'Метод isWord возвращает true только для слов, добавленных в trie и false для всех других слов.'
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.");'
- text: The Trie has an add method.
testString: assert((function testTrie() { var test = false; if (typeof Trie !== 'undefined') { test = new Trie() } else { return false; }; return (typeof test.add == 'function') }()));
- text: The Trie has a print method.
testString: assert((function testTrie() { var test = false; if (typeof Trie !== 'undefined') { test = new Trie() } else { return false; }; return (typeof test.print == 'function') }()));
- text: The Trie has an isWord method.
testString: assert((function testTrie() { var test = false; if (typeof Trie !== 'undefined') { test = new Trie() } else { return false; }; return (typeof test.isWord == 'function') }()));
- text: The print method returns all items added to the trie as strings in an 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); }()));
- text: The isWord method returns true only for words added to the trie and false for all other words.
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')); }()));
```
@@ -39,7 +43,7 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
var Node = function() {
this.keys = new Map();
this.end = false;
@@ -59,8 +63,6 @@ var Trie = function() {
</div>
</section>
## Solution
@@ -69,4 +71,5 @@ var Trie = function() {
```js
// solution required
```
</section>

View File

@@ -2,25 +2,36 @@
id: 587d825b367417b2b2512c8d
title: Create an ES6 JavaScript Map
challengeType: 1
videoUrl: ''
forumTopicId: 301635
localeTitle: Создание карты JavaScript ES6
---
## Description
undefined
<section id='description'>
The new version of JavaScript provides us with a built-in Map object which provides much of the functionality we wrote by hand in the last challenge. This Map object, although similar to regular JavaScript objects, provides some useful functionality that normal objects lack. For example, an ES6 Map tracks the insertion order of items that are added to it. Here is a more complete overview of its methods:
<code>.has(key)</code> returns true or false based on the presence of a key
<code>.get(key)</code> returns the value associated with a key
<code>.set(key, value)</code> sets a new key, value pair
<code>.delete(key)</code> removes a key, value pair
<code>.clear()</code> removes all key, value pairs
<code>.entries()</code> returns an array of all the keys in insertion order
<code>.values()</code> returns an array of all the values in insertion order
</section>
## Instructions
undefined
<section id='instructions'>
Define a JavaScript Map object and assign to it a variable called myMap. Add the key, value pair <code>freeCodeCamp</code>, <code>Awesome!</code> to it.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert(typeof myMap === "object", "The myMap object exists.");'
- text: 'myMap содержит пару ключевых значений <code>freeCodeCamp</code> , <code>Awesome!</code> ,'
testString: 'assert(myMap.get("freeCodeCamp") === "Awesome!", "myMap contains the key value pair <code>freeCodeCamp</code>, <code>Awesome!</code>.");'
- text: The myMap object exists.
testString: assert(typeof myMap === 'object');
- text: myMap contains the key value pair <code>freeCodeCamp</code>, <code>Awesome!</code>.
testString: assert(myMap.get('freeCodeCamp') === 'Awesome!');
```
@@ -38,8 +49,6 @@ tests:
</div>
</section>
## Solution
@@ -48,4 +57,5 @@ tests:
```js
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d8254367417b2b2512c70
title: Create and Add to Sets in ES6
challengeType: 1
videoUrl: ''
forumTopicId: 301636
localeTitle: Создание и добавление к наборам в ES6
---
## Description
<section id="description"> Теперь, когда вы работали с ES5, вы собираетесь выполнить что-то подобное в ES6. Это будет значительно проще. ES6 содержит встроенную структуру данных. <code>Set</code> операций, которые вы написали вручную, теперь включены для вас. Давайте посмотрим: Чтобы создать новый пустой набор: <code>var set = new Set();</code> Вы можете создать набор со значением: <code>var set = new Set(1);</code> Вы можете создать набор с массивом: <code>var set = new Set([1, 2, 3]);</code> Когда вы создали набор, вы можете добавить нужные значения с помощью метода <code>add</code> : <blockquote> var set = new Set ([1, 2, 3]); <br> set.add ([4, 5, 6]); </blockquote> Напомним, что набор представляет собой структуру данных, которая не может содержать повторяющиеся значения: <blockquote> var set = new Set ([1, 2, 3, 1, 2, 3]); <br> // set содержит только [1, 2, 3] </blockquote></section>
<section id='description'>
Теперь, когда вы работали с ES5, вы собираетесь выполнить что-то подобное в ES6. Это будет значительно проще. ES6 содержит встроенную структуру данных. <code>Set</code> операций, которые вы написали вручную, теперь включены для вас. Давайте посмотрим: Чтобы создать новый пустой набор: <code>var set = new Set();</code> Вы можете создать набор со значением: <code>var set = new Set(1);</code> Вы можете создать набор с массивом: <code>var set = new Set([1, 2, 3]);</code> Когда вы создали набор, вы можете добавить нужные значения с помощью метода <code>add</code> : <blockquote> var set = new Set ([1, 2, 3]); <br> set.add ([4, 5, 6]); </blockquote> Напомним, что набор представляет собой структуру данных, которая не может содержать повторяющиеся значения: <blockquote> var set = new Set ([1, 2, 3, 1, 2, 3]); <br> // set содержит только [1, 2, 3] </blockquote>
</section>
## Instructions
<section id="instructions"> Для этого упражнения верните набор со следующими значениями: <code>1, 2, 3, &#39;Taco&#39;, &#39;Cat&#39;, &#39;Awesome&#39;</code> </section>
<section id='instructions'>
Для этого упражнения верните набор со следующими значениями: <code>1, 2, 3, &#39;Taco&#39;, &#39;Cat&#39;, &#39;Awesome&#39;</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Ваш <code>Set</code> должен содержать только значения <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>.");'
- text: Your <code>Set</code> should only contain the values <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");})());
```
@@ -35,7 +39,7 @@ function checkSet() {
// change code below this line
// change code above this line
console.log(set);
console.log(Array.from(set));
return set;
}
@@ -45,14 +49,14 @@ checkSet();
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function checkSet(){var set = new Set([1,2,3,'Taco','Cat','Awesome']);
return set;}
```
</section>

View File

@@ -2,31 +2,36 @@
id: 587d8258367417b2b2512c80
title: Delete a Leaf Node in a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301637
localeTitle: Удалить узел листа в двоичном дереве поиска
---
## Description
<section id="description"> Это первая из трех задач, когда мы будем выполнять более сложную операцию в двоичных деревьях поиска: удаление. Удаление затруднено, поскольку удаление узлов ломает ссылки в дереве. Эти ссылки должны быть тщательно восстановлены для обеспечения сохранения структуры двоичного дерева. Для некоторых исключений это означает, что дерево должно быть перестроено. В общем случае вы столкнетесь с одним из трех случаев, когда пытаетесь удалить узел: Leaf Node: цель для удаления имеет ноль детей. Один ребенок: у цели для удаления только один ребенок. Двое детей: цель для удаления имеет два дочерних узла. Удаление листового узла легко, мы просто удалим его. Удаление узла одним ребенком также относительно просто, мы просто удалим его и связаем его родительский с дочерним узлом удаляемого узла. Однако удалить узел с двумя детьми сложнее, поскольку это создает два дочерних узла, которые необходимо переподключить к родительскому дереву. Мы посмотрим, как справиться с этим делом в третьем вызове. Кроме того, вы должны помнить о некоторых случаях при обработке удаления. Что делать, если дерево пустое? Что делать, если удаляемый узел является корневым узлом? Что делать, если в дереве есть только два элемента? Теперь давайте рассмотрим первый случай, когда мы удаляем листовой узел. Инструкции: Создайте метод на нашем двоичном дереве, который называется <code>remove</code> . Здесь мы построим логику для операции удаления. Во-первых, вам нужно создать функцию в удалении, которая находит узел, который мы пытаемся удалить в текущем дереве. Если узел отсутствует в дереве, <code>remove</code> должен вернуть значение <code>null</code> . Теперь, если целевой узел является листовым узлом без детей, то родительская ссылка на него должна быть установлена ​​в <code>null</code> . Это эффективно удаляет узел из дерева. Для этого вам нужно будет отслеживать родительский узел узла, который мы также пытаемся удалить. Также будет полезно создать способ отслеживания числа дочерних узлов целевого узла, так как это определит, к какому случаю относится наше удаление. Мы рассмотрим второй и третий случаи в следующих задачах. Удачи! </section>
<section id='description'>
Это первая из трех задач, когда мы будем выполнять более сложную операцию в двоичных деревьях поиска: удаление. Удаление затруднено, поскольку удаление узлов ломает ссылки в дереве. Эти ссылки должны быть тщательно восстановлены для обеспечения сохранения структуры двоичного дерева. Для некоторых исключений это означает, что дерево должно быть перестроено. В общем случае вы столкнетесь с одним из трех случаев, когда пытаетесь удалить узел: Leaf Node: цель для удаления имеет ноль детей. Один ребенок: у цели для удаления только один ребенок. Двое детей: цель для удаления имеет два дочерних узла. Удаление листового узла легко, мы просто удалим его. Удаление узла одним ребенком также относительно просто, мы просто удалим его и связаем его родительский с дочерним узлом удаляемого узла. Однако удалить узел с двумя детьми сложнее, поскольку это создает два дочерних узла, которые необходимо переподключить к родительскому дереву. Мы посмотрим, как справиться с этим делом в третьем вызове. Кроме того, вы должны помнить о некоторых случаях при обработке удаления. Что делать, если дерево пустое? Что делать, если удаляемый узел является корневым узлом? Что делать, если в дереве есть только два элемента? Теперь давайте рассмотрим первый случай, когда мы удаляем листовой узел. Инструкции: Создайте метод на нашем двоичном дереве, который называется <code>remove</code> . Здесь мы построим логику для операции удаления. Во-первых, вам нужно создать функцию в удалении, которая находит узел, который мы пытаемся удалить в текущем дереве. Если узел отсутствует в дереве, <code>remove</code> должен вернуть значение <code>null</code> . Теперь, если целевой узел является листовым узлом без детей, то родительская ссылка на него должна быть установлена ​​в <code>null</code> . Это эффективно удаляет узел из дерева. Для этого вам нужно будет отслеживать родительский узел узла, который мы также пытаемся удалить. Также будет полезно создать способ отслеживания числа дочерних узлов целевого узла, так как это определит, к какому случаю относится наше удаление. Мы рассмотрим второй и третий случаи в следующих задачах. Удачи!
</section>
## Instructions
undefined
<section id='instructions'>
Create a method on our binary tree called <code>remove</code>. We'll build the logic for our deletion operation in here. First, you'll want to create a function within remove that finds the node we are trying to delete in the current tree. If the node is not present in the tree, <code>remove</code> should return <code>null</code>. Now, if the target node is a leaf node with no children, then the parent reference to it should be set to <code>null</code>. This effectively deletes the node from the tree. To do this, you will have to keep track of the parent of the node we are trying to delete as well. It will also be useful to create a way to track the number of children the target node has, as this will determine which case our deletion falls under.
We will handle the second and third cases in the next challenges. Good luck!
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
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: 'Двоичное дерево поиска имеет метод, называемый <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: 'Попытка удалить элемент, который не существует, возвращает <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: 'Если корневой узел не имеет дочерних элементов, его удаление устанавливает корень в <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: Метод <code>remove</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(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: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>remove</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == 'function')})());
- text: Trying to remove an element that does not exist returns <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); })());
- text: If the root node has no children, deleting it sets the root to <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); })());
- text: The <code>remove</code> method removes leaf nodes from the tree
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'); })());
```
@@ -38,28 +43,102 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
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
this.root = null;
// case 1: target has no children, change code below this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
},
inorder: function() {
if (this.root == null) {
return null;
} else {
var result = new Array();
function traverseInOrder(node) {
if (node.left != null) {
traverseInOrder(node.left);
}
result.push(node.value);
if (node.right != null) {
traverseInOrder(node.right);
}
}
traverseInOrder(this.root);
return result;
}
},
isBinarySearchTree() {
if (this.root == null) {
return null;
} else {
var check = true;
function checkTree(node) {
if (node.left != null) {
var left = node.left;
if (left.value > node.value) {
check = false;
} else {
checkTree(left);
}
}
if (node.right != null) {
var right = node.right;
if (right.value < node.value) {
check = false;
} else {
checkTree(right);
}
}
}
checkTree(this.root);
return check;
}
}
};
```
</div>
@@ -72,4 +151,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8258367417b2b2512c81
title: Delete a Node with One Child in a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301638
localeTitle: Удаление узла с одним ребенком в двоичном дереве поиска
---
## Description
undefined
<section id='description'>
Now that we can delete leaf nodes let's move on to the second case: deleting a node with one child. For this case, say we have a tree with the following nodes 1 — 2 — 3 where 1 is the root. To delete 2, we simply need to make the right reference in 1 point to 3. More generally to delete a node with only one child, we make that node's parent reference the next node in the tree.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
We've provided some code in our <code>remove</code> method that accomplishes the tasks from the last challenge. We find the target to delete and its parent and define the number of children the target node has. Let's add the next case here for target nodes with only one child. Here, we'll have to determine if the single child is a left or right branch in the tree and then set the correct reference in the parent to point to this node. In addition, let's account for the case where the target is the root node (this means the parent node will be <code>null</code>). Feel free to replace all the starter code with your own as long as it passes the tests.
</section>
## Tests
@@ -18,20 +21,20 @@ undefined
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: 'Двоичное дерево поиска имеет метод, называемый <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: ''
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: ''
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: ''
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: ''
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: ''
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: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>remove</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == 'function')})());
- text: Trying to remove an element that does not exist returns <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); })());
- text: If the root node has no children, deleting it sets the root to <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); })());
- text: The <code>remove</code> method removes leaf nodes from the tree
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'); })());
- text: The <code>remove</code> method removes nodes with one child.
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'); })());
- text: Removing the root in a tree with two nodes sets the second to be the root.
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'); })());
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
@@ -73,18 +76,18 @@ function BinarySearchTree() {
} else {
return null;
}
}).bind(this)();
}.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);
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 {
} else {
if (parent.left == target) {
parent.left = null;
} else {
@@ -100,12 +103,86 @@ function BinarySearchTree() {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
},
inorder: function() {
if (this.root == null) {
return null;
} else {
var result = new Array();
function traverseInOrder(node) {
if (node.left != null) {
traverseInOrder(node.left);
}
result.push(node.value);
if (node.right != null) {
traverseInOrder(node.right);
}
}
traverseInOrder(this.root);
return result;
}
},
isBinarySearchTree() {
if (this.root == null) {
return null;
} else {
var check = true;
function checkTree(node) {
if (node.left != null) {
var left = node.left;
if (left.value > node.value) {
check = false;
} else {
checkTree(left);
}
}
if (node.right != null) {
var right = node.right;
if (right.value < node.value) {
check = false;
} else {
checkTree(right);
}
}
}
checkTree(this.root);
return check;
}
}
};
```
</div>
@@ -118,4 +195,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8258367417b2b2512c82
title: Delete a Node with Two Children in a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301639
localeTitle: Удаление узла с двумя детьми в двоичном дереве поиска
---
## Description
<section id="description"> Удаление узлов, имеющих двух детей, является самым сложным для реализации. Удаление такого узла приводит к двум поддеревьям, которые больше не связаны с исходной древовидной структурой. Как мы можем их восстановить? Один из методов заключается в том, чтобы найти наименьшее значение в правом поддереве целевого узла и заменить целевой узел на это значение. Выбор замены таким образом гарантирует, что он больше, чем каждый узел в левом поддереве, он становится новым родителем, но также меньше, чем каждый узел в правом поддереве, он становится новым родителем. После этой замены узел замены должен быть удален из правого поддерева. Даже эта операция сложна, потому что замена может быть листом, или она сама может быть родителем правильного поддерева. Если это лист, мы должны удалить ссылку на родителя. В противном случае это должен быть правильный ребенок цели. В этом случае мы должны заменить целевое значение значением замены и сделать целевую ссылку правильным ребенком замены. Инструкции: Закончим наш метод <code>remove</code> , обработав третий случай. Мы снова предоставили код для первых двух случаев. Добавьте код для обработки целевых узлов двумя детьми. Любые случаи краев, о которых нужно знать? Что, если дерево имеет только три узла? По завершении этого будет завершена операция удаления двоичных деревьев поиска. Хорошая работа, это довольно сложная проблема! </section>
<section id='description'>
Удаление узлов, имеющих двух детей, является самым сложным для реализации. Удаление такого узла приводит к двум поддеревьям, которые больше не связаны с исходной древовидной структурой. Как мы можем их восстановить? Один из методов заключается в том, чтобы найти наименьшее значение в правом поддереве целевого узла и заменить целевой узел на это значение. Выбор замены таким образом гарантирует, что он больше, чем каждый узел в левом поддереве, он становится новым родителем, но также меньше, чем каждый узел в правом поддереве, он становится новым родителем. После этой замены узел замены должен быть удален из правого поддерева. Даже эта операция сложна, потому что замена может быть листом, или она сама может быть родителем правильного поддерева. Если это лист, мы должны удалить ссылку на родителя. В противном случае это должен быть правильный ребенок цели. В этом случае мы должны заменить целевое значение значением замены и сделать целевую ссылку правильным ребенком замены. Инструкции: Закончим наш метод <code>remove</code> , обработав третий случай. Мы снова предоставили код для первых двух случаев. Добавьте код для обработки целевых узлов двумя детьми. Любые случаи краев, о которых нужно знать? Что, если дерево имеет только три узла? По завершении этого будет завершена операция удаления двоичных деревьев поиска. Хорошая работа, это довольно сложная проблема!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Let's finish our <code>remove</code> method by handling the third case. We've provided some code again for the first two cases. Add some code now to handle target nodes with two children. Any edge cases to be aware of? What if the tree has only three nodes? Once you are finished this will complete our deletion operation for binary search trees. Nice job, this is a pretty hard problem!
</section>
## Tests
@@ -18,24 +21,24 @@ localeTitle: Удаление узла с двумя детьми в двоич
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: 'Двоичное дерево поиска имеет метод, называемый <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: 'Попытка удалить элемент, который не существует, возвращает <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: 'Если корневой узел не имеет дочерних элементов, его удаление устанавливает корень в <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: Метод <code>remove</code> удаляет листовые узлы из дерева
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: Метод <code>remove</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(-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: Удаление корня в дереве с двумя узлами устанавливает второй корень.
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: Метод <code>remove</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(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: Корень можно удалить на дереве из трех узлов.
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.");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>remove</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == 'function')})());
- text: Trying to remove an element that does not exist returns <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})());'
- text: If the root node has no children, deleting it sets the root to <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})());'
- text: The <code>remove</code> method removes leaf nodes from the tree
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})());'
- text: The <code>remove</code> method removes nodes with one child.
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'); })());
- text: Removing the root in a tree with two nodes sets the second to be the root.
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'); })());
- text: The <code>remove</code> method removes nodes with two children while maintaining the binary search tree structure.
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'); })());
- text: The root can be removed on a tree of three nodes.
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); })());
```
@@ -47,7 +50,7 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
@@ -77,18 +80,18 @@ function BinarySearchTree() {
} else {
return null;
}
}).bind(this)();
}.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);
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 {
} else {
if (parent.left == target) {
parent.left = null;
} else {
@@ -98,7 +101,7 @@ function BinarySearchTree() {
}
// case 2: target has one child
else if (children == 1) {
var newChild = (target.left !== null) ? target.left : target.right;
var newChild = target.left !== null ? target.left : target.right;
if (parent === null) {
target.value = newChild.value;
target.left = null;
@@ -118,12 +121,86 @@ function BinarySearchTree() {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
},
inorder: function() {
if (this.root == null) {
return null;
} else {
var result = new Array();
function traverseInOrder(node) {
if (node.left != null) {
traverseInOrder(node.left);
}
result.push(node.value);
if (node.right != null) {
traverseInOrder(node.right);
}
}
traverseInOrder(this.root);
return result;
}
},
isBinarySearchTree() {
if (this.root == null) {
return null;
} else {
var check = true;
function checkTree(node) {
if (node.left != null) {
var left = node.left;
if (left.value > node.value) {
check = false;
} else {
checkTree(left);
}
}
if (node.right != null) {
var right = node.right;
if (right.value < node.value) {
check = false;
} else {
checkTree(right);
}
}
}
checkTree(this.root);
return check;
}
}
};
```
</div>
@@ -136,4 +213,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,37 +2,41 @@
id: 587d825d367417b2b2512c96
title: Depth-First Search
challengeType: 1
videoUrl: ''
forumTopicId: 301640
localeTitle: Поиск по глубине
---
## Description
<section id="description"> Подобно <dfn>поиску в ширину</dfn> , здесь мы узнаем о другом алгоритме обхода графа, называемом методом поиска в <dfn>глубину</dfn> . В то время как поиск по ширине ищет инкрементные длины кромок от исходного узла, <dfn>поиск по глубине сначала</dfn> идет по пути ребер, насколько это возможно. Как только он достигнет одного конца пути, поиск вернется к последнему узлу с не посещенным краем пути и продолжит поиск. Ниже приведена визуализация того, что делает алгоритм, когда верхний узел является отправной точкой поиска. <img class="img-responsive" src="https://camo.githubusercontent.com/aaad9e39961daf34d967c616edeb50abf3bf1235/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37662f44657074682d46697273742d5365617263682e676966"> Простым выходом этого алгоритма является список узлов, которые достижимы с данного узла. Поэтому при реализации этого алгоритма вам нужно будет отслеживать узлы, которые вы посещаете. </section>
<section id='description'>
Подобно <dfn>поиску в ширину</dfn> , здесь мы узнаем о другом алгоритме обхода графа, называемом методом поиска в <dfn>глубину</dfn> . В то время как поиск по ширине ищет инкрементные длины кромок от исходного узла, <dfn>поиск по глубине сначала</dfn> идет по пути ребер, насколько это возможно. Как только он достигнет одного конца пути, поиск вернется к последнему узлу с не посещенным краем пути и продолжит поиск. Ниже приведена визуализация того, что делает алгоритм, когда верхний узел является отправной точкой поиска. <img class="img-responsive" src="https://camo.githubusercontent.com/aaad9e39961daf34d967c616edeb50abf3bf1235/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37662f44657074682d46697273742d5365617263682e676966"> Простым выходом этого алгоритма является список узлов, которые достижимы с данного узла. Поэтому при реализации этого алгоритма вам нужно будет отслеживать узлы, которые вы посещаете.
</section>
## Instructions
<section id="instructions"> Напишите функцию <code>dfs()</code> которая принимает неориентированный <code>graph</code> матрицы смежности и <code>root</code> метки узла в качестве параметров. Метка узла будет просто числовым значением узла между <code>0</code> и <code>n - 1</code> , где <code>n</code> - общее количество узлов на графике. Ваша функция должна выводить массив всех узлов, доступных из <code>root</code> . </section>
<section id='instructions'>
Напишите функцию <code>dfs()</code> которая принимает неориентированный <code>graph</code> матрицы смежности и <code>root</code> метки узла в качестве параметров. Метка узла будет просто числовым значением узла между <code>0</code> и <code>n - 1</code> , где <code>n</code> - общее количество узлов на графике. Ваша функция должна выводить массив всех узлов, доступных из <code>root</code> .
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Входной график <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>1</code> должен возвращать массив с <code>0</code> , <code>1</code> , <code>2</code> и <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: 'Входной график <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>1</code> должен возвращать массив с четырьмя элементами.'
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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> с начальным узлом <code>3</code> должен возвращать массив с <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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> с начальным узлом <code>3</code> должен возвращать массив с одним элементом.'
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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>3</code> должен возвращать массив с <code>2</code> и <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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>3</code> должен возвращать массив с двумя элементами.'
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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>0</code> должен возвращать массив с <code>0</code> и <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: 'Входной граф <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> с начальным узлом <code>0</code> должен возвращать массив с двумя элементами.'
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.");'
- text: 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>.
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]);
- text: 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.
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);
- text: 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>.
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]);
- text: 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.
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);
- text: 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>.
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]);
- text: 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.
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);
- text: 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>.
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]);
- text: 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.
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);
```
@@ -60,14 +64,32 @@ console.log(dfs(exDFSGraph, 3));
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function dfs(graph, root) {
var stack = [];
var tempV;
var visited = [];
var tempVNeighbors = [];
stack.push(root);
while (stack.length > 0) {
tempV = stack.pop();
if (visited.indexOf(tempV) == -1) {
visited.push(tempV);
tempVNeighbors = graph[tempV];
for (var i = 0; i < tempVNeighbors.length; i++) {
if (tempVNeighbors[i] == 1) {
stack.push(i);
}
}
}
}
return visited;
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8257367417b2b2512c7d
title: Find the Minimum and Maximum Height of a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301641
localeTitle: Найдите минимальную и максимальную высоту двоичного дерева поиска
---
## Description
<section id="description"> В последнем вызове мы описали сценарий, в котором дерево может стать неуравновешенным. Чтобы понять концепцию баланса, давайте посмотрим на другое свойство дерева: height. Высота в дереве представляет собой расстояние от корневого узла до любого заданного листового узла. Различные пути в сильно разветвленной структуре дерева могут иметь разную высоту, но для данного дерева будет минимальная и максимальная высота. Если дерево сбалансировано, эти значения будут отличаться не более чем на один. Это означает, что в сбалансированном дереве все листовые узлы существуют на одном уровне, или если они не находятся на одном уровне, они не более одного уровня друг от друга. Свойство баланса важно для деревьев, потому что именно это определяет эффективность древовидных операций. Как мы объяснили в последнем задаче, мы сталкиваемся с худшей временной сложностью для сильно неуравновешенных деревьев. Самобалансирующиеся деревья обычно используются для учета этой проблемы в деревьях с динамическими наборами данных. К общим примерам относятся деревья AVL, красно-черные деревья и B-деревья. Эти деревья содержат дополнительную внутреннюю логику, которая перебалансирует дерево, когда вставки или удаления создают состояние дисбаланса. Примечание. Аналогичным свойством высоты является глубина, которая относится к тому, насколько далеко данный узел находится от корневого узла. Инструкции: Напишите два метода для нашего двоичного дерева: <code>findMinHeight</code> и <code>findMaxHeight</code> . Эти методы должны возвращать целочисленное значение для минимальной и максимальной высоты в заданном двоичном дереве, соответственно. Если узел пуст, назначим ему высоту <code>-1</code> (это базовый случай). Наконец, добавьте третий метод <code>isBalanced</code> который возвращает <code>true</code> или <code>false</code> зависимости от того, сбалансировано ли дерево или нет. Вы можете использовать первые два метода, которые вы только что написали, чтобы определить это. </section>
<section id='description'>
В последнем вызове мы описали сценарий, в котором дерево может стать неуравновешенным. Чтобы понять концепцию баланса, давайте посмотрим на другое свойство дерева: height. Высота в дереве представляет собой расстояние от корневого узла до любого заданного листового узла. Различные пути в сильно разветвленной структуре дерева могут иметь разную высоту, но для данного дерева будет минимальная и максимальная высота. Если дерево сбалансировано, эти значения будут отличаться не более чем на один. Это означает, что в сбалансированном дереве все листовые узлы существуют на одном уровне, или если они не находятся на одном уровне, они не более одного уровня друг от друга. Свойство баланса важно для деревьев, потому что именно это определяет эффективность древовидных операций. Как мы объяснили в последнем задаче, мы сталкиваемся с худшей временной сложностью для сильно неуравновешенных деревьев. Самобалансирующиеся деревья обычно используются для учета этой проблемы в деревьях с динамическими наборами данных. К общим примерам относятся деревья AVL, красно-черные деревья и B-деревья. Эти деревья содержат дополнительную внутреннюю логику, которая перебалансирует дерево, когда вставки или удаления создают состояние дисбаланса. Примечание. Аналогичным свойством высоты является глубина, которая относится к тому, насколько далеко данный узел находится от корневого узла. Инструкции: Напишите два метода для нашего двоичного дерева: <code>findMinHeight</code> и <code>findMaxHeight</code> . Эти методы должны возвращать целочисленное значение для минимальной и максимальной высоты в заданном двоичном дереве, соответственно. Если узел пуст, назначим ему высоту <code>-1</code> (это базовый случай). Наконец, добавьте третий метод <code>isBalanced</code> который возвращает <code>true</code> или <code>false</code> зависимости от того, сбалансировано ли дерево или нет. Вы можете использовать первые два метода, которые вы только что написали, чтобы определить это.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write two methods for our binary tree: <code>findMinHeight</code> and <code>findMaxHeight</code>. These methods should return an integer value for the minimum and maximum height within a given binary tree, respectively. If the node is empty let's assign it a height of <code>-1</code> (that's the base case). Finally, add a third method <code>isBalanced</code> which returns <code>true</code> or <code>false</code> depending on whether the tree is balanced or not. You can use the first two methods you just wrote to determine this.
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: Найдите минимальную и максимальную
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: Двоичное дерево поиска имеет метод под названием <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: Дерево двоичного поиска имеет метод под названием <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: 'Двоичное дерево поиска имеет метод, называемый <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: Метод <code>findMinHeight</code> возвращает минимальную высоту дерева.
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: Метод <code>findMaxHeight</code> возвращает максимальную высоту дерева.
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: Пустое дерево возвращает высоту <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: 'Метод <code>isBalanced</code> возвращает true, если дерево является сбалансированным двоичным деревом поиска.'
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.");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>findMinHeight</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMinHeight == 'function')})());
- text: The binary search tree has a method called <code>findMaxHeight</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMaxHeight == 'function')})());
- text: The binary search tree has a method called <code>isBalanced</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.isBalanced == 'function')})());
- text: The <code>findMinHeight</code> method returns the minimum height of the tree.
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); })());
- text: The <code>findMaxHeight</code> method returns the maximum height of the tree.
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); })());
- text: An empty tree returns a height of <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); })());
- text: The <code>isBalanced</code> method returns true if the tree is a balanced binary search tree.
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(); })());
```
@@ -45,28 +48,57 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
}
};
```
</div>
@@ -77,6 +109,79 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
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
this.findMinHeight = function(root = this.root) {
// empty tree.
if (root === null) {
return -1;
}
// leaf node.
if (root.left === null && root.right === null) {
return 0;
}
if (root.left === null) {
return this.findMinHeight(root.right) + 1;
}
if (root.right === null) {
return this.findMinHeight(root.left) + 1;
}
const lHeight = this.findMinHeight(root.left);
const rHeight = this.findMinHeight(root.right);
return Math.min(lHeight, rHeight) + 1;
};
this.findMaxHeight = function(root = this.root) {
// empty tree.
if (root === null) {
return -1;
}
// leaf node.
if (root.left === null && root.right === null) {
return 0;
}
if (root.left === null) {
return this.findMaxHeight(root.right) + 1;
}
if (root.right === null) {
return this.findMaxHeight(root.left) + 1;
}
const lHeight = this.findMaxHeight(root.left);
const rHeight = this.findMaxHeight(root.right);
return Math.max(lHeight, rHeight) + 1;
};
this.isBalanced = function(root = this.root) {
if (root === null) {
return true;
}
if (root.left === null && root.right === null) {
return true;
}
if (root.left === null) {
return this.findMaxHeight(root.right) <= 0;
}
if (root.right === null) {
return this.findMaxHeight(root.left) <= 0;
}
const lHeight = this.findMaxHeight(root.left);
const rHeight = this.findMaxHeight(root.right);
if (Math.abs(lHeight - rHeight) > 1) {
return false;
}
return this.isBalanced(root.left) && this.isBalanced(root.right);
};
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d825b367417b2b2512c8c
title: Implement Heap Sort with a Min Heap
challengeType: 1
videoUrl: ''
forumTopicId: 301643
localeTitle: Выполнение сортировки кучи с помощью Min Heap
---
## Description
<section id="description"> Теперь, когда мы можем добавлять и удалять элементы, давайте посмотрим, как можно использовать некоторые кучи приложений. Кучи обычно используются для реализации очередей приоритетов, поскольку они всегда хранят элемент наибольшего или наименьшего значения в первой позиции. Кроме того, они используются для реализации алгоритма сортировки, называемого сортировкой кучи. Посмотрим, как это сделать. Сортировка кучи использует минимальную кучу, обратную к максимальной куче. Минимальная куча всегда сохраняет элемент наименьшего значения в корневой позиции. Heap sort работает, беря несортированный массив, добавляя каждый элемент в массив в кучу минут, а затем извлекает каждый элемент из кучи min в новый массив. Структура минимальной кучи гарантирует, что новый массив будет содержать исходные элементы по крайней мере до наибольшего порядка. Это один из наиболее эффективных алгоритмов сортировки со средней и наихудшей производительностью O (nlog (n)). Инструкции: Давайте реализуем кучу сортировки с минимальной кучей. Не стесняйтесь адаптировать свой максимальный код кучи. Создайте объект MinHeap с помощью методов вставки, удаления и сортировки. Метод sort должен возвращать массив из всех элементов в куче минимальной сортировки от минимального до самого большого. </section>
<section id='description'>
Теперь, когда мы можем добавлять и удалять элементы, давайте посмотрим, как можно использовать некоторые кучи приложений. Кучи обычно используются для реализации очередей приоритетов, поскольку они всегда хранят элемент наибольшего или наименьшего значения в первой позиции. Кроме того, они используются для реализации алгоритма сортировки, называемого сортировкой кучи. Посмотрим, как это сделать. Сортировка кучи использует минимальную кучу, обратную к максимальной куче. Минимальная куча всегда сохраняет элемент наименьшего значения в корневой позиции. Heap sort работает, беря несортированный массив, добавляя каждый элемент в массив в кучу минут, а затем извлекает каждый элемент из кучи min в новый массив. Структура минимальной кучи гарантирует, что новый массив будет содержать исходные элементы по крайней мере до наибольшего порядка. Это один из наиболее эффективных алгоритмов сортировки со средней и наихудшей производительностью O (nlog (n)). Инструкции: Давайте реализуем кучу сортировки с минимальной кучей. Не стесняйтесь адаптировать свой максимальный код кучи. Создайте объект MinHeap с помощью методов вставки, удаления и сортировки. Метод sort должен возвращать массив из всех элементов в куче минимальной сортировки от минимального до самого большого.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Let's implement heap sort with a min heap. Feel free to adapt your max heap code here. Create an object <code>MinHeap</code> with <code>insert</code>, <code>remove</code>, and <code>sort</code> methods. The <code>sort</code> method should return an array of all the elements in the min heap sorted from smallest to largest.
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Выполнение сортировки кучи с помощь
```yml
tests:
- text: Структура данных MinHeap существует.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== "undefined") { test = new MinHeap() }; return (typeof test == "object")})(), "The MinHeap data structure exists.");'
- text: 'У MinHeap есть метод, называемый 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 есть метод, называемый remove.'
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 есть метод под названием 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: 'Метод sort возвращает массив, содержащий все элементы, добавленные в кучу минут в отсортированном порядке.'
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.");'
- text: The MinHeap data structure exists.
testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() }; return (typeof test == 'object')})());
- text: MinHeap has a method called insert.
testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() } else { return false; }; return (typeof test.insert == 'function')})());
- text: MinHeap has a method called remove.
testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() } else { return false; }; return (typeof test.remove == 'function')})());
- text: MinHeap has a method called sort.
testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() } else { return false; }; return (typeof test.sort == 'function')})());
- text: The sort method returns an array containing all items added to the min heap in sorted order.
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)); })());
```
@@ -41,14 +44,15 @@ tests:
```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);
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;
return size > 1 ? createArray(size - 1) : undefined;
})(25);
var MinHeap = function() {
// change code below this line
@@ -59,8 +63,6 @@ var MinHeap = function() {
</div>
</section>
## Solution
@@ -69,4 +71,5 @@ var MinHeap = function() {
```js
// solution required
```
</section>

View File

@@ -2,31 +2,35 @@
id: 587d8256367417b2b2512c79
title: Incidence Matrix
challengeType: 1
videoUrl: ''
forumTopicId: 301644
localeTitle: Матрица инцидентов
---
## Description
<section id="description"> Еще один способ представить график - положить его в <dfn>матрицу инцидентности.</dfn> Матрица <dfn>инцидентности</dfn> представляет собой двумерный (2D) массив. Вообще говоря, матрица инцидентов связывает два разных класса объектов между двумя его измерениями. Такая матрица подобна матрице смежности. Тем не менее, строки и столбцы означают что-то еще здесь. В графах мы имеем ребра и узлы. Это будут наши «два разных класса объектов». Эта матрица будет содержать строки, в которых узлы и столбцы будут ребрами. Это означает, что мы можем иметь нечетное количество строк и столбцов. Каждый столбец будет представлять собой уникальный ребро. Кроме того, каждое ребро соединяет два узла. Чтобы показать, что существует ребро между двумя узлами, вы поместите 1 в две строки определенного столбца. Ниже приведен граф из 3 узлов с одним ребром между узлом 1 и узлом 3. <blockquote> 1 <br> --- <br> 1 | 1 <br> 2 | 0 <br> 3 | 1 </blockquote> Ниже приведен пример <code>incidence matrix</code> с 4 ребрами и 4 узлами. Помните, что столбцы - это ребра, а строки - сами узлы. <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> Ниже приведена реализация JavaScript того же самого. <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> Чтобы создать ориентированный граф, используйте <code>-1</code> для края, оставляющего определенный узел, и <code>1</code> для края, входящего в узел. <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> Графики также могут иметь <dfn>веса</dfn> по краям. До сих пор у нас есть <dfn>невзвешенные</dfn> края, где только наличие и отсутствие ребра двоично ( <code>0</code> или <code>1</code> ). Вы можете иметь разные веса в зависимости от вашего приложения. Другой вес представлен как числа больше 1. </section>
<section id='description'>
Еще один способ представить график - положить его в <dfn>матрицу инцидентности.</dfn> Матрица <dfn>инцидентности</dfn> представляет собой двумерный (2D) массив. Вообще говоря, матрица инцидентов связывает два разных класса объектов между двумя его измерениями. Такая матрица подобна матрице смежности. Тем не менее, строки и столбцы означают что-то еще здесь. В графах мы имеем ребра и узлы. Это будут наши «два разных класса объектов». Эта матрица будет содержать строки, в которых узлы и столбцы будут ребрами. Это означает, что мы можем иметь нечетное количество строк и столбцов. Каждый столбец будет представлять собой уникальный ребро. Кроме того, каждое ребро соединяет два узла. Чтобы показать, что существует ребро между двумя узлами, вы поместите 1 в две строки определенного столбца. Ниже приведен граф из 3 узлов с одним ребром между узлом 1 и узлом 3. <blockquote> 1 <br> --- <br> 1 | 1 <br> 2 | 0 <br> 3 | 1 </blockquote> Ниже приведен пример <code>incidence matrix</code> с 4 ребрами и 4 узлами. Помните, что столбцы - это ребра, а строки - сами узлы. <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> Ниже приведена реализация JavaScript того же самого. <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> Чтобы создать ориентированный граф, используйте <code>-1</code> для края, оставляющего определенный узел, и <code>1</code> для края, входящего в узел. <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> Графики также могут иметь <dfn>веса</dfn> по краям. До сих пор у нас есть <dfn>невзвешенные</dfn> края, где только наличие и отсутствие ребра двоично ( <code>0</code> или <code>1</code> ). Вы можете иметь разные веса в зависимости от вашего приложения. Другой вес представлен как числа больше 1.
</section>
## Instructions
<section id="instructions"> Создайте матрицу инцидентности неориентированного графа с пятью узлами и четырьмя ребрами. Эта матрица должна быть в многомерном массиве. Эти пять узлов имеют отношения, следующие за отношениями. Первое ребро находится между первым и вторым узлами. Второе ребро находится между вторым и третьим узлами. Третий край находится между третьим и пятым узлами. И четыре края расположены между четвертым и вторым узлами. Все весовые коэффициенты ребер имеют один и порядок ребер. </section>
<section id='instructions'>
Создайте матрицу инцидентности неориентированного графа с пятью узлами и четырьмя ребрами. Эта матрица должна быть в многомерном массиве. Эти пять узлов имеют отношения, следующие за отношениями. Первое ребро находится между первым и вторым узлами. Второе ребро находится между вторым и третьим узлами. Третий край находится между третьим и пятым узлами. И четыре края расположены между четвертым и вторым узлами. Все весовые коэффициенты ребер имеют один и порядок ребер.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>incMatUndirected</code> должен содержать только пять узлов.
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: Между первым и вторым узлом должно быть первое ребро.
testString: 'assert((incMatUndirected[0][0] === 1) && (incMatUndirected[1][0] === 1), "There should be a first edge between the first and second node.");'
- text: Между вторым и третьим узлами должно быть второе ребро.
testString: 'assert((incMatUndirected[1][1] === 1) && (incMatUndirected[2][1] === 1), "There should be a second edge between the second and third node.");'
- text: Между третьим и пятым узлами должно быть третье ребро.
testString: 'assert((incMatUndirected[2][2] === 1) && (incMatUndirected[4][2] === 1), "There should be a third edge between the third and fifth node.");'
- text: Между вторым и четвертым узлами должно быть четвертое грани.
testString: 'assert((incMatUndirected[1][3] === 1) && (incMatUndirected[3][3] === 1), "There should be a fourth edge between the second and fourth node.");'
- text: <code>incMatUndirected</code> should only contain five nodes.
testString: assert((incMatUndirected.length === 5) && incMatUndirected.map(function(x) { return x.length === 4 }).reduce(function(a, b) { return a && b }) );
- text: There should be a first edge between the first and second node.
testString: assert((incMatUndirected[0][0] === 1) && (incMatUndirected[1][0] === 1));
- text: There should be a second edge between the second and third node.
testString: assert((incMatUndirected[1][1] === 1) && (incMatUndirected[2][1] === 1));
- text: There should be a third edge between the third and fifth node.
testString: assert((incMatUndirected[2][2] === 1) && (incMatUndirected[4][2] === 1));
- text: There should be a fourth edge between the second and fourth node.
testString: assert((incMatUndirected[1][3] === 1) && (incMatUndirected[3][3] === 1));
```
@@ -46,14 +50,13 @@ var incMatUndirected = [
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
var incMatUndirected = [[1, 0, 0, 0],[1, 1, 0, 1],[0, 1, 1, 0],[0, 0, 0, 1],[0, 0, 1, 0]];
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8259367417b2b2512c83
title: Invert a Binary Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301704
localeTitle: Инвертировать двоичное дерево
---
## Description
<section id="description"> Здесь мы создадим функцию инвертирования двоичного дерева. Учитывая двоичное дерево, мы хотим создать новое дерево, эквивалентное зеркальному изображению этого дерева. Выполнение обхода порядка на инвертированном дереве будет исследовать узлы в обратном порядке по сравнению с обходным порядком исходного дерева. Напишите метод для этого, который называется <code>invert</code> на нашем двоичном дереве. Вызов этого метода должен инвертировать текущую древовидную структуру. В идеале мы хотели бы сделать это на месте в линейном времени. То есть мы только посещаем каждый узел один раз, и мы изменяем существующую древовидную структуру, когда мы идем, без использования дополнительной памяти. Удачи! </section>
<section id='description'>
Здесь мы создадим функцию инвертирования двоичного дерева. Учитывая двоичное дерево, мы хотим создать новое дерево, эквивалентное зеркальному изображению этого дерева. Выполнение обхода порядка на инвертированном дереве будет исследовать узлы в обратном порядке по сравнению с обходным порядком исходного дерева. Напишите метод для этого, который называется <code>invert</code> на нашем двоичном дереве. Вызов этого метода должен инвертировать текущую древовидную структуру. В идеале мы хотели бы сделать это на месте в линейном времени. То есть мы только посещаем каждый узел один раз, и мы изменяем существующую древовидную структуру, когда мы идем, без использования дополнительной памяти. Удачи!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Инвертировать двоичное дерево
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: Двоичное дерево поиска имеет метод <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: Метод <code>invert</code> корректно инвертирует древовидную структуру.
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: Инвертирование пустого дерева возвращает <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>.");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>invert</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.invert == 'function')})());
- text: The <code>invert</code> method correctly inverts the tree structure.
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'; })());
- text: Inverting an empty tree returns <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); })());
```
@@ -39,26 +42,73 @@ tests:
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left)
};
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
};
} else {
return null;
};
};
return searchTree(node);
};
},
inorder: function() {
if (this.root == null) {
return null;
} else {
var result = new Array();
function traverseInOrder(node) {
if (node.left != null) {
traverseInOrder(node.left);
};
result.push(node.value);
if (node.right != null) {
traverseInOrder(node.right);
};
}
traverseInOrder(this.root);
return result;
};
}
};
```
</div>
@@ -69,6 +119,27 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
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
this.invert = function(node = this.root) {
if (node) {
const temp = node.left;
node.left = node.right;
node.right = temp;
this.invert(node.left);
this.invert(node.right);
}
return node;
}
// change code above this line
}
```
</section>

View File

@@ -2,29 +2,33 @@
id: 587d8250367417b2b2512c5e
title: Learn how a Stack Works
challengeType: 1
videoUrl: ''
localeTitle: 'Узнайте, как работает стек'
forumTopicId: 301705
localeTitle: Узнайте, как работает стек
---
## Description
<section id="description"> Вероятно, вы знакомы со стопкой книг на своем столе. Вероятно, вы использовали функцию отмены текстового редактора. Вы также, вероятно, используете для нажатия кнопки «Назад» на своем телефоне, чтобы вернуться к предыдущему виду в приложении. Вы знаете, что у них общего? Все они хранят данные таким образом, чтобы вы могли перемещаться назад. Самая верхняя книга в стеке была той, которая была помещена последней. Если вы удалите эту книгу из верхней части стека, вы откроете книгу, которая была помещена туда до последней книги, и так далее. Если вы думаете об этом, во всех приведенных выше примерах вы получаете тип обслуживания <dfn>Last-In-First-Out</dfn> . Мы постараемся имитировать это с помощью нашего кода. Эта схема хранения данных называется <dfn>стеком</dfn> . В частности, нам пришлось бы реализовать метод <code>push()</code> который толкает объекты JavaScript вверху стека; и <code>pop()</code> , который удаляет объект JavaScript, который находится в верхней части стека в текущий момент. </section>
<section id='description'>
Вероятно, вы знакомы со стопкой книг на своем столе. Вероятно, вы использовали функцию отмены текстового редактора. Вы также, вероятно, используете для нажатия кнопки «Назад» на своем телефоне, чтобы вернуться к предыдущему виду в приложении. Вы знаете, что у них общего? Все они хранят данные таким образом, чтобы вы могли перемещаться назад. Самая верхняя книга в стеке была той, которая была помещена последней. Если вы удалите эту книгу из верхней части стека, вы откроете книгу, которая была помещена туда до последней книги, и так далее. Если вы думаете об этом, во всех приведенных выше примерах вы получаете тип обслуживания <dfn>Last-In-First-Out</dfn> . Мы постараемся имитировать это с помощью нашего кода. Эта схема хранения данных называется <dfn>стеком</dfn> . В частности, нам пришлось бы реализовать метод <code>push()</code> который толкает объекты JavaScript вверху стека; и <code>pop()</code> , который удаляет объект JavaScript, который находится в верхней части стека в текущий момент.
</section>
## Instructions
<section id="instructions"> Здесь у нас есть набор домашних заданий, представленных как массив: <code>&quot;BIO12&quot;</code> находится у основания, а <code>&quot;PSY44&quot;</code> находится в верхней части стека. Измените данный массив и обработайте его как <code>stack</code> используя описанные выше методы JavaScript. Удалите верхний элемент <code>&quot;PSY44&quot;</code> из стека. Затем добавьте <code>&quot;CS50&quot;</code> в новый верхний элемент стека. </section>
<section id='instructions'>
Здесь у нас есть набор домашних заданий, представленных как массив: <code>&quot;BIO12&quot;</code> находится у основания, а <code>&quot;PSY44&quot;</code> находится в верхней части стека. Измените данный массив и обработайте его как <code>stack</code> используя описанные выше методы JavaScript. Удалите верхний элемент <code>&quot;PSY44&quot;</code> из стека. Затем добавьте <code>&quot;CS50&quot;</code> в новый верхний элемент стека.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>homeworkStack</code> должен содержать только 4 элемента.
testString: 'assert(homeworkStack.length === 4, "<code>homeworkStack</code> should only contain 4 elements.");'
- text: Последним элементом <code>homeworkStack</code> должен быть <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> .
testString: 'assert(homeworkStack.indexOf("PSY44") === -1, "<code>homeworkStack</code> should not contain <code>"PSY44"</code>.");'
- text: Исходное объявление <code>homeworkStack</code> таблицы не должно быть изменено.
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.");'
- text: <code>homeworkStack</code> should only contain 4 elements.
testString: assert(homeworkStack.length === 4);
- text: The last element in <code>homeworkStack</code> should be <code>"CS50"</code>.
testString: assert(homeworkStack[3] === 'CS50');
- text: <code>homeworkStack</code> should not contain <code>"PSY44"</code>.
testString: assert(homeworkStack.indexOf('PSY44') === -1);
- text: The initial declaration of the <code>homeworkStack</code> should not be changed.
testString: assert(code.match(/=/g).length === 1 && /homeworkStack\s*=\s*\["BIO12"\s*,\s*"HIS80"\s*,\s*"MAT122"\s*,\s*"PSY44"\]/.test(code));
```
@@ -43,8 +47,6 @@ var homeworkStack = ["BIO12","HIS80","MAT122","PSY44"];
</div>
</section>
## Solution
@@ -53,4 +55,5 @@ var homeworkStack = ["BIO12","HIS80","MAT122","PSY44"];
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8254367417b2b2512c6e
title: Perform a Difference on Two Sets of Data
challengeType: 1
videoUrl: ''
forumTopicId: 301706
localeTitle: Выполните разницу на двух наборах данных
---
## Description
<section id="description"> В этом упражнении мы собираемся выполнить разницу на 2 набора данных. Мы создадим метод на нашем <code>Set</code> структуры данных называется <code>difference</code> . Разница множеств должна сравнивать два набора и возвращать элементы, присутствующие в первом наборе, отсутствующие во втором. Этот метод должен принять другой <code>Set</code> в качестве аргумента и вернуть <code>difference</code> двух наборов. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , то разность setA и setB равна: <code>setA.difference(setB) = [&#39;c&#39;]</code> . </section>
<section id='description'>
В этом упражнении мы собираемся выполнить разницу на 2 набора данных. Мы создадим метод на нашем <code>Set</code> структуры данных называется <code>difference</code> . Разница множеств должна сравнивать два набора и возвращать элементы, присутствующие в первом наборе, отсутствующие во втором. Этот метод должен принять другой <code>Set</code> в качестве аргумента и вернуть <code>difference</code> двух наборов. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , то разность setA и setB равна: <code>setA.difference(setB) = [&#39;c&#39;]</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Выполните разницу на двух наборах да
```yml
tests:
- text: Класс <code>Set</code> должен иметь <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: Собственная коллекция была возвращена
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");'
- text: Your <code>Set</code> class should have a <code>difference</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.difference === 'function')})());
- text: Your <code>difference</code> method should return the proper collection.
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) && DeepEqual(differenceSetAB.values(), [ 'a', 'b' ])})());
```
@@ -97,14 +100,79 @@ function Set() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
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.difference = function(otherSet) {
var differenceSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e) {
if (!otherSet.has(e)) {
differenceSet.add(e);
}
});
return differenceSet;
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8254367417b2b2512c6f
title: Perform a Subset Check on Two Sets of Data
challengeType: 1
videoUrl: ''
forumTopicId: 301707
localeTitle: Выполните проверку подмножества на двух наборах данных
---
## Description
<section id="description"> В этом упражнении мы собираемся выполнить тест подмножества на 2 набора данных. Мы создадим метод на нашем <code>Set</code> структуры данных называется <code>subset</code> . Это будет сравнивать первый набор, второй и если первый набор полностью содержится внутри второго, тогда он вернет true. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]</code> , то подмножество setA и setB будет: <code>setA.subset(setB)</code> должно быть <code>true</code> . </section>
<section id='description'>
В этом упражнении мы собираемся выполнить тест подмножества на 2 набора данных. Мы создадим метод на нашем <code>Set</code> структуры данных называется <code>subset</code> . Это будет сравнивать первый набор, второй и если первый набор полностью содержится внутри второго, тогда он вернет true. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]</code> , то подмножество setA и setB будет: <code>setA.subset(setB)</code> должно быть <code>true</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Выполните проверку подмножества на
```yml
tests:
- text: Класс <code>Set</code> должен иметь метод <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: Первый 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> должно возвращать <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> должно возвращать <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> должен возвращать <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> должно возвращать <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>");'
- text: Your <code>Set</code> class should have a <code>subset</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.subset === 'function')})());
- text: The first Set() was contained in the second 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)})());
- text: <code>['a', 'b'].subset(['a', 'b', 'c', 'd'])</code> should return <code>true</code>
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)})());
- text: <code>['a', 'b', 'c'].subset(['a', 'b'])</code> should return <code>false</code>
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)})());
- text: <code>[].subset([])</code> should return <code>true</code>
testString: assert((function(){var setA = new Set(); var setB = new Set(); var subsetSetAB = setA.subset(setB); return (subsetSetAB === true)})());
- text: <code>['a', 'b'].subset(['c', 'd'])</code> should return <code>false</code>
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)})());
```
@@ -116,14 +119,13 @@ function Set() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};this.size = function() {return collection.length;};this.union = function(set) {var u = new Set();var c = this.values();var s = set.values();c.forEach(function(element){u.add(element);});s.forEach(function(element){u.add(element);});return u;};this.intersection = function(set) {var i = new Set();var c = this.values();c.forEach(function(element){if(s.has(element)) i.add(element);});};this.difference = function(set) {var d = new Set();var c = this.values();c.forEach(function(e){if(!set.has(e)) d.add(e);});};this.subset = function(set) {var isSubset = true;var c = this.values();c.forEach(function(e){if(!set.has(e)) isSubset = false;});return isSubset;};}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8253367417b2b2512c6c
title: Perform a Union on Two Sets
challengeType: 1
videoUrl: ''
forumTopicId: 301708
localeTitle: Выполните Союз на двух наборах
---
## Description
<section id="description"> В этом упражнении мы собираемся выполнить объединение на двух наборах данных. Мы создадим метод в нашей структуре данных <code>Set</code> называемый <code>union</code> . Этот метод должен принимать другой <code>Set</code> в качестве аргумента и возвращать <code>union</code> двух наборов, исключая любые повторяющиеся значения. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , то объединение множества A и setB: <code>setA.union(setB) = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]</code> . </section>
<section id='description'>
В этом упражнении мы собираемся выполнить объединение на двух наборах данных. Мы создадим метод в нашей структуре данных <code>Set</code> называемый <code>union</code> . Этот метод должен принимать другой <code>Set</code> в качестве аргумента и возвращать <code>union</code> двух наборов, исключая любые повторяющиеся значения. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , то объединение множества A и 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 id='instructions'>
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Выполните Союз на двух наборах
```yml
tests:
- text: Класс <code>Set</code> должен иметь метод <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: Собственная коллекция была возвращена
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");'
- text: Your <code>Set</code> class should have a <code>union</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.union === 'function')})());
- text: The union of <code>["a", "b", "c"]</code> and <code>["c", "d"]</code> should return <code>["a", "b", "c", "d"]</code>.
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)})());
```
@@ -74,14 +77,52 @@ function Set() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function Set() {
var collection = [];
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
this.values = function() {
return collection;
};
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
this.size = function() {
return collection.length;
};
this.union = function(anotherSet){
const newSet = new Set();
const addToSet = el => newSet.add(el);
this.values().forEach(addToSet);
anotherSet.values().forEach(addToSet);
return newSet;
};
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8253367417b2b2512c6d
title: Perform an Intersection on Two Sets of Data
challengeType: 1
videoUrl: ''
forumTopicId: 301709
localeTitle: Выполнить пересечение на двух наборах данных
---
## Description
<section id="description"> В этом упражнении мы собираемся выполнить пересечение на 2 набора данных. Мы создадим метод на наших <code>Set</code> структуры данных называется <code>intersection</code> . Пересечение множеств представляет все значения, которые являются общими для двух или более наборов. Этот метод должен принимать другой <code>Set</code> в качестве аргумента и возвращать <code>intersection</code> двух наборов. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , то пересечение множества A и множества B: <code>setA.intersection(setB) = [&#39;a&#39;, &#39;b&#39;]</code> . </section>
<section id='description'>
В этом упражнении мы собираемся выполнить пересечение на 2 набора данных. Мы создадим метод на наших <code>Set</code> структуры данных называется <code>intersection</code> . Пересечение множеств представляет все значения, которые являются общими для двух или более наборов. Этот метод должен принимать другой <code>Set</code> в качестве аргумента и возвращать <code>intersection</code> двух наборов. Например, если <code>setA = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</code> и <code>setB = [&#39;a&#39;,&#39;b&#39;,&#39;d&#39;,&#39;e&#39;]</code> , то пересечение множества A и множества B: <code>setA.intersection(setB) = [&#39;a&#39;, &#39;b&#39;]</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Выполнить пересечение на двух набор
```yml
tests:
- text: Класс <code>Set</code> должен иметь метод <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: Собственная коллекция была возвращена
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");'
- text: Your <code>Set</code> class should have a <code>intersection</code> method.
testString: assert((function(){var test = new Set(); return (typeof test.intersection === 'function')})());
- text: The proper collection was returned
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')})());
```
@@ -86,14 +89,68 @@ function Set() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
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.intersection = function(otherSet) {
var intersectionSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e) {
if (otherSet.has(e)) {
intersectionSet.add(e);
}
})
return intersectionSet;
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d825b367417b2b2512c8b
title: Remove an Element from a Max Heap
challengeType: 1
videoUrl: ''
forumTopicId: 301710
localeTitle: Удалить элемент из максимальной кучи
---
## Description
<section id="description"> Теперь, когда мы можем добавить элементы в нашу кучу, посмотрим, как мы можем удалить элементы. Для снятия и вставки элементов требуется аналогичная логика. В максимальной куче вы обычно хотите удалить наибольшую ценность, поэтому это требует просто извлечь ее из корня нашего дерева. Это разрушит свойство кучи нашего дерева, поэтому мы должны каким-то образом восстановить его. Как правило, для максимальной кучи это делается следующим образом: переместите последний элемент в куче в корневую позицию. Если любой корень корня больше, чем он, замените корень с дочерним значением большего значения. Продолжайте замену, пока родитель больше, чем оба ребенка, или вы достигнете последнего уровня в дереве. Инструкции: добавьте метод в нашу максимальную кучу, называемую remove. Этот метод должен вернуть наибольшее значение, которое было добавлено в нашу максимальную кучу и удалить его из кучи. Он также должен изменить порядок кучи, чтобы сохранить свойство кучи. После удаления элемента следующий главный элемент, оставшийся в куче, должен стать корнем. Здесь также добавьте свой метод вставки. </section>
<section id='description'>
Теперь, когда мы можем добавить элементы в нашу кучу, посмотрим, как мы можем удалить элементы. Для снятия и вставки элементов требуется аналогичная логика. В максимальной куче вы обычно хотите удалить наибольшую ценность, поэтому это требует просто извлечь ее из корня нашего дерева. Это разрушит свойство кучи нашего дерева, поэтому мы должны каким-то образом восстановить его. Как правило, для максимальной кучи это делается следующим образом: переместите последний элемент в куче в корневую позицию. Если любой корень корня больше, чем он, замените корень с дочерним значением большего значения. Продолжайте замену, пока родитель больше, чем оба ребенка, или вы достигнете последнего уровня в дереве. Инструкции: добавьте метод в нашу максимальную кучу, называемую remove. Этот метод должен вернуть наибольшее значение, которое было добавлено в нашу максимальную кучу и удалить его из кучи. Он также должен изменить порядок кучи, чтобы сохранить свойство кучи. После удаления элемента следующий главный элемент, оставшийся в куче, должен стать корнем. Здесь также добавьте свой метод вставки.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Удалить элемент из максимальной куч
```yml
tests:
- text: Структура данных MaxHeap существует.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== "undefined") { test = new MaxHeap() }; return (typeof test == "object")})(), "The MaxHeap data structure exists.");'
- text: У MaxHeap есть метод под названием 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 имеет метод, называемый 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 есть метод, называемый remove.'
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: 'Метод remove удаляет наибольший элемент из максимальной кучи, сохраняя при этом свойство максимальной кучи.'
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.");'
- text: The MaxHeap data structure exists.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() }; return (typeof test == 'object')})());
- text: MaxHeap has a method called print.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.print == 'function')})());
- text: MaxHeap has a method called insert.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.insert == 'function')})());
- text: MaxHeap has a method called remove.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.remove == 'function')})());
- text: The remove method removes the greatest element from the max heap while maintaining the max heap property.
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') })());
```
@@ -48,8 +51,6 @@ var MaxHeap = function() {
</div>
</section>
## Solution
@@ -58,4 +59,5 @@ var MaxHeap = function() {
```js
// solution required
```
</section>

View File

@@ -2,31 +2,39 @@
id: 587d8251367417b2b2512c65
title: Remove Elements from a Linked List by Index
challengeType: 1
videoUrl: ''
forumTopicId: 301711
localeTitle: Удалить элементы из связанного списка по индексу
---
## Description
<section id="description"> Прежде чем перейти к другой структуре данных, давайте получим пару последних бит практики со связанными списками. Давайте напишем <code>removeAt</code> который удаляет <code>element</code> по заданному <code>index</code> . Метод следует называть <code>removeAt(index)</code> . Чтобы удалить <code>element</code> с определенным <code>index</code> , нам нужно сохранить количество запусков каждого узла при перемещении по связанному списку. Обычный метод, используемый для итерации через элементы связанного списка, включает в себя <dfn>«бегун»</dfn> или дозорный, который «указывает» на узлы, которые сравнивает ваш код. В нашем случае, начиная с <code>head</code> нашего списка, мы начинаем с переменной <code>currentIndex</code> которая начинается с <code>0</code> . <code>currentIndex</code> должен увеличиваться на единицу для каждого проходящего узла. Так же, как наш метод <code>remove(element)</code> , мы должны быть осторожны, чтобы не осилить остальную часть нашего списка, когда мы удаляем узел в нашем методе removeAt (index). Мы держим наши узлы смежными, убедившись, что узел, имеющий ссылку на удаленный узел, имеет ссылку на следующий узел. </section>
<section id='description'>
Прежде чем перейти к другой структуре данных, давайте получим пару последних бит практики со связанными списками. Давайте напишем <code>removeAt</code> который удаляет <code>element</code> по заданному <code>index</code> . Метод следует называть <code>removeAt(index)</code> . Чтобы удалить <code>element</code> с определенным <code>index</code> , нам нужно сохранить количество запусков каждого узла при перемещении по связанному списку. Обычный метод, используемый для итерации через элементы связанного списка, включает в себя <dfn>«бегун»</dfn> или дозорный, который «указывает» на узлы, которые сравнивает ваш код. В нашем случае, начиная с <code>head</code> нашего списка, мы начинаем с переменной <code>currentIndex</code> которая начинается с <code>0</code> . <code>currentIndex</code> должен увеличиваться на единицу для каждого проходящего узла. Так же, как наш метод <code>remove(element)</code> , мы должны быть осторожны, чтобы не осилить остальную часть нашего списка, когда мы удаляем узел в нашем методе removeAt (index). Мы держим наши узлы смежными, убедившись, что узел, имеющий ссылку на удаленный узел, имеет ссылку на следующий узел.
</section>
## Instructions
<section id="instructions"> Напишите <code>removeAt(index)</code> который удаляет и возвращает узел с заданным <code>index</code> . Метод должен возвращать значение <code>null</code> если данный <code>index</code> либо отрицательный, либо больше или равен <code>length</code> связанного списка. Примечание. Не забудьте сохранить счетчик <code>currentIndex</code> . </section>
<section id='instructions'>
Напишите <code>removeAt(index)</code> который удаляет и возвращает узел с заданным <code>index</code> . Метод должен возвращать значение <code>null</code> если данный <code>index</code> либо отрицательный, либо больше или равен <code>length</code> связанного списка. Примечание. Не забудьте сохранить счетчик <code>currentIndex</code> .
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Класс <code>LinkedList</code> должен иметь <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: Метод <code>removeAt</code> должен уменьшить <code>length</code> связанного списка
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: Метод <code>removeAt</code> также должен возвращать элемент удаленного узла.
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: Метод <code>removeAt</code> также должен возвращать значение <code>null</code> если данный индекс меньше <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: Метод <code>removeAt</code> также должен возвращать значение <code>null</code> если данный индекс равен или больше <code>length</code> связанного списка.
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.");'
- text: Your <code>LinkedList</code> class should have a <code>removeAt</code> method.
testString: assert((function(){var test = new LinkedList(); return (typeof test.removeAt === 'function')}()));
- text: Your <code>removeAt</code> method should reduce the <code>length</code> of the linked list by one.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); test.removeAt(1); return test.size() === 2}()));
- text: Your <code>removeAt</code> method should remove the element at the specified index from the linked list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); test.add('bird');test.removeAt(1); return JSON.stringify(test.head()) === '{"element":"cat","next":{"element":"kitten","next":{"element":"bird","next":null}}}'}()));
- text: When only one element is present in the linked list, your <code>removeAt</code> method should remove and return the element at specified index, and reduce the length of the linked list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); var removedItem = test.removeAt(0); return test.head() === null && test.size() === 0 && removedItem === 'cat';}()));
- text: Your <code>removeAt</code> method should return the element of the removed node.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); return test.removeAt(1) === 'dog'}()));
- text: Your <code>removeAt</code> method should return <code>null</code> and the linked list should not change if the given index is less than <code>0</code>.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); var removedItem = test.removeAt(-1); return removedItem === null && JSON.stringify(test.head()) === '{"element":"cat","next":{"element":"dog","next":{"element":"kitten","next":null}}}'}()));
- text: Your <code>removeAt</code> method should return <code>null</code> and the linked list should not change if the given index is greater than or equal to the <code>length</code> of the list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); var removedItem = test.removeAt(3); return removedItem === null && JSON.stringify(test.head()) === '{"element":"cat","next":{"element":"dog","next":{"element":"kitten","next":null}}}'}()));
```
@@ -72,23 +80,6 @@ function LinkedList() {
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
@@ -98,14 +89,69 @@ function LinkedList() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
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 {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.removeAt = function (index) {
var currentNode = head;
var previous = head;
var count = 0;
if (index >= length || index < 0) {
return null;
}
if (index === 0) {
var removed = head.element;
head = currentNode.next;
} else {
while (count < index) {
previous = currentNode;
currentNode = currentNode.next;
count++;
}
var removed = previous.next.element;
previous.next = currentNode.next;
}
length--;
return removed;
};
}
```
</section>

View File

@@ -2,29 +2,35 @@
id: 587d8251367417b2b2512c63
title: Remove Elements from a Linked List
challengeType: 1
videoUrl: ''
forumTopicId: 301712
localeTitle: Удалить элементы из связанного списка
---
## Description
<section id="description"> Следующим важным методом, который потребуется для любой реализации связанного списка, является метод <code>remove</code> . Этот метод должен взять элемент, который мы хотим удалить в качестве аргумента, а затем выполнить поиск в списке, чтобы найти и удалить узел, содержащий этот элемент. Всякий раз, когда мы удаляем узел из связанного списка, важно, чтобы мы не случайно оставили все остальное в списке. Напомним, что <code>next</code> свойство <code>next</code> узла указывает на узел, который следует за ним в списке. Если мы удалим средний элемент, скажем, мы хотим убедиться , что у нас есть связь с предыдущим узлом этого элемента <code>next</code> имущества к середине элемента <code>next</code> имуществу (который является следующим узлом в списке!) Это может показаться действительно запутанный, так что давайте вернемся к примеру линии conga, чтобы у нас была хорошая концептуальная модель. Представьте себя в линии конги, и человек прямо перед вами покинет линию. Лицо, которое только что покинуло линию, больше не имеет руки на кого-либо в очереди - и у вас больше нет рук на лице, которое осталось. Вы шагнете вперед и положите руки на следующего человека, которого видите. Если элемент мы хотим , чтобы удалить это <code>head</code> элемент, мы переназначить <code>head</code> на второй узел связанного списка. </section>
<section id='description'>
Следующим важным методом, который потребуется для любой реализации связанного списка, является метод <code>remove</code> . Этот метод должен взять элемент, который мы хотим удалить в качестве аргумента, а затем выполнить поиск в списке, чтобы найти и удалить узел, содержащий этот элемент. Всякий раз, когда мы удаляем узел из связанного списка, важно, чтобы мы не случайно оставили все остальное в списке. Напомним, что <code>next</code> свойство <code>next</code> узла указывает на узел, который следует за ним в списке. Если мы удалим средний элемент, скажем, мы хотим убедиться , что у нас есть связь с предыдущим узлом этого элемента <code>next</code> имущества к середине элемента <code>next</code> имуществу (который является следующим узлом в списке!) Это может показаться действительно запутанный, так что давайте вернемся к примеру линии conga, чтобы у нас была хорошая концептуальная модель. Представьте себя в линии конги, и человек прямо перед вами покинет линию. Лицо, которое только что покинуло линию, больше не имеет руки на кого-либо в очереди - и у вас больше нет рук на лице, которое осталось. Вы шагнете вперед и положите руки на следующего человека, которого видите. Если элемент мы хотим , чтобы удалить это <code>head</code> элемент, мы переназначить <code>head</code> на второй узел связанного списка.
</section>
## Instructions
<section id="instructions"> Напишите метод <code>remove</code> который принимает элемент и удаляет его из связанного списка. Примечание. <code>length</code> списка должна уменьшаться на единицу при каждом удалении элемента из связанного списка. </section>
<section id='instructions'>
Напишите метод <code>remove</code> который принимает элемент и удаляет его из связанного списка. Примечание. <code>length</code> списка должна уменьшаться на единицу при каждом удалении элемента из связанного списка.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Класс <code>LinkedList</code> должен иметь метод <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: Метод <code>remove</code> должен переназначить <code>head</code> во второй узел при удалении первого узла.
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: Метод <code>remove</code> должен уменьшать <code>length</code> связанного списка по одному на каждый удаленный узел.
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: Метод <code>remove</code> должен переназначить ссылку предыдущего узла удаленного узла на <code>next</code> ссылку удаленного узла.
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.");'
- text: Your <code>LinkedList</code> class should have a <code>remove</code> method.
testString: assert((function(){var test = new LinkedList(); return (typeof test.remove === 'function')}()));
- text: Your <code>remove</code> method should reassign <code>head</code> to the second node when the first node is removed.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.remove('cat'); return test.head().element === 'dog'}()));
- text: Your <code>remove</code> method should decrease the <code>length</code> of the linked list by one for every node removed.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.remove('cat'); return test.size() === 1})());
- text: 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.
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'})());
- text: Your <code>remove</code> method should not change the linked list if the element does not exist in the linked list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog');test.add('kitten'); test.remove('elephant'); return JSON.stringify(test.head()) === '{"element":"cat","next":{"element":"dog","next":{"element":"kitten","next":null}}}'})());
```
@@ -81,14 +87,70 @@ function LinkedList() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
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 {
var currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
if (head === null) {
return;
}
var previous;
var currentNode = head;
while (currentNode.next !== null && currentNode.element !== element) {
previous = currentNode;
currentNode = currentNode.next;
}
if (currentNode.next === null && currentNode.element !== element) {
return;
}
else if (previous) {
previous.next = currentNode.next;
} else {
head = currentNode.next;
}
length--;
};
}
```
</section>

View File

@@ -7,10 +7,13 @@ localeTitle: Удалить из набора
---
## Description
<section id="description"> В этих упражнениях мы собираемся создать функцию удаления для нашего набора. Функция должна быть названа <code>this.remove</code> . Эта функция должна принимать значение и проверять, существует ли он в наборе. Если это так, удалите это значение из набора и верните true. В противном случае верните false. </section>
<section id='description'>
В этих упражнениях мы собираемся создать функцию удаления для нашего набора. Функция должна быть названа <code>this.remove</code> . Эта функция должна принимать значение и проверять, существует ли он в наборе. Если это так, удалите это значение из набора и верните true. В противном случае верните false.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -24,7 +27,6 @@ tests:
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: Ваш метод <code>remove</code> должен удалить данный элемент из набора.
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>
@@ -62,8 +64,6 @@ function Set() {
</div>
</section>
## Solution
@@ -72,4 +72,5 @@ function Set() {
```js
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d8254367417b2b2512c71
title: Remove items from a set in ES6
challengeType: 1
videoUrl: ''
forumTopicId: 301713
localeTitle: Удаление элементов из набора в ES6
---
## Description
<section id="description"> Давайте практикуем элементы removeimg из набора ES6, используя метод <code>delete</code> . Сначала создайте набор ES6 <code>var set = new Set([1,2,3]);</code> Теперь удалите элемент из вашего набора с помощью метода <code>delete</code> . <blockquote> set.delete (1); <br> console.log ([... set]) // должен возвращать [2, 3] <blockquote></blockquote></blockquote></section>
<section id='description'>
Давайте практикуем элементы removeimg из набора ES6, используя метод <code>delete</code> . Сначала создайте набор ES6 <code>var set = new Set([1,2,3]);</code> Теперь удалите элемент из вашего набора с помощью метода <code>delete</code> . <blockquote> set.delete (1); <br> console.log ([... set]) // должен возвращать [2, 3] <blockquote></blockquote></blockquote>
</section>
## Instructions
<section id="instructions"> Теперь создайте набор с целыми числами 1, 2, 3, 4 и 5. Удалите значения 2 и 5, а затем верните набор. </section>
<section id='instructions'>
Теперь создайте набор с целыми числами 1, 2, 3, 4 и 5. Удалите значения 2 и 5, а затем верните набор.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Ваш набор должен содержать значения 1, 3 и 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");'
- text: Your Set should contain the values 1, 3, & 4
testString: assert((function(){var test = checkSet(); return test.has(1) && test.has(3) && test.has(4) && test.size === 3;})());
```
@@ -42,14 +46,17 @@ function checkSet(){
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function checkSet(){
var set = new Set([1,2,3,4,5]);
set.delete(2);
set.delete(5);
return set;}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d825a367417b2b2512c88
title: Reverse a Doubly Linked List
challengeType: 1
videoUrl: ''
forumTopicId: 301714
localeTitle: Переверните двойной список ссылок
---
## Description
<section id="description"> Давайте создадим еще один метод для нашего дважды связанного списка, который называется reverse, который меняет список на месте. Как только метод выполняется, голова должна указывать на предыдущий хвост, а хвост должен указывать на предыдущую голову. Теперь, если мы пересекаем список от головы до хвоста, мы должны встретить узлы в обратном порядке по сравнению с исходным списком. Попытка изменить пустой список должна вернуть значение null. </section>
<section id='description'>
Давайте создадим еще один метод для нашего дважды связанного списка, который называется reverse, который меняет список на месте. Как только метод выполняется, голова должна указывать на предыдущий хвост, а хвост должен указывать на предыдущую голову. Теперь, если мы пересекаем список от головы до хвоста, мы должны встретить узлы в обратном порядке по сравнению с исходным списком. Попытка изменить пустой список должна вернуть значение null.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Переверните двойной список ссылок
```yml
tests:
- text: Существует структура данных DoublyLinkedList.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== "undefined") { test = new DoublyLinkedList() }; return (typeof test == "object")})(), "The DoublyLinkedList data structure exists.");'
- text: 'У DoublyLinkedList есть метод, называемый 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: 'У DoublyLinkedList есть метод, называемый обратным.'
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: Возврат пустого списка возвращает значение 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: Обратный метод отменяет список.
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: Следующая и предыдущая ссылки корректно сохраняются при перестановке списка.
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.");'
- text: The DoublyLinkedList data structure exists.
testString: assert((function() { var test = false; if (typeof DoublyLinkedList !== 'undefined') { test = new DoublyLinkedList() }; return (typeof test == 'object')})());
- text: The DoublyLinkedList has a method called 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')})());
- text: The DoublyLinkedList has a method called reverse.
testString: assert((function() { var test = false; if (typeof DoublyLinkedList !== 'undefined') { test = new DoublyLinkedList() }; if (test.reverse == undefined) { return false; }; return (typeof test.reverse == 'function')})());
- text: Reversing an empty list returns null.
testString: assert((function() { var test = false; if (typeof DoublyLinkedList !== 'undefined') { test = new DoublyLinkedList() }; return (test.reverse() == null); })());
- text: The reverse method reverses the list.
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'); })());
- text: The next and previous references are correctly maintained when a list is reversed.
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'); })());
```
@@ -57,12 +60,57 @@ var DoublyLinkedList = function() {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
DoublyLinkedList.prototype = {
add(data) {
if (this.head == null) {
this.head = new Node(data, null);
this.tail = this.head;
} else {
var node = this.head;
var prev = null;
while (node.next != null) {
prev = node;
node = node.next;
};
var newNode = new Node(data, node);
node.next = newNode;
this.tail = newNode;
};
},
print() {
if (this.head == null) {
return null;
} else {
var result = new Array();
var node = this.head;
while (node.next != null) {
result.push(node.data);
node = node.next;
};
result.push(node.data);
return result;
};
},
printReverse() {
if (this.tail == null) {
return null;
} else {
var result = new Array();
var node = this.tail;
while (node.prev != null) {
result.push(node.data);
node = node.prev;
};
result.push(node.data);
return result;
};
}
};
```
</div>
@@ -75,4 +123,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,31 +2,35 @@
id: 587d8251367417b2b2512c64
title: Search within a Linked List
challengeType: 1
videoUrl: ''
forumTopicId: 301715
localeTitle: Поиск в связанном списке
---
## Description
<section id="description"> Давайте добавим еще несколько полезных методов в наш связанный класс списка. Не было бы полезно, если бы мы могли сказать, был ли наш список пустым или нет, как в наших классах <code>Stack</code> и <code>Queue</code> ? Мы также должны иметь возможность находить определенные элементы в нашем связанном списке. Прохождение через структуры данных - это то, с чем вы захотите получить много практики! Давайте создадим метод <code>indexOf</code> который принимает <code>element</code> в качестве аргумента и возвращает <code>index</code> этого элемента в связанном списке. Если элемент не найден в связанном списке, верните <code>-1</code> . Давайте также реализуем метод, который делает обратное: метод <code>elementAt</code> который принимает <code>index</code> в качестве аргумента и возвращает <code>element</code> в указанном <code>index</code> . Если ни один <code>element</code> не найден, возвращайте <code>undefined</code> . </section>
<section id='description'>
Давайте добавим еще несколько полезных методов в наш связанный класс списка. Не было бы полезно, если бы мы могли сказать, был ли наш список пустым или нет, как в наших классах <code>Stack</code> и <code>Queue</code> ? Мы также должны иметь возможность находить определенные элементы в нашем связанном списке. Прохождение через структуры данных - это то, с чем вы захотите получить много практики! Давайте создадим метод <code>indexOf</code> который принимает <code>element</code> в качестве аргумента и возвращает <code>index</code> этого элемента в связанном списке. Если элемент не найден в связанном списке, верните <code>-1</code> . Давайте также реализуем метод, который делает обратное: метод <code>elementAt</code> который принимает <code>index</code> в качестве аргумента и возвращает <code>element</code> в указанном <code>index</code> . Если ни один <code>element</code> не найден, возвращайте <code>undefined</code> .
</section>
## Instructions
<section id="instructions"> Напишите метод <code>isEmpty</code> который проверяет, является ли связанный список пустым, метод <code>indexOf</code> который возвращает <code>index</code> данного элемента, и <code>elementAt</code> который возвращает <code>element</code> в указанном <code>index.</code> </section>
<section id='instructions'>
Напишите метод <code>isEmpty</code> который проверяет, является ли связанный список пустым, метод <code>indexOf</code> который возвращает <code>index</code> данного элемента, и <code>elementAt</code> который возвращает <code>element</code> в указанном <code>index.</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Класс <code>LinkedList</code> должен иметь метод <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: Класс <code>LinkedList</code> должен иметь метод <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: Метод <code>size</code> должен возвращать длину связанного списка.
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: Ваш метод <code>indexOf</code> должен возвращать индекс данного элемента.
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: Метод <code>elementAt</code> должен возвращаться в элементе по заданному индексу.
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.");'
- text: Your <code>LinkedList</code> class should have a <code>indexOf</code> method.
testString: assert((function(){var test = new LinkedList(); return (typeof test.indexOf === 'function')}()));
- text: Your <code>LinkedList</code> class should have a <code>elementAt</code> method.
testString: assert((function(){var test = new LinkedList(); return (typeof test.elementAt === 'function')}()));
- text: Your <code>size</code> method should return the length of the linked list
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); return test.size() === 3}()));
- text: Your <code>indexOf</code> method should return the index of the given element.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); return test.indexOf('kitten') === 2}()));
- text: Your <code>elementAt</code> method should return at element at a given index.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); return test.elementAt(1) === 'dog'}()));
```
@@ -98,8 +102,6 @@ function LinkedList() {
</div>
</section>
## Solution
@@ -108,4 +110,5 @@ function LinkedList() {
```js
// solution required
```
</section>

View File

@@ -7,10 +7,13 @@ localeTitle: Размер набора
---
## Description
<section id="description"> В этом упражнении мы собираемся создать функцию размера для нашего Set. Эта функция должна быть названа <code>this.size</code> и она должна вернуть размер коллекции. </section>
<section id='description'>
В этом упражнении мы собираемся создать функцию размера для нашего Set. Эта функция должна быть названа <code>this.size</code> и она должна вернуть размер коллекции.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -22,7 +25,6 @@ tests:
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: Метод <code>size</code> должен возвращать количество элементов в коллекции.
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>
@@ -69,8 +71,6 @@ function Set() {
</div>
</section>
## Solution
@@ -79,4 +79,5 @@ function Set() {
```js
// solution required
```
</section>

View File

@@ -2,27 +2,31 @@
id: 587d8253367417b2b2512c6a
title: Typed Arrays
challengeType: 1
videoUrl: ''
forumTopicId: 301716
localeTitle: Типизированные массивы
---
## Description
<section id="description"> Массивы - это объекты JavaScript, которые могут содержать множество разных элементов. <code>var complexArr = [1, 5, &quot;2&quot;, &quot;Word&quot;, {&quot;name&quot;: &quot;James&quot;}];</code> В основном, что происходит в фоновом режиме, так это то, что ваш браузер автоматически предоставит необходимый объем памяти для этого массива. Он также будет изменяться по мере необходимости, если вы добавите или удалите данные. Тем не менее, в мире высокой производительности и разных типов элементов иногда требуется более конкретная информация о том, сколько памяти передано массиву. Ответы на эту проблему вызывают <dfn>типизированные массивы</dfn> . Теперь вы можете сказать, сколько памяти вы хотите дать массиву. Ниже представлен базовый обзор различных типов доступных массивов и размер в байтах для каждого элемента в этом массиве. <table class="table table-striped"><tbody><tr><th> Тип </th><th> Размер каждого элемента в байтах </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> Существует два способа создания таких массивов. Один из способов - создать его напрямую. Ниже <code>Int16Array</code> как создать <code>Int16Array</code> длиной 3 длины. <blockquote> var i8 = новый Int16Array (3); <br> console.log (i8); <br> // Возвращает [0, 0, 0] </blockquote> Вы также можете создать <dfn>буфер,</dfn> чтобы указать, сколько данных (в байтах) требуется массиву. <strong>Заметка</strong> <br> Чтобы создать типизированные массивы с использованием буферов, вам необходимо назначить количество байтов кратным байтам, перечисленным выше. <blockquote> // Создаем такой же массив Int16Array по-разному <br> var byteSize = 6; // Требуется быть кратным 2 <br> var buffer = new ArrayBuffer (byteSize); <br> var i8View = новый Int16Array (буфер); <br> buffer.byteLength; // Возвращает 6 <br> i8View.byteLength; // Возвращает 6 <br> console.log (i8View); // Возвращает [0, 0, 0] </blockquote> <dfn>Буферы</dfn> представляют собой объекты общего назначения, которые просто переносят данные. Вы не можете получить к ним доступ в обычном режиме. Чтобы получить к ним доступ, вам нужно сначала создать <dfn>представление</dfn> . <blockquote> i8View [0] = 42; <br> console.log (i8View); // Возвращает [42, 0, 0] </blockquote> <strong>Заметка</strong> <br> Типизированные массивы не имеют некоторых методов, которые имеют традиционные массивы, такие как <code>.pop()</code> или <code>.push()</code> . В типизированных массивах также отсутствует <code>Array.isArray()</code> который проверяет, что-то есть массив. Хотя это проще, это может быть преимуществом для менее сложных JavaScript-движков для их реализации. </section>
<section id='description'>
Массивы - это объекты JavaScript, которые могут содержать множество разных элементов. <code>var complexArr = [1, 5, &quot;2&quot;, &quot;Word&quot;, {&quot;name&quot;: &quot;James&quot;}];</code> В основном, что происходит в фоновом режиме, так это то, что ваш браузер автоматически предоставит необходимый объем памяти для этого массива. Он также будет изменяться по мере необходимости, если вы добавите или удалите данные. Тем не менее, в мире высокой производительности и разных типов элементов иногда требуется более конкретная информация о том, сколько памяти передано массиву. Ответы на эту проблему вызывают <dfn>типизированные массивы</dfn> . Теперь вы можете сказать, сколько памяти вы хотите дать массиву. Ниже представлен базовый обзор различных типов доступных массивов и размер в байтах для каждого элемента в этом массиве. <table class="table table-striped"><tbody><tr><th> Тип </th><th> Размер каждого элемента в байтах </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> Существует два способа создания таких массивов. Один из способов - создать его напрямую. Ниже <code>Int16Array</code> как создать <code>Int16Array</code> длиной 3 длины. <blockquote> var i8 = новый Int16Array (3); <br> console.log (i8); <br> // Возвращает [0, 0, 0] </blockquote> Вы также можете создать <dfn>буфер,</dfn> чтобы указать, сколько данных (в байтах) требуется массиву. <strong>Заметка</strong> <br> Чтобы создать типизированные массивы с использованием буферов, вам необходимо назначить количество байтов кратным байтам, перечисленным выше. <blockquote> // Создаем такой же массив Int16Array по-разному <br> var byteSize = 6; // Требуется быть кратным 2 <br> var buffer = new ArrayBuffer (byteSize); <br> var i8View = новый Int16Array (буфер); <br> buffer.byteLength; // Возвращает 6 <br> i8View.byteLength; // Возвращает 6 <br> console.log (i8View); // Возвращает [0, 0, 0] </blockquote> <dfn>Буферы</dfn> представляют собой объекты общего назначения, которые просто переносят данные. Вы не можете получить к ним доступ в обычном режиме. Чтобы получить к ним доступ, вам нужно сначала создать <dfn>представление</dfn> . <blockquote> i8View [0] = 42; <br> console.log (i8View); // Возвращает [42, 0, 0] </blockquote> <strong>Заметка</strong> <br> Типизированные массивы не имеют некоторых методов, которые имеют традиционные массивы, такие как <code>.pop()</code> или <code>.push()</code> . В типизированных массивах также отсутствует <code>Array.isArray()</code> который проверяет, что-то есть массив. Хотя это проще, это может быть преимуществом для менее сложных JavaScript-движков для их реализации.
</section>
## Instructions
<section id="instructions"> Сначала создайте <code>buffer</code> размером 64 байта. Затем создайте массив с массивом <code>Int32Array</code> с видом <code>i32View</code> . </section>
<section id='instructions'>
Сначала создайте <code>buffer</code> размером 64 байта. Затем создайте массив с массивом <code>Int32Array</code> с видом <code>i32View</code> .
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Ваш <code>buffer</code> должен быть размером 64 байта.
testString: 'assert(buffer.byteLength === 64, "Your <code>buffer</code> should be 64 bytes large.");'
- text: Ваш вид <code>i32View</code> вашего буфера должен быть 64 байта.
testString: 'assert(i32View.byteLength === 64, "Your <code>i32View</code> view of your buffer should be 64 bytes large.");'
- text: Ваш вид <code>i32View</code> вашего буфера должен составлять 16 элементов.
testString: 'assert(i32View.length === 16, "Your <code>i32View</code> view of your buffer should be 16 elements long.");'
- text: Your <code>buffer</code> should be 64 bytes large.
testString: assert(buffer.byteLength === 64);
- text: Your <code>i32View</code> view of your buffer should be 64 bytes large.
testString: assert(i32View.byteLength === 64);
- text: Your <code>i32View</code> view of your buffer should be 16 elements long.
testString: assert(i32View.length === 16);
```
@@ -41,14 +45,14 @@ var i32View;
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
var buffer = new ArrayBuffer(64);
var i32View = new Int32Array(buffer);
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d8255367417b2b2512c72
title: Use .has and .size on an ES6 Set
challengeType: 1
videoUrl: ''
forumTopicId: 301717
localeTitle: Используйте .has и .size в наборе ES6.
---
## Description
<section id="description"> Давайте посмотрим на методы .has и .size, доступные на объекте Set ES6. Сначала создайте набор ES6 <code>var set = new Set([1,2,3]);</code> Метод .has проверяет, содержится ли это значение в наборе. <code>var hasTwo = set.has(2);</code> Метод .size возвращает целое число, представляющее размер Set <code>var howBig = set.size;</code> </section>
<section id='description'>
Давайте посмотрим на методы .has и .size, доступные на объекте Set ES6. Сначала создайте набор ES6 <code>var set = new Set([1,2,3]);</code> Метод .has проверяет, содержится ли это значение в наборе. <code>var hasTwo = set.has(2);</code> Метод .size возвращает целое число, представляющее размер Set <code>var howBig = set.size;</code>
</section>
## Instructions
<section id="instructions"> В этом упражнении мы передадим массив и значение функции checkSet (). Ваша функция должна создать набор ES6 из аргумента массива. Найдите, содержит ли набор аргумент значения. Найдите размер набора. И верните эти два значения в массив. </section>
<section id='instructions'>
В этом упражнении мы передадим массив и значение функции checkSet (). Ваша функция должна создать набор ES6 из аргумента массива. Найдите, содержит ли набор аргумент значения. Найдите размер набора. И верните эти два значения в массив.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>checkSet([4, 5, 6], 3)</code> должен возвращать [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 ]");'
- text: <code>checkSet([4, 5, 6], 3)</code> should return [ false, 3 ]
testString: assert((function(){var test = checkSet([4,5,6], 3); return DeepEqual(test, [ false, 3 ]);})());
```
@@ -44,14 +48,20 @@ checkSet([ 1, 2, 3], 2); // Should return [ true, 3 ]
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function checkSet(arrToBeSet, checkValue){
var set = new Set(arrToBeSet);
var result = [
set.has(checkValue),
set.size
];
return result;
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8258367417b2b2512c7f
title: Use Breadth First Search in a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301718
localeTitle: Использовать пятый поиск в двоичном дереве поиска
---
## Description
<section id="description"> Здесь мы представим другой метод обхода дерева: поиск по ширине. В отличие от методов поиска по глубине из последней задачи, поиск по ширине исследует все узлы на заданном уровне внутри дерева, а затем переходит на следующий уровень. Как правило, очереди используются в качестве вспомогательных структур данных при разработке алгоритмов поиска по ширине. В этом методе мы начинаем с добавления корневого узла в очередь. Затем мы начинаем цикл, в котором мы деактивируем первый элемент в очереди, добавим его в новый массив и затем проверим оба его дочерних поддерева. Если его дочерние элементы не равны нулю, все они помещаются в очередь. Этот процесс продолжается до тех пор, пока очередь не будет пустой. Инструкции. Давайте создадим метод поиска ширины в нашем дереве, называемый <code>levelOrder</code> . Этот метод должен возвращать массив, содержащий значения всех узлов дерева, исследованных в широком смысле. Обязательно верните значения в массиве, а не сами узлы. Уровень должен пересекаться слева направо. Далее, давайте напишем аналогичный метод <code>reverseLevelOrder</code> который выполняет тот же поиск, но в обратном направлении (справа налево) на каждом уровне. </section>
<section id='description'>
Здесь мы представим другой метод обхода дерева: поиск по ширине. В отличие от методов поиска по глубине из последней задачи, поиск по ширине исследует все узлы на заданном уровне внутри дерева, а затем переходит на следующий уровень. Как правило, очереди используются в качестве вспомогательных структур данных при разработке алгоритмов поиска по ширине. В этом методе мы начинаем с добавления корневого узла в очередь. Затем мы начинаем цикл, в котором мы деактивируем первый элемент в очереди, добавим его в новый массив и затем проверим оба его дочерних поддерева. Если его дочерние элементы не равны нулю, все они помещаются в очередь. Этот процесс продолжается до тех пор, пока очередь не будет пустой. Инструкции. Давайте создадим метод поиска ширины в нашем дереве, называемый <code>levelOrder</code> . Этот метод должен возвращать массив, содержащий значения всех узлов дерева, исследованных в широком смысле. Обязательно верните значения в массиве, а не сами узлы. Уровень должен пересекаться слева направо. Далее, давайте напишем аналогичный метод <code>reverseLevelOrder</code> который выполняет тот же поиск, но в обратном направлении (справа налево) на каждом уровне.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Let's create a breadth-first search method in our tree called <code>levelOrder</code>. This method should return an array containing the values of all the tree nodes, explored in a breadth-first manner. Be sure to return the values in the array, not the nodes themselves. A level should be traversed from left to right. Next, let's write a similar method called <code>reverseLevelOrder</code> which performs the same search but in the reverse direction (right to left) at each level.
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Использовать пятый поиск в двоичном
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: ''
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: ''
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: ''
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: ''
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: ''
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: ''
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.");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>levelOrder</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.levelOrder == 'function')})());
- text: The binary search tree has a method called <code>reverseLevelOrder</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.reverseLevelOrder == 'function')})());
- text: The <code>levelOrder</code> method returns an array of the tree node values explored in level order.
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'); })());
- text: The <code>reverseLevelOrder</code> method returns an array of the tree node values explored in reverse level order.
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'); })());
- text: The <code>levelOrder</code> method returns <code>null</code> for an empty tree.
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); })());
- text: The <code>reverseLevelOrder</code> method returns <code>null</code> for an empty tree.
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); })());
```
@@ -43,28 +46,57 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
}
};
```
</div>
@@ -77,4 +109,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,15 +2,19 @@
id: 587d8257367417b2b2512c7e
title: Use Depth First Search in a Binary Search Tree
challengeType: 1
videoUrl: ''
forumTopicId: 301719
localeTitle: Использовать глубину первого поиска в двоичном дереве поиска
---
## Description
<section id="description"> Мы знаем, как искать двоичное дерево поиска для определенного значения. Но что, если мы просто хотим исследовать все дерево? Или что, если у нас нет упорядоченного дерева, и нам нужно просто искать значение? Здесь мы представим некоторые методы обхода дерева, которые можно использовать для изучения структур древовидных данных. Сначала - поиск по глубине. При поиске по глубине, заданное поддерево рассматривается как можно глубже, прежде чем поиск продолжит переход к другому поддереву. Это можно сделать тремя способами: In-order: Начать поиск на самом левом узле и завершить на самом правом узле. Предварительный порядок: исследуйте все корни перед листьями. Post-order: Исследуйте все листья перед корнями. Как вы можете догадаться, вы можете выбрать различные методы поиска в зависимости от того, какие данные хранят ваше дерево и что вы ищете. Для двоичного дерева поиска обход ордера возвращает узлы в отсортированном порядке. Инструкции: Здесь мы создадим эти три метода поиска в нашем двоичном дереве поиска. Поиск по глубине - это неотъемлемая рекурсивная операция, которая продолжает исследовать дальнейшие поддеревья, пока присутствуют дочерние узлы. Как только вы поймете эту базовую концепцию, вы можете просто изменить порядок, в котором вы исследуете узлы и поддеревья, чтобы произвести любой из трех поисков выше. Например, в post-order search мы хотели бы перечислить весь путь до листового узла, прежде чем мы начнем возвращать любой из самих узлов, тогда как в предварительном поиске мы хотели бы сначала вернуть узлы, а затем продолжить рекурсию вниз по дереву. Определение <code>inorder</code> , <code>preorder</code> , и <code>postorder</code> метода на нашем дереве. Каждый из этих методов должен возвращать массив элементов, которые представляют обход дерева. Обязательно верните целые значения в каждом узле массива, а не сами узлы. Наконец, возвращаем значение <code>null</code> если дерево пусто. </section>
<section id='description'>
Мы знаем, как искать двоичное дерево поиска для определенного значения. Но что, если мы просто хотим исследовать все дерево? Или что, если у нас нет упорядоченного дерева, и нам нужно просто искать значение? Здесь мы представим некоторые методы обхода дерева, которые можно использовать для изучения структур древовидных данных. Сначала - поиск по глубине. При поиске по глубине, заданное поддерево рассматривается как можно глубже, прежде чем поиск продолжит переход к другому поддереву. Это можно сделать тремя способами: In-order: Начать поиск на самом левом узле и завершить на самом правом узле. Предварительный порядок: исследуйте все корни перед листьями. Post-order: Исследуйте все листья перед корнями. Как вы можете догадаться, вы можете выбрать различные методы поиска в зависимости от того, какие данные хранят ваше дерево и что вы ищете. Для двоичного дерева поиска обход ордера возвращает узлы в отсортированном порядке. Инструкции: Здесь мы создадим эти три метода поиска в нашем двоичном дереве поиска. Поиск по глубине - это неотъемлемая рекурсивная операция, которая продолжает исследовать дальнейшие поддеревья, пока присутствуют дочерние узлы. Как только вы поймете эту базовую концепцию, вы можете просто изменить порядок, в котором вы исследуете узлы и поддеревья, чтобы произвести любой из трех поисков выше. Например, в post-order search мы хотели бы перечислить весь путь до листового узла, прежде чем мы начнем возвращать любой из самих узлов, тогда как в предварительном поиске мы хотели бы сначала вернуть узлы, а затем продолжить рекурсию вниз по дереву. Определение <code>inorder</code> , <code>preorder</code> , и <code>postorder</code> метода на нашем дереве. Каждый из этих методов должен возвращать массив элементов, которые представляют обход дерева. Обязательно верните целые значения в каждом узле массива, а не сами узлы. Наконец, возвращаем значение <code>null</code> если дерево пусто.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Here we will create these three search methods on our binary search tree. Depth-first search is an inherently recursive operation which continues to explore further subtrees so long as child nodes are present. Once you understand this basic concept, you can simply rearrange the order in which you explore the nodes and subtrees to produce any of the three searches above. For example, in post-order search we would want to recurse all the way to a leaf node before we begin to return any of the nodes themselves, whereas in pre-order search we would want to return the nodes first, and then continue recursing down the tree.
Define <code>inorder</code>, <code>preorder</code>, and <code>postorder</code> methods on our tree. Each of these methods should return an array of items which represent the tree traversal. Be sure to return the integer values at each node in the array, not the nodes themselves. Finally, return <code>null</code> if the tree is empty.
</section>
## Tests
@@ -18,26 +22,26 @@ localeTitle: Использовать глубину первого поиска
```yml
tests:
- text: Существует структура данных <code>BinarySearchTree</code> .
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: 'Двоичное дерево поиска имеет метод, называемый <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: 'Двоичное дерево поиска имеет метод, называемый <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: 'Двоичное дерево поиска имеет метод, называемый <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: 'Метод <code>inorder</code> возвращает массив значений узла, которые являются результатом обхода порядка.'
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: 'Метод <code>preorder</code> возвращает массив значений узлов, которые являются результатом обхода предзаказов.'
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: 'Метод <code>postorder</code> возвращает массив значений узлов, которые являются результатом обхода порядка после расписания.'
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: Метод <code>inorder</code> возвращает <code>null</code> для пустого дерева.
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: Метод <code>preorder</code> возвращает <code>null</code> для пустого дерева.
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: Метод <code>postorder</code> возвращает значение <code>null</code> для пустого дерева.
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.");'
- text: The <code>BinarySearchTree</code> data structure exists.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
- text: The binary search tree has a method called <code>inorder</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.inorder == 'function')})());
- text: The binary search tree has a method called <code>preorder</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.preorder == 'function')})());
- text: The binary search tree has a method called <code>postorder</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.postorder == 'function')})());
- text: The <code>inorder</code> method returns an array of the node values that result from an inorder traversal.
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'); })());
- text: The <code>preorder</code> method returns an array of the node values that result from a preorder traversal.
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'); })());
- text: The <code>postorder</code> method returns an array of the node values that result from a postorder traversal.
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'); })());
- text: The <code>inorder</code> method returns <code>null</code> for an empty tree.
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); })());
- text: The <code>preorder</code> method returns <code>null</code> for an empty tree.
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); })());
- text: The <code>postorder</code> method returns <code>null</code> for an empty tree.
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); })());
```
@@ -49,28 +53,57 @@ tests:
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
BinarySearchTree.prototype = {
add: function(value) {
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left);
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
}
return searchTree(node);
}
}
};
```
</div>
@@ -81,6 +114,45 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
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.result = [];
this.inorder = function(node) {
if (!node) node = this.root;
if (!node) return null;
if (node.left) this.inorder(node.left);
this.result.push(node.value);
if (node.right) this.inorder(node.right);
return this.result;
};
this.preorder = function(node) {
if (!node) node = this.root;
if (!node) return null;
this.result.push(node.value);
if (node.left) this.preorder(node.left);
if (node.right) this.preorder(node.right);
return this.result;
};
this.postorder = function(node) {
if (!node) node = this.root;
if (!node) return null;
if (node.left) this.postorder(node.left);
if (node.right) this.postorder(node.right);
this.result.push(node.value);
return this.result;
};
}
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d8255367417b2b2512c73
title: Use Spread and Notes for ES5 Set() Integration
challengeType: 1
videoUrl: ''
forumTopicId: 301720
localeTitle: Использование Spread и Notes для интеграции ES5 Set ()
---
## Description
<section id="description"> Вы помните оператор распространения ES6 <code>...</code> ? <code>...</code> может принимать истребимые объекты в ES6 и превращать их в массивы. Давайте создадим Set и проверим функцию спреда. <blockquote> var set = new Set ([1,2,3]); <br> var setToArr = [... set] <br> console.log (setToArr) // возвращает [1, 2, 3] </blockquote></section>
<section id='description'>
Вы помните оператор распространения ES6 <code>...</code> ? <code>...</code> может принимать истребимые объекты в ES6 и превращать их в массивы. Давайте создадим Set и проверим функцию спреда. <blockquote> var set = new Set ([1,2,3]); <br> var setToArr = [... set] <br> console.log (setToArr) // возвращает [1, 2, 3] </blockquote>
</section>
## Instructions
<section id="instructions"> В этом упражнении мы передадим заданный объект функции <code>checkSet</code> . Он должен возвращать массив, содержащий значения Set. Теперь вы успешно научились использовать объект ES6 <code>Set()</code> , хорошую работу! </section>
<section id='instructions'>
В этом упражнении мы передадим заданный объект функции <code>checkSet</code> . Он должен возвращать массив, содержащий значения Set. Теперь вы успешно научились использовать объект ES6 <code>Set()</code> , хорошую работу!
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Ваш набор был возвращен правильно!
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!");'
- text: Your Set was returned correctly!
testString: assert((function(){var test = checkSet(new Set([1,2,3,4,5,6,7])); return DeepEqual(test, [ 1, 2, 3, 4, 5, 6, 7 ]);})());
```
@@ -40,14 +44,14 @@ function checkSet(set){
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function checkSet(set){
return [...set];}
```
</section>

View File

@@ -2,25 +2,29 @@
id: 587d8251367417b2b2512c61
title: Work with Nodes in a Linked List
challengeType: 1
videoUrl: ''
forumTopicId: 301721
localeTitle: Работа с узлами в связанном списке
---
## Description
<section id="description"> Другой общей структурой данных, с которой вы столкнетесь в информатике, является <dfn>связанный список</dfn> . Связанный список представляет собой линейный набор элементов данных, называемый «узлами», каждый из которых указывает на следующий. Каждый <dfn>узел</dfn> в связанном списке содержит две ключевые части информации: сам <code>element</code> и ссылку на следующий <code>node</code> . Представьте, что вы находитесь в линии конги. У вас есть руки на следующем человеке в очереди, и человек, стоящий за вами, держит вас в руках. Вы можете видеть человека прямо перед собой, но они блокируют взгляд других людей в очереди. Узел точно так же, как человек в линии конги: они знают, кто они, и они могут видеть только следующего человека в очереди, но они не знают других людей впереди или позади них. </section>
<section id='description'>
Другой общей структурой данных, с которой вы столкнетесь в информатике, является <dfn>связанный список</dfn> . Связанный список представляет собой линейный набор элементов данных, называемый «узлами», каждый из которых указывает на следующий. Каждый <dfn>узел</dfn> в связанном списке содержит две ключевые части информации: сам <code>element</code> и ссылку на следующий <code>node</code> . Представьте, что вы находитесь в линии конги. У вас есть руки на следующем человеке в очереди, и человек, стоящий за вами, держит вас в руках. Вы можете видеть человека прямо перед собой, но они блокируют взгляд других людей в очереди. Узел точно так же, как человек в линии конги: они знают, кто они, и они могут видеть только следующего человека в очереди, но они не знают других людей впереди или позади них.
</section>
## Instructions
<section id="instructions"> В нашем редакторе кода мы создали два узла, <code>Kitten</code> и <code>Puppy</code> , и мы связали узел <code>Kitten</code> вручную с узлом <code>Puppy</code> . Создайте узел <code>Cat</code> и <code>Dog</code> и вручную добавьте их в строку. </section>
<section id='instructions'>
В нашем редакторе кода мы создали два узла, <code>Kitten</code> и <code>Puppy</code> , и мы связали узел <code>Kitten</code> вручную с узлом <code>Puppy</code> . Создайте узел <code>Cat</code> и <code>Dog</code> и вручную добавьте их в строку.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: У вашего узла <code>Puppy</code> должна быть ссылка на узел <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: Ваш узел <code>Cat</code> должен иметь ссылку на узел <code>Dog</code> .
testString: 'assert(Cat.next.element === "Dog", "Your <code>Cat</code> node should have a reference to a <code>Dog</code> node.");'
- text: Your <code>Puppy</code> node should have a reference to a <code>Cat</code> node.
testString: assert(Puppy.next.element === "Cat");
- text: Your <code>Cat</code> node should have a reference to a <code>Dog</code> node.
testString: assert(Cat.next.element === "Dog");
```
@@ -32,12 +36,12 @@ tests:
<div id='js-seed'>
```js
var Node = function(element){
this.element = element;
this.next = null;
var Node = function(element) {
this.element = element;
this.next = null;
};
var Kitten = new Node("Kitten");
var Puppy = new Node("Puppy");
var Kitten = new Node('Kitten');
var Puppy = new Node('Puppy');
Kitten.next = Puppy;
// only add code below this line
@@ -49,8 +53,6 @@ console.log(Kitten.next);
</div>
</section>
## Solution
@@ -59,4 +61,5 @@ console.log(Kitten.next);
```js
// solution required
```
</section>