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,49 +2,53 @@
id: a3f503de51cf954ede28891d
title: Find the Symmetric Difference
challengeType: 5
videoUrl: ''
forumTopicId: 301611
localeTitle: Найти симметричную разницу
---
## Description
<section id="description"> Создайте функцию, которая принимает два или более массива и возвращает массив <dfn>симметричной разности</dfn> ( <code>△</code> или <code>⊕</code> ) предоставленных массивов. Для двух множеств (например, для множества <code>A = {1, 2, 3}</code> и множества <code>B = {2, 3, 4}</code> ) математический термин «симметричная разность» двух множеств представляет собой включающее все элементы исходных множеств, не принадлежащие одновременно обоим исходным множествам ( <code>A △ B = C = {1, 4}</code> ). Для каждой дополнительной симметричной разности, которую вы принимаете (допустим, множество <code>D = {2, 3}</code> ), вы должны получить набор с элементами, которые находятся в любом из двух наборов, но не в обоих одновременно ( <code>C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}</code> ). Результирующий массив должен содержать только уникальные значения ( <em>без дубликатов</em> ). Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте парное программирование. Напишите свой собственный код. </section>
<section id='description'>
Создайте функцию, которая принимает два или более массива и возвращает массив <dfn>симметричной разности</dfn> ( <code>△</code> или <code>⊕</code> ) предоставленных массивов. Для двух множеств (например, для множества <code>A = {1, 2, 3}</code> и множества <code>B = {2, 3, 4}</code> ) математический термин «симметричная разность» двух множеств представляет собой включающее все элементы исходных множеств, не принадлежащие одновременно обоим исходным множествам ( <code>A △ B = C = {1, 4}</code> ). Для каждой дополнительной симметричной разности, которую вы принимаете (допустим, множество <code>D = {2, 3}</code> ), вы должны получить набор с элементами, которые находятся в любом из двух наборов, но не в обоих одновременно ( <code>C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}</code> ). Результирующий массив должен содержать только уникальные значения ( <em>без дубликатов</em> ). Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте парное программирование. Напишите свой собственный код.
</section>
## Instructions
undefined
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4])</code> должнен возвращать <code>[3, 4, 5]</code>.'
testString: 'assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4]), [3, 4, 5], "<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.");'
- text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен содержать только три элемента.'
testString: 'assert.equal(sym([1, 2, 3], [5, 2, 1, 4]).length, 3, "<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should contain only three elements.");'
- text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен возвращать <code>[3, 4, 5]</code> .'
testString: 'assert.sameMembers(sym([1, 2, 3, 3], [5, 2, 1, 4]), [3, 4, 5], "<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.");'
- text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен содержать только три элемента.'
testString: 'assert.equal(sym([1, 2, 3, 3], [5, 2, 1, 4]).length, 3, "<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should contain only three elements.");'
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> должен возвращать <code>[3, 4, 5]</code> .'
testString: 'assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5], "<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should return <code>[3, 4, 5]</code>.");'
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> должен содержать только три элемента.'
testString: 'assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3, "<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should contain only three elements.");'
- text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> должен возвращать <code>[1, 4, 5]</code>'
testString: 'assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5], "<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should return <code>[1, 4, 5]</code>");'
- text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> должен содержать только три элемента.'
testString: 'assert.equal(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]).length, 3, "<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should contain only three elements.");'
- text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> должен возвращать <code>[1, 4, 5]</code>'
testString: 'assert.sameMembers(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]), [1, 4, 5], "<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should return <code>[1, 4, 5]</code>.");'
- text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> должен содержать только три элемента.'
testString: 'assert.equal(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]).length, 3, "<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should contain only three elements.");'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> должен возвращать <code>[2, 3, 4, 6, 7]</code> .'
testString: 'assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]), [2, 3, 4, 6, 7], "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should return <code>[2, 3, 4, 6, 7]</code>.");'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> должен содержать только пять элементов.'
testString: 'assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]).length, 5, "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should contain only five elements.");'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> должен возвращать <code>[1, 2, 4, 5, 6, 7, 8, 9]</code> .'
testString: 'assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]), [1, 2, 4, 5, 6, 7, 8, 9], "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should return <code>[1, 2, 4, 5, 6, 7, 8, 9]</code>.");'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> должен содержать только восемь элементов.'
testString: 'assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]).length, 8, "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should contain only eight elements.");'
- text: <code>sym([1, 2, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.
testString: assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4]), [3, 4, 5]);
- text: <code>sym([1, 2, 3], [5, 2, 1, 4])</code> should contain only three elements.
testString: assert.equal(sym([1, 2, 3], [5, 2, 1, 4]).length, 3);
- text: <code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.
testString: assert.sameMembers(sym([1, 2, 3, 3], [5, 2, 1, 4]), [3, 4, 5]);
- text: <code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should contain only three elements.
testString: assert.equal(sym([1, 2, 3, 3], [5, 2, 1, 4]).length, 3);
- text: <code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should return <code>[3, 4, 5]</code>.
testString: assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5]);
- text: <code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should contain only three elements.
testString: assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3);
- text: <code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should return <code>[1, 4, 5]</code>
testString: assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5]);
- text: <code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should contain only three elements.
testString: assert.equal(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]).length, 3);
- text: <code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should return <code>[1, 4, 5]</code>.
testString: assert.sameMembers(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]), [1, 4, 5]);
- text: <code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should contain only three elements.
testString: assert.equal(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]).length, 3);
- text: <code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should return <code>[2, 3, 4, 6, 7]</code>.
testString: assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]), [2, 3, 4, 6, 7]);
- text: <code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should contain only five elements.
testString: assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]).length, 5);
- text: <code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should return <code>[1, 2, 4, 5, 6, 7, 8, 9]</code>.
testString: assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]), [1, 2, 4, 5, 6, 7, 8, 9]);
- text: <code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should contain only eight elements.
testString: assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]).length, 8);
```
@@ -66,14 +70,22 @@ sym([1, 2, 3], [5, 2, 1, 4]);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function sym() {
var arrays = [].slice.call(arguments);
return arrays.reduce(function (symDiff, arr) {
return symDiff.concat(arr).filter(function (val, idx, theArr) {
return theArr.indexOf(val) === idx
&& (symDiff.indexOf(val) === -1 || arr.indexOf(val) === -1);
});
});
}
sym([1, 2, 3], [5, 2, 1, 4]);
```
</section>

View File

@@ -2,31 +2,34 @@
id: 8d5123c8c441eddfaeb5bdef
title: Implement Bubble Sort
challengeType: 1
videoUrl: ''
forumTopicId: 301612
localeTitle: Реализация Сортировки пузырьком
---
## Описание
## Description
<section id='description'>
Это первая из нескольких задач алгоритмов сортировки. Учитывая массив несортированных элементов, мы хотим иметь возможность возвращать отсортированный массив. Мы рассмотрим несколько различных методов для этого и изучим некоторые компромиссы между этими различными подходами. Хотя большинство современных языков имеют встроенные методы сортировки для таких операций, все же важно понять некоторые из общих базовых подходов и узнать, как они могут быть реализованы. Здесь мы увидим вид пузыря. Метод сортировки пузырьков начинается с начала несортированного массива и «выравнивает» несортированные значения до конца, итерации по массиву до тех пор, пока он не будет полностью отсортирован. Он делает это, сравнивая смежные элементы и заменяя их, если они не соответствуют порядку. Метод продолжает цикл через массив до тех пор, пока не произойдет своп, после чего массив будет отсортирован. Этот метод требует нескольких итераций через массив, а для средних и худших случаев имеет квадратичную временную сложность. Хотя это просто, в большинстве случаев это обычно нецелесообразно. Инструкции: Напишите функцию bubbleSort, которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. Замечания:
Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging array, чтобы увидеть ваш алгоритм сортировки в действии!
</section>
## Instructions
undefined
<section id='instructions'>
## Тесты
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert(typeof bubbleSort == "function", "<code>bubbleSort</code> это функция.");'
- text: ''
testString: 'assert(isSorted(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), "<code>bubbleSort</code> возвращает отсортированный массив (от наименьшего к наибольшему).");'
- text: ''
testString: 'assert.sameMembers(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], "<code>bubbleSort</code> rвыдает массив, который не изменяется, за исключением порядка.");'
- text: ''
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, "<code>bubbleSort</code> не следует использовать встроенный <code>.sort()</code> method.");'
- text: <code>bubbleSort</code> is a function.
testString: assert(typeof bubbleSort == 'function');
- text: <code>bubbleSort</code> returns a sorted array (least to greatest).
testString: assert(isSorted(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])));
- text: <code>bubbleSort</code> returns an array that is unchanged except for order.
testString: assert.sameMembers(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);
- text: <code>bubbleSort</code> should not use the built-in <code>.sort()</code> method.
testString: assert.strictEqual(code.search(/\.sort\(/), -1);
```
@@ -39,25 +42,26 @@ tests:
```js
function bubbleSort(array) {
// изменить код ниже этой строки
// изменить код над этой строкой
// change code below this line
return array;
// change code above this line
}
// массив для задания:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
</div>
### После задания
### After Tests
<div id='js-teardown'>
```js
console.info('после задания');
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
};
```
</div>
@@ -68,6 +72,23 @@ console.info('после задания');
<section id='solution'>
```js
// требуется решение
function bubbleSort(array) {
for (let i = 0; i < array.length; i++) {
let swapped = false;
for (let j = 1; j < array.length; j++) {
if (array[j - 1] > array[j]) {
let temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
swapped = true;
}
}
if (swapped === false) {
break;
}
}
return array;
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8259367417b2b2512c86
title: Implement Insertion Sort
challengeType: 1
videoUrl: ''
forumTopicId: 301613
localeTitle: Внедрить сортировку вставками
---
## Description
<section id="description"> Следующий метод сортировки, на который мы будем смотреть - это сортировка вставками. Этот метод работает, создавая сортированный массив в начале списка. Он создает сортированный массив с первым элементом. Затем он проверяет следующий элемент и свопирует его обратно в отсортированный массив до тех пор, пока он не будет отсортирован. Он продолжает итерирование по списку и сворачивание новых элементов назад в отсортированную часть до тех пор, пока она не достигнет конца. Этот алгоритм имеет квадратичную временную сложность в среднем и худшем случае. <strong>Инструкции:</strong> Напишите функцию <code>insertionSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии! </section>
<section id='description'>
Следующий метод сортировки, на который мы будем смотреть - это сортировка вставками. Этот метод работает, создавая сортированный массив в начале списка. Он создает сортированный массив с первым элементом. Затем он проверяет следующий элемент и свопирует его обратно в отсортированный массив до тех пор, пока он не будет отсортирован. Он продолжает итерирование по списку и сворачивание новых элементов назад в отсортированную часть до тех пор, пока она не достигнет конца. Этот алгоритм имеет квадратичную временную сложность в среднем и худшем случае. <strong>Инструкции:</strong> Напишите функцию <code>insertionSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Внедрить сортировку вставками
```yml
tests:
- text: <code>insertionSort</code> - это функция.
testString: 'assert(typeof insertionSort == "function", "<code>insertionSort</code> это функция.");'
- text: <code>insertionSort</code> возвращает отсортированный массив (от наименьшего к наибольшему).
testString: 'assert(isSorted(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), "<code>insertionSort</code> возвращает отсортированный массив (от наименьшего к наибольшему).");'
- text: '<code>insertionSort</code> возвращает массив, который не изменяется, кроме порядка.'
testString: 'assert.sameMembers(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], "<code>insertionSort</code> возвращает массив, который не изменяется, за исключением порядка.");'
- text: <code>insertionSort</code> не должен использовать встроенный метод <code>.sort()</code> .
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, "<code>insertionSort</code> не следует использовать встроенный <code>.sort()</code> method.");'
- text: <code>insertionSort</code> is a function.
testString: assert(typeof insertionSort == 'function');
- text: <code>insertionSort</code> returns a sorted array (least to greatest).
testString: assert(isSorted(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])));
- text: <code>insertionSort</code> returns an array that is unchanged except for order.
testString: assert.sameMembers(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);
- text: <code>insertionSort</code> should not use the built-in <code>.sort()</code> method.
testString: assert.strictEqual(code.search(/\.sort\(/), -1);
```
@@ -38,25 +41,26 @@ tests:
```js
function insertionSort(array) {
// изменить код ниже этой строки
// изменить код над этой строкой
// change code below this line
return array;
// change code above this line
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
};
```
</div>
@@ -67,6 +71,18 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function insertionSort (array) {
for (let currentIndex = 0; currentIndex < array.length; currentIndex++) {
let current = array[currentIndex];
let j = currentIndex - 1;
while (j > -1 && array[j] > current) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = current;
}
return array;
}
```
</section>

View File

@@ -2,20 +2,23 @@
id: 587d825c367417b2b2512c8f
title: Implement Merge Sort
challengeType: 1
videoUrl: ''
forumTopicId: 301614
localeTitle: Реализация Merge Sort
---
## Description
<section id="description"> Другим промежуточным алгоритмом сортировки, который очень распространен, является сортировка слияния. Подобно быстрой сортировке, сортировка слиянием также использует метод рекурсивного анализа для разделения массива. Сортировка использует тот факт, что легче сортировать два массива меньшего размера, нежели один большего. <br>В качестве входных данных начнем с неотсортированного массива. Как мы можем перейти к двум отсортированным массивам? Мы можем рекурсивно разделить исходный ввод на два, пока не достигнем базового случая массива с одним элементом. Массив из одного элемента естественно сортируется, поэтому мы можем начать комбинировать. Эта комбинация будет раскручивать рекурсивные вызовы, разделяющие исходный массив, в конечном итоге создавая окончательный отсортированный массив всех элементов.
<section id='description'>
Другим промежуточным алгоритмом сортировки, который очень распространен, является сортировка слияния. Подобно быстрой сортировке, сортировка слиянием также использует метод рекурсивного анализа для разделения массива. Сортировка использует тот факт, что легче сортировать два массива меньшего размера, нежели один большего. <br>В качестве входных данных начнем с неотсортированного массива. Как мы можем перейти к двум отсортированным массивам? Мы можем рекурсивно разделить исходный ввод на два, пока не достигнем базового случая массива с одним элементом. Массив из одного элемента естественно сортируется, поэтому мы можем начать комбинировать. Эта комбинация будет раскручивать рекурсивные вызовы, разделяющие исходный массив, в конечном итоге создавая окончательный отсортированный массив всех элементов.
Затем выполняются шаги сортировки слияния:
<br><strong>1)</strong> Рекурсивно разделить входной массив пополам, пока не будет создан массив только с одним элементом. <br><strong>2)</strong> Объединтить каждый отсортированный подмассив вместе, чтобы получить окончательный отсортированный массив.
Сортировка Merge - это эффективный метод сортировки со алгоритмически-оптимальной сложностью <i>O (nlog (n))</i> . Этот алгоритм популярен, потому что он прост в реализации. <br>Это будет последний эффективный алгоритм сортировки, который мы рассмотрим здесь. Однако позже в разделе о структурах древовидных данных мы опишем сортировку кучи (HeapSort), еще один эффективный метод сортировки, который требует реализацию бинарной кучи.
<strong>Инструкции:</strong> Напишите функцию <code>mergeSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. Хороший способ реализовать это - написать одну функцию, например <code>merge</code> , которая отвечает за объединение двух отсортированных массивов и другую функцию, например, <code>mergeSort</code> , которая отвечает за слияние. Удачи!
<strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии! </section>
<strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -23,14 +26,14 @@ localeTitle: Реализация Merge Sort
```yml
tests:
- text: <code>mergeSort</code> - это функция.
testString: 'assert(typeof mergeSort == "function", "<code>mergeSort</code> is a function.");'
- text: <code>mergeSort</code> возвращает отсортированный массив (от наименьшего к наибольшему).
testString: 'assert(isSorted(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), "<code>mergeSort</code> returns a sorted array (least to greatest).");'
- text: '<code>mergeSort</code> возвращает массив, который не изменяется, кроме порядка.'
testString: 'assert.sameMembers(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], "<code>mergeSort</code> returns an array that is unchanged except for order.");'
- text: <code>mergeSort</code> не должен использовать встроенный метод <code>.sort()</code> .
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, "<code>mergeSort</code> should not use the built-in <code>.sort()</code> method.");'
- text: <code>mergeSort</code> is a function.
testString: assert(typeof mergeSort == 'function');
- text: <code>mergeSort</code> returns a sorted array (least to greatest).
testString: assert(isSorted(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])));
- text: <code>mergeSort</code> returns an array that is unchanged except for order.
testString: assert.sameMembers(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);
- text: <code>mergeSort</code> should not use the built-in <code>.sort()</code> method.
testString: assert.strictEqual(code.search(/\.sort\(/), -1);
```
@@ -49,19 +52,21 @@ function mergeSort(array) {
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
};
```
</div>
@@ -74,4 +79,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d825a367417b2b2512c89
title: Implement Quick Sort
challengeType: 1
videoUrl: ''
forumTopicId: 301615
localeTitle: Внедрить Quick Sort
---
## Description
<section id="description"> Здесь мы перейдем к промежуточному алгоритму сортировки: быстрая сортировка. Быстрая сортировка - это эффективный, рекурсивный подход к сортировке массива. В этом методе в исходном массиве выбирается значение поворота. Массив затем разбивается на два подмассивов значений меньше и больше, чем значение поворота. Затем мы комбинируем результат рекурсивного вызова алгоритма быстрой сортировки на обоих подмассивах. Это продолжается до тех пор, пока не будет достигнут базовый случай для пустого или одного элемента массива, который мы вернем. Откат рекурсивных вызовов возвращает нам отсортированный массив. Быстрый сортировка - очень эффективный метод сортировки, обеспечивающий производительность <i>O (nlog (n))</i> в среднем. Это также относительно легко реализовать. Эти атрибуты делают его популярным и полезным методом сортировки. <strong>Инструкции:</strong> Напишите функцию <code>quickSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. В то время как выбор значения поворота важен, любой стержень будет делать для наших целей здесь. Для простоты можно использовать первый или последний элемент. <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии! </section>
<section id='description'>
Здесь мы перейдем к промежуточному алгоритму сортировки: быстрая сортировка. Быстрая сортировка - это эффективный, рекурсивный подход к сортировке массива. В этом методе в исходном массиве выбирается значение поворота. Массив затем разбивается на два подмассивов значений меньше и больше, чем значение поворота. Затем мы комбинируем результат рекурсивного вызова алгоритма быстрой сортировки на обоих подмассивах. Это продолжается до тех пор, пока не будет достигнут базовый случай для пустого или одного элемента массива, который мы вернем. Откат рекурсивных вызовов возвращает нам отсортированный массив. Быстрый сортировка - очень эффективный метод сортировки, обеспечивающий производительность <i>O (nlog (n))</i> в среднем. Это также относительно легко реализовать. Эти атрибуты делают его популярным и полезным методом сортировки. <strong>Инструкции:</strong> Напишите функцию <code>quickSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. В то время как выбор значения поворота важен, любой стержень будет делать для наших целей здесь. Для простоты можно использовать первый или последний элемент. <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Внедрить Quick Sort
```yml
tests:
- text: <code>quickSort</code> - это функция.
testString: 'assert(typeof quickSort == "function", "<code>quickSort</code> is a function.");'
- text: <code>quickSort</code> возвращает отсортированный массив (от наименьшего к наибольшему).
testString: 'assert(isSorted(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), "<code>quickSort</code> returns a sorted array (least to greatest).");'
- text: '<code>quickSort</code> возвращает массив, который не изменяется, кроме порядка.'
testString: 'assert.sameMembers(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], "<code>quickSort</code> returns an array that is unchanged except for order.");'
- text: <code>quickSort</code> не должен использовать встроенный метод <code>.sort()</code> .
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, "<code>quickSort</code> should not use the built-in <code>.sort()</code> method.");'
- text: <code>quickSort</code> is a function.
testString: assert(typeof quickSort == 'function');
- text: <code>quickSort</code> returns a sorted array (least to greatest).
testString: assert(isSorted(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])));
- text: <code>quickSort</code> returns an array that is unchanged except for order.
testString: assert.sameMembers(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);
- text: <code>quickSort</code> should not use the built-in <code>.sort()</code> method.
testString: assert.strictEqual(code.search(/\.sort\(/), -1);
```
@@ -51,12 +54,15 @@ function quickSort(array) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
};
```
</div>
@@ -69,4 +75,5 @@ console.info('after the test');
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 587d8259367417b2b2512c85
title: Implement Selection Sort
challengeType: 1
videoUrl: ''
forumTopicId: 301616
localeTitle: Реализация Сортировки выбором
---
## Описание
<section id="description"> Здесь мы будем применять сортировку выбором. Сортировка выбором работает, выбирая минимальное значение в списке и меняя его с первым значением в списке. Затем он начинается со второй позиции, выбирает наименьшее значение в оставшемся списке и свопирует его со вторым элементом. Он продолжает итерирование по списку и свопинг элементов до тех пор, пока он не достигнет конца списка. Теперь список отсортирован. Сортировка выбора имеет квадратичную временную сложность во всех случаях. <strong>Инструкции</strong> : Напишите функцию <code>selectionSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии! </section>
## Description
<section id='description'>
Здесь мы будем применять сортировку выбором. Сортировка выбором работает, выбирая минимальное значение в списке и меняя его с первым значением в списке. Затем он начинается со второй позиции, выбирает наименьшее значение в оставшемся списке и свопирует его со вторым элементом. Он продолжает итерирование по списку и свопинг элементов до тех пор, пока он не достигнет конца списка. Теперь список отсортирован. Сортировка выбора имеет квадратичную временную сложность во всех случаях. <strong>Инструкции</strong> : Напишите функцию <code>selectionSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии!
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Реализация Сортировки выбором
```yml
tests:
- text: <code>selectionSort</code> - это функция.
testString: 'assert(typeof selectionSort == "function", "<code>selectionSort</code> is a function.");'
- text: <code>selectionSort</code> возвращает отсортированный массив (от наименьшего к наибольшему).
testString: 'assert(isSorted(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), "<code>selectionSort</code> returns a sorted array (least to greatest).");'
- text: '<code>selectionSort</code> возвращает массив, который не изменяется, кроме порядка.'
testString: 'assert.sameMembers(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], "<code>selectionSort</code> returns an array that is unchanged except for order.");'
- text: <code>selectionSort</code> не должен использовать встроенный метод <code>.sort()</code> .
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, "<code>selectionSort</code> should not use the built-in <code>.sort()</code> method.");'
- text: <code>selectionSort</code> is a function.
testString: assert(typeof selectionSort == 'function');
- text: <code>selectionSort</code> returns a sorted array (least to greatest).
testString: assert(isSorted(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])));
- text: <code>selectionSort</code> returns an array that is unchanged except for order.
testString: assert.sameMembers(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);
- text: <code>selectionSort</code> should not use the built-in <code>.sort()</code> method.
testString: assert.strictEqual(code.search(/\.sort\(/), -1);
```
@@ -39,24 +42,26 @@ tests:
```js
function selectionSort(array) {
// change code below this line
// change code above this line
return array;
// change code above this line
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
selectionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
};
```
</div>
@@ -67,6 +72,20 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function selectionSort(array) {
for (let i = 0; i < array.length-1; i++) {
let minimumIndex = i;
for (let j = i+1; j < array.length; j++){
if (array[j] < array[minimumIndex]) {
minimumIndex = j;
}
}
let value = array[minimumIndex];
array[minimumIndex] = array[i];
array[i] = value;
}
return array;
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: a56138aff60341a09ed6c480
title: Inventory Update
challengeType: 5
videoUrl: ''
forumTopicId: 16019
localeTitle: Обновление инвентаря
---
## Description
<section id="description"> Сравните и обновите инвентарь, хранящийся в 2D-массиве, против второго 2D-массива новой доставки. Обновите текущие объемы инвентарных количеств (в <code>arr1</code> ). Если элемент не найден, добавьте новый элемент и количество в массив инвентаря. Возвращаемый массив инвентаря должен быть в алфавитном порядке по позиции. Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код. </section>
<section id='description'>
Сравните и обновите инвентарь, хранящийся в 2D-массиве, против второго 2D-массива новой доставки. Обновите текущие объемы инвентарных количеств (в <code>arr1</code> ). Если элемент не найден, добавьте новый элемент и количество в массив инвентаря. Возвращаемый массив инвентаря должен быть в алфавитном порядке по позиции. Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Обновление инвентаря
```yml
tests:
- text: Функция <code>updateInventory</code> должна возвращать массив.
testString: 'assert.isArray(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), "The function <code>updateInventory</code> should return an array.");'
- text: '<code>updateInventory([[21, &quot;Bowling Ball&quot;], [2, &quot;Dirty Sock&quot;], [1, &quot;Hair Pin&quot;], [5, &quot;Microphone&quot;]], [[2, &quot;Hair Pin&quot;], [3, &quot;Half-Eaten Apple&quot;], [67, &quot;Bowling Ball&quot;], [7, &quot;Toothpaste&quot;]])</code> должны возвращать массив длиной 6.'
testString: 'assert.equal(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length, 6, "<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return an array with a length of 6.");'
- text: '<code>updateInventory([[21, &quot;Bowling Ball&quot;], [2, &quot;Dirty Sock&quot;], [1, &quot;Hair Pin&quot;], [5, &quot;Microphone&quot;]], [[2, &quot;Hair Pin&quot;], [3, &quot;Half-Eaten Apple&quot;], [67, &quot;Bowling Ball&quot;], [7, &quot;Toothpaste&quot;]])</code> должны вернуться <code>[[88, &quot;Bowling Ball&quot;], [2, &quot;Dirty Sock&quot;], [3, &quot;Hair Pin&quot;], [3, &quot;Half-Eaten Apple&quot;], [5, &quot;Microphone&quot;], [7, &quot;Toothpaste&quot;]]</code> .'
testString: 'assert.deepEqual(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]], "<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]</code>.");'
- text: '<code>updateInventory([[21, &quot;Bowling Ball&quot;], [2, &quot;Dirty Sock&quot;], [1, &quot;Hair Pin&quot;], [5, &quot;Microphone&quot;]], [])</code> должны возвращать <code>[[21, &quot;Bowling Ball&quot;], [2, &quot;Dirty Sock&quot;], [1, &quot;Hair Pin&quot;], [5, &quot;Microphone&quot;]]</code> .'
testString: 'assert.deepEqual(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], []), [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], "<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])</code> should return <code>[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]</code>.");'
- text: '<code>updateInventory([], [[2, &quot;Hair Pin&quot;], [3, &quot;Half-Eaten Apple&quot;], [67, &quot;Bowling Ball&quot;], [7, &quot;Toothpaste&quot;]])</code> должны вернуться <code>[[67, &quot;Bowling Ball&quot;], [2, &quot;Hair Pin&quot;], [3, &quot;Half-Eaten Apple&quot;], [7, &quot;Toothpaste&quot;]]</code> .'
testString: 'assert.deepEqual(updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]], "<code>updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]</code>.");'
- text: '<code>updateInventory([[0, &quot;Bowling Ball&quot;], [0, &quot;Dirty Sock&quot;], [0, &quot;Hair Pin&quot;], [0, &quot;Microphone&quot;]], [[1, &quot;Hair Pin&quot;], [1, &quot;Half-Eaten Apple&quot;], [1, &quot;Bowling Ball&quot;], [1, &quot;Toothpaste&quot;]])</code> должны возвращать <code>[[1, &quot;Bowling Ball&quot;], [0, &quot;Dirty Sock&quot;], [1, &quot;Hair Pin&quot;], [1, &quot;Half-Eaten Apple&quot;], [0, &quot;Microphone&quot;], [1, &quot;Toothpaste&quot;]]</code> .'
testString: 'assert.deepEqual(updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]), [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]], "<code>updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])</code> should return <code>[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]</code>.");'
- text: The function <code>updateInventory</code> should return an array.
testString: assert.isArray(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]));
- text: <code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return an array with a length of 6.
testString: assert.equal(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length, 6);
- text: <code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]</code>.
testString: assert.deepEqual(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]);
- text: <code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])</code> should return <code>[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]</code>.
testString: assert.deepEqual(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], []), [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]);
- text: <code>updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]</code>.
testString: assert.deepEqual(updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]);
- text: <code>updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])</code> should return <code>[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]</code>.
testString: assert.deepEqual(updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]), [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]);
```
@@ -67,14 +70,50 @@ updateInventory(curInv, newInv);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function updateInventory(arr1, arr2) {
arr2.forEach(function(item) {
createOrUpdate(arr1, item);
});
// All inventory must be accounted for or you're fired!
return arr1;
}
function createOrUpdate(arr1, item) {
var index = -1;
while (++index < arr1.length) {
if (arr1[index][1] === item[1]) {
arr1[index][0] += item[0];
return;
}
if (arr1[index][1] > item[1]) {
break;
}
}
arr1.splice(index, 0, item);
}
// Example inventory lists
var curInv = [
[21, 'Bowling Ball'],
[2, 'Dirty Sock'],
[1, 'Hair Pin'],
[5, 'Microphone']
];
var newInv = [
[2, 'Hair Pin'],
[3, 'Half-Eaten Apple'],
[67, 'Bowling Ball'],
[7, 'Toothpaste']
];
updateInventory(curInv, newInv);
```
</section>

View File

@@ -2,15 +2,18 @@
id: a7bf700cd123b9a54eef01d5
title: No Repeats Please
challengeType: 5
videoUrl: ''
forumTopicId: 16037
localeTitle: Нет повторений Пожалуйста
---
## Description
<section id="description"> Возвращает число полных перестановок предоставленной строки, которые не имеют повторяющихся последовательных букв. Предположим, что все символы в предоставленной строке уникальны. Например, <code>aab</code> должен возвращать 2, поскольку имеет 6 полных перестановок ( <code>aab</code> , <code>aab</code> , <code>aba</code> , <code>aba</code> , <code>baa</code> , <code>baa</code> ), но только 2 из них ( <code>aba</code> и <code>aba</code> ) не имеют одинаковой буквы (в данном случае <code>a</code> ) повторяющееся. Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код. </section>
<section id='description'>
Возвращает число полных перестановок предоставленной строки, которые не имеют повторяющихся последовательных букв. Предположим, что все символы в предоставленной строке уникальны. Например, <code>aab</code> должен возвращать 2, поскольку имеет 6 полных перестановок ( <code>aab</code> , <code>aab</code> , <code>aba</code> , <code>aba</code> , <code>baa</code> , <code>baa</code> ), но только 2 из них ( <code>aba</code> и <code>aba</code> ) не имеют одинаковой буквы (в данном случае <code>a</code> ) повторяющееся. Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,26 +21,26 @@ localeTitle: Нет повторений Пожалуйста
```yml
tests:
- text: <code>permAlone(&quot;aab&quot;)</code> должен возвращать число.
testString: 'assert.isNumber(permAlone("aab"), "<code>permAlone("aab")</code> should return a number.");'
- text: <code>permAlone(&quot;aab&quot;)</code> должен вернуть 2.
testString: 'assert.strictEqual(permAlone("aab"), 2, "<code>permAlone("aab")</code> should return 2.");'
- text: <code>permAlone(&quot;aaa&quot;)</code> должен вернуть 0.
testString: 'assert.strictEqual(permAlone("aaa"), 0, "<code>permAlone("aaa")</code> should return 0.");'
- text: <code>permAlone(&quot;aabb&quot;)</code> должен вернуть 8.
testString: 'assert.strictEqual(permAlone("aabb"), 8, "<code>permAlone("aabb")</code> should return 8.");'
- text: <code>permAlone(&quot;abcdefa&quot;)</code> должен вернуть 3600.
testString: 'assert.strictEqual(permAlone("abcdefa"), 3600, "<code>permAlone("abcdefa")</code> should return 3600.");'
- text: <code>permAlone(&quot;abfdefa&quot;)</code> должен вернуть 2640.
testString: 'assert.strictEqual(permAlone("abfdefa"), 2640, "<code>permAlone("abfdefa")</code> should return 2640.");'
- text: <code>permAlone(&quot;zzzzzzzz&quot;)</code> должен вернуть 0.
testString: 'assert.strictEqual(permAlone("zzzzzzzz"), 0, "<code>permAlone("zzzzzzzz")</code> should return 0.");'
- text: <code>permAlone(&quot;a&quot;)</code> должен возвращать 1.
testString: 'assert.strictEqual(permAlone("a"), 1, "<code>permAlone("a")</code> should return 1.");'
- text: <code>permAlone(&quot;aaab&quot;)</code> должен вернуть 0.
testString: 'assert.strictEqual(permAlone("aaab"), 0, "<code>permAlone("aaab")</code> should return 0.");'
- text: <code>permAlone(&quot;aaabb&quot;)</code> должен вернуть 12.
testString: 'assert.strictEqual(permAlone("aaabb"), 12, "<code>permAlone("aaabb")</code> should return 12.");'
- text: <code>permAlone("aab")</code> should return a number.
testString: assert.isNumber(permAlone('aab'));
- text: <code>permAlone("aab")</code> should return 2.
testString: assert.strictEqual(permAlone('aab'), 2);
- text: <code>permAlone("aaa")</code> should return 0.
testString: assert.strictEqual(permAlone('aaa'), 0);
- text: <code>permAlone("aabb")</code> should return 8.
testString: assert.strictEqual(permAlone('aabb'), 8);
- text: <code>permAlone("abcdefa")</code> should return 3600.
testString: assert.strictEqual(permAlone('abcdefa'), 3600);
- text: <code>permAlone("abfdefa")</code> should return 2640.
testString: assert.strictEqual(permAlone('abfdefa'), 2640);
- text: <code>permAlone("zzzzzzzz")</code> should return 0.
testString: assert.strictEqual(permAlone('zzzzzzzz'), 0);
- text: <code>permAlone("a")</code> should return 1.
testString: assert.strictEqual(permAlone('a'), 1);
- text: <code>permAlone("aaab")</code> should return 0.
testString: assert.strictEqual(permAlone('aaab'), 0);
- text: <code>permAlone("aaabb")</code> should return 12.
testString: assert.strictEqual(permAlone('aaabb'), 12);
```
@@ -59,14 +62,46 @@ permAlone('aab');
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function permAlone(str) {
return permutor(str).filter(function(perm) {
return !perm.match(/(.)\1/g);
}).length;
}
function permutor(str) {
// http://staff.roguecc.edu/JMiller/JavaScript/permute.html
//permArr: Global array which holds the list of permutations
//usedChars: Global utility array which holds a list of "currently-in-use" characters
var permArr = [], usedChars = [];
function permute(input) {
//convert input into a char array (one element for each character)
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
//get and remove character at index "i" from char array
ch = chars.splice(i, 1);
//add removed character to the end of used characters
usedChars.push(ch);
//when there are no more characters left in char array to add, add used chars to list of permutations
if (chars.length === 0) permArr[permArr.length] = usedChars.join("");
//send characters (minus the removed one from above) from char array to be permuted
permute(chars.join(""));
//add removed character back into char array in original position
chars.splice(i, 0, ch);
//remove the last character used off the end of used characters array
usedChars.pop();
}
}
permute(str);
return permArr;
}
permAlone('aab');
```
</section>

View File

@@ -2,15 +2,18 @@
id: a3f503de51cfab748ff001aa
title: Pairwise
challengeType: 5
videoUrl: ''
forumTopicId: 301617
localeTitle: парный
---
## Description
<section id="description"> Учитывая массив <code>arr</code> , найдите пары элементов, сумма которых равна второму аргументу <code>arg</code> и возвращает сумму их индексов. Вы можете использовать несколько пар, которые имеют одинаковые числовые элементы, но разные индексы. Каждая пара должна использовать самые низкие доступные индексы. Как только элемент был использован, его нельзя повторно использовать для соединения с другим элементом. Например, <code>pairwise([1, 1, 2], 3)</code> создает пару <code>[2, 1]</code> используя 1 в индексе 0, а не 1 в индексе 1, потому что 0 + 2 &lt;1 + 2. Например, <code>pairwise([7, 9, 11, 13, 15], 20)</code> возвращает <code>6</code> . Парами, суммирующимися до 20, являются <code>[7, 13]</code> и <code>[9, 11]</code> . Затем мы можем записать массив с их индексами и значениями. <table class="table"><tbody><tr><th> <strong>Индекс</strong> </th><th> 0 </th><th> 1 </th><th> 2 </th><th> 3 </th><th> 4 </th></tr><tr><td> Стоимость </td><td> 7 </td><td> 9 </td><td> 11 </td><td> 13 </td><td> 15 </td></tr></tbody></table> Ниже мы возьмем соответствующие индексы и добавим их. 7 + 13 = 20 → Индексы 0 + 3 = 3 <br> 9 + 11 = 20 → Индексы 1 + 2 = 3 <br> 3 + 3 = 6 → Return <code>6</code> забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код. </section>
<section id='description'>
Учитывая массив <code>arr</code> , найдите пары элементов, сумма которых равна второму аргументу <code>arg</code> и возвращает сумму их индексов. Вы можете использовать несколько пар, которые имеют одинаковые числовые элементы, но разные индексы. Каждая пара должна использовать самые низкие доступные индексы. Как только элемент был использован, его нельзя повторно использовать для соединения с другим элементом. Например, <code>pairwise([1, 1, 2], 3)</code> создает пару <code>[2, 1]</code> используя 1 в индексе 0, а не 1 в индексе 1, потому что 0 + 2 &lt;1 + 2. Например, <code>pairwise([7, 9, 11, 13, 15], 20)</code> возвращает <code>6</code> . Парами, суммирующимися до 20, являются <code>[7, 13]</code> и <code>[9, 11]</code> . Затем мы можем записать массив с их индексами и значениями. <table class="table"><tbody><tr><th> <strong>Индекс</strong> </th><th> 0 </th><th> 1 </th><th> 2 </th><th> 3 </th><th> 4 </th></tr><tr><td> Стоимость </td><td> 7 </td><td> 9 </td><td> 11 </td><td> 13 </td><td> 15 </td></tr></tbody></table> Ниже мы возьмем соответствующие индексы и добавим их. 7 + 13 = 20 → Индексы 0 + 3 = 3 <br> 9 + 11 = 20 → Индексы 1 + 2 = 3 <br> 3 + 3 = 6 → Return <code>6</code> забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: парный
```yml
tests:
- text: ''
testString: 'assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11, "<code>pairwise([1, 4, 2, 3, 0, 5], 7)</code> should return 11.");'
- text: ''
testString: 'assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1, "<code>pairwise([1, 3, 2, 4], 4)</code> should return 1.");'
- text: ''
testString: 'assert.deepEqual(pairwise([1, 1, 1], 2), 1, "<code>pairwise([1, 1, 1], 2)</code> should return 1.");'
- text: ''
testString: 'assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10, "<code>pairwise([0, 0, 0, 0, 1, 1], 1)</code> should return 10.");'
- text: ''
testString: 'assert.deepEqual(pairwise([], 100), 0, "<code>pairwise([], 100)</code> should return 0.");'
- text: <code>pairwise([1, 4, 2, 3, 0, 5], 7)</code> should return 11.
testString: assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11);
- text: <code>pairwise([1, 3, 2, 4], 4)</code> should return 1.
testString: assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1);
- text: <code>pairwise([1, 1, 1], 2)</code> should return 1.
testString: assert.deepEqual(pairwise([1, 1, 1], 2), 1);
- text: <code>pairwise([0, 0, 0, 0, 1, 1], 1)</code> should return 10.
testString: assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10);
- text: <code>pairwise([], 100)</code> should return 0.
testString: assert.deepEqual(pairwise([], 100), 0);
```
@@ -49,14 +52,30 @@ pairwise([1,4,2,3,0,5], 7);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function pairwise(arr, arg) {
var sum = 0;
arr.forEach(function(e, i, a) {
if (e != null) {
var diff = arg-e;
a[i] = null;
var dix = a.indexOf(diff);
if (dix !== -1) {
sum += dix;
sum += i;
a[dix] = null;
}
}
});
return sum;
}
pairwise([1,4,2,3,0,5], 7);
```
</section>

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>

View File

@@ -2,15 +2,18 @@
id: 5900f36e1000cf542c50fe80
challengeType: 5
title: 'Problem 1: Multiples of 3 and 5'
videoUrl: ''
forumTopicId: 301722
localeTitle: 'Проблема 1: Числа, кратные 3 или 5'
---
## Description
<section id="description"> Если мы перечислим все натуральные числа меньше 10, кратные 3 или 5, мы получим 3, 5, 6 и 9. Сумма этих кратных равна 23. Найдите сумму всех кратных 3 или 5 меньше значения параметра <code>number</code> . </section>
<section id='description'>
Если мы перечислим все натуральные числа меньше 10, кратные 3 или 5, мы получим 3, 5, 6 и 9. Сумма этих кратных равна 23. Найдите сумму всех кратных 3 или 5 меньше значения параметра <code>number</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: 'Проблема 1: Числа, кратные 3 или 5'
```yml
tests:
- text: <code>multiplesOf3and5(1000)</code> должна возвращать 233168.
testString: 'assert.strictEqual(multiplesOf3and5(1000), 233168, "<code>multiplesOf3and5(1000)</code> should return 233168.");'
- text: <code>multiplesOf3and5(49)</code> должна возвращать 543.
testString: 'assert.strictEqual(multiplesOf3and5(49), 543, "<code>multiplesOf3and5(49)</code> should return 543.");'
- text: <code>multiplesOf3and5(19564)</code> должна возвращать 89301183.
testString: 'assert.strictEqual(multiplesOf3and5(19564), 89301183, "<code>multiplesOf3and5(19564)</code> should return 89301183.");'
- text: 'Ваша функция возвращает неправильный результат, используя наши тестовые значения.'
testString: 'assert.strictEqual(multiplesOf3and5(8456), 16687353, "Your function is not returning the correct result using our tests values.");'
- text: <code>multiplesOf3and5(1000)</code> should return 233168.
testString: assert.strictEqual(multiplesOf3and5(1000), 233168);
- text: <code>multiplesOf3and5(49)</code> should return 543.
testString: assert.strictEqual(multiplesOf3and5(49), 543);
- text: <code>multiplesOf3and5(19564)</code> should return 89301183.
testString: assert.strictEqual(multiplesOf3and5(19564), 89301183);
- text: Your function is not returning the correct result using our tests values.
testString: assert.strictEqual(multiplesOf3and5(8456), 16687353);
```
@@ -48,14 +51,22 @@ multiplesOf3and5(1000);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
const multiplesOf3and5 = (number) => {
var total = 0;
for(var i = 0; i < number; i++) {
if(i % 3 == 0 || i % 5 == 0) {
total += i;
}
}
return total;
};
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3761000cf542c50fe89
challengeType: 5
title: 'Problem 10: Summation of primes'
videoUrl: ''
forumTopicId: 301723
localeTitle: 'Задача 10: Суммирование простых чисел'
---
## Description
<section id="description"> Сумма простых чисел ниже 10 равна 2 + 3 + 5 + 7 = 17. Найдите сумму всех простых чисел ниже n. </section>
<section id='description'>
Сумма простых чисел ниже 10 равна 2 + 3 + 5 + 7 = 17. Найдите сумму всех простых чисел ниже n.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: 'Задача 10: Суммирование простых чисе
```yml
tests:
- text: <code>primeSummation(17)</code> должен вернуть 41.
testString: 'assert.strictEqual(primeSummation(17), 41, "<code>primeSummation(17)</code> should return 41.");'
- text: <code>primeSummation(2001)</code> должен вернуть 277050.
testString: 'assert.strictEqual(primeSummation(2001), 277050, "<code>primeSummation(2001)</code> should return 277050.");'
- text: <code>primeSummation(140759)</code> должен вернуть 873608362.
testString: 'assert.strictEqual(primeSummation(140759), 873608362, "<code>primeSummation(140759)</code> should return 873608362.");'
- text: <code>primeSummation(2000000)</code> должен вернуть 142913828922.
testString: 'assert.strictEqual(primeSummation(2000000), 142913828922, "<code>primeSummation(2000000)</code> should return 142913828922.");'
- text: <code>primeSummation(17)</code> should return 41.
testString: assert.strictEqual(primeSummation(17), 41);
- text: <code>primeSummation(2001)</code> should return 277050.
testString: assert.strictEqual(primeSummation(2001), 277050);
- text: <code>primeSummation(140759)</code> should return 873608362.
testString: assert.strictEqual(primeSummation(140759), 873608362);
- text: <code>primeSummation(2000000)</code> should return 142913828922.
testString: assert.strictEqual(primeSummation(2000000), 142913828922);
```
@@ -48,14 +51,31 @@ primeSummation(2000000);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
//noprotect
function primeSummation(n) {
if (n < 3) { return 0 };
let nums = [0, 0, 2];
for (let i = 3; i < n; i += 2){
nums.push(i);
nums.push(0);
}
let sum = 2;
for (let i = 3; i < n; i += 2){
if (nums[i] !== 0){
sum += nums[i];
for (let j = i*i; j < n; j += i){
nums[j] = 0;
}
}
}
return sum;
}
```
</section>

View File

@@ -2,23 +2,29 @@
id: 5900f3d01000cf542c50fee3
challengeType: 5
title: 'Problem 100: Arranged probability'
videoUrl: ''
forumTopicId: 301724
localeTitle: 'Задача 100: Устроенная вероятность'
---
## Description
undefined
<section id='description'>
If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs, P(BB) = (15/21)×(14/20) = 1/2.
The next such arrangement, for which there is exactly 50% chance of taking two blue discs at random, is a box containing eighty-five blue discs and thirty-five red discs.
By finding the first arrangement to contain over 1012 = 1,000,000,000,000 discs in total, determine the number of blue discs that the box would contain.
</section>
## Instructions
undefined
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert.strictEqual(euler100(), 756872327473, "<code>euler100()</code> should return 756872327473.");'
- text: <code>euler100()</code> should return 756872327473.
testString: assert.strictEqual(euler100(), 756872327473);
```
@@ -41,8 +47,6 @@ euler100();
</div>
</section>
## Solution
@@ -51,4 +55,5 @@ euler100();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d21000cf542c50fee4
challengeType: 5
title: 'Problem 101: Optimum polynomial'
videoUrl: ''
forumTopicId: 301725
localeTitle: 'Задача 101: Оптимальный полином'
---
## Description
<section id="description"> Если нам представить первые k членов последовательности, то с уверенностью нельзя сказать значение следующего члена, так как существует бесконечно много полиномиальных функций, которые могут моделировать последовательность. В качестве примера рассмотрим последовательность чисел куба. Это определяется производящей функцией, un = n3: 1, 8, 27, 64, 125, 216, ... Предположим, что нам дали только первые два члена этой последовательности. Работая над принципом, что «просто лучше», мы должны принять линейную зависимость и предсказать, что следующий термин будет равен 15 (общая разница 7). Даже если нам были представлены первые три термина, по тому же принципу простоты, следует принять квадратичную зависимость. Будем определять OP (k, n) как n-й член оптимальной производящей полиномы функции для первых k членов последовательности. Должно быть ясно, что OP (k, n) будет точно генерировать члены последовательности для n ≤ k, и потенциально первый неправильный член (FIT) будет OP (k, k + 1); в этом случае мы будем называть это плохим OP (BOP). В качестве основы, если бы нам дали только первый член последовательности, было бы разумнее предполагать постоянство; т. е. при n ≥ 2, OP (1, n) = u1. Следовательно, для кубической последовательности мы получаем следующие OP: <p> OP (1, n) = 1 1, 1, 1, 1, ... OP (2, n) = 7n-6 1, 8, 15, ... OP (3, n) = 6n2-11n + 6 1, 8, 27, 58, ... OP (4, n) = n3 1, 8, 27, 64, 125, ... </p><p> Очевидно, что для k ≥ 4 не существует BOP. Рассматривая сумму FIT, генерируемых BOP (указанную красным выше), получаем 1 + 15 + 58 = 74. Рассмотрим следующую производящую функцию многочлена десятой степени: un = 1 - n + n2 - n3 + n4 - n5 + n6 - n7 + n8 - n9 + n10 Найти сумму FIT для BOP. </p></section>
<section id='description'>
Если нам представить первые k членов последовательности, то с уверенностью нельзя сказать значение следующего члена, так как существует бесконечно много полиномиальных функций, которые могут моделировать последовательность. В качестве примера рассмотрим последовательность чисел куба. Это определяется производящей функцией, un = n3: 1, 8, 27, 64, 125, 216, ... Предположим, что нам дали только первые два члена этой последовательности. Работая над принципом, что «просто лучше», мы должны принять линейную зависимость и предсказать, что следующий термин будет равен 15 (общая разница 7). Даже если нам были представлены первые три термина, по тому же принципу простоты, следует принять квадратичную зависимость. Будем определять OP (k, n) как n-й член оптимальной производящей полиномы функции для первых k членов последовательности. Должно быть ясно, что OP (k, n) будет точно генерировать члены последовательности для n ≤ k, и потенциально первый неправильный член (FIT) будет OP (k, k + 1); в этом случае мы будем называть это плохим OP (BOP). В качестве основы, если бы нам дали только первый член последовательности, было бы разумнее предполагать постоянство; т. е. при n ≥ 2, OP (1, n) = u1. Следовательно, для кубической последовательности мы получаем следующие OP: <p> OP (1, n) = 1 1, 1, 1, 1, ... OP (2, n) = 7n-6 1, 8, 15, ... OP (3, n) = 6n2-11n + 6 1, 8, 27, 58, ... OP (4, n) = n3 1, 8, 27, 64, 125, ... </p><p> Очевидно, что для k ≥ 4 не существует BOP. Рассматривая сумму FIT, генерируемых BOP (указанную красным выше), получаем 1 + 15 + 58 = 74. Рассмотрим следующую производящую функцию многочлена десятой степени: un = 1 - n + n2 - n3 + n4 - n5 + n6 - n7 + n8 - n9 + n10 Найти сумму FIT для BOP. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 101: Оптимальный полином'
```yml
tests:
- text: <code>euler101()</code> должен вернуть 37076114526.
testString: 'assert.strictEqual(euler101(), 37076114526, "<code>euler101()</code> should return 37076114526.");'
- text: <code>euler101()</code> should return 37076114526.
testString: assert.strictEqual(euler101(), 37076114526);
```
@@ -42,8 +45,6 @@ euler101();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler101();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,24 @@
id: 5900f3d21000cf542c50fee5
challengeType: 5
title: 'Problem 102: Triangle containment'
videoUrl: ''
forumTopicId: 301726
localeTitle: 'Проблема 102: Сохранение треугольника'
---
## Description
undefined
<section id='description'>
Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.
Consider the following two triangles:
A(-340,495), B(-153,-910), C(835,-947)
X(-175,41), Y(-421,-714), Z(574,-645)
It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.
Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin.
NOTE: The first two examples in the file represent the triangles in the example given above.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +27,8 @@ undefined
```yml
tests:
- text: ''
testString: 'assert.strictEqual(euler102(), 228, "<code>euler102()</code> should return 228.");'
- text: <code>euler102()</code> should return 228.
testString: assert.strictEqual(euler102(), 228);
```
@@ -42,8 +51,6 @@ euler102();
</div>
</section>
## Solution
@@ -52,4 +59,5 @@ euler102();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d61000cf542c50fee7
challengeType: 5
title: 'Problem 103: Special subset sums: optimum'
videoUrl: ''
forumTopicId: 301727
localeTitle: 'Задача 103: Специальные суммы подмножества: оптимальные'
---
## Description
<section id="description"> Пусть S (A) представляет сумму элементов из множества A размера n. Мы будем называть это специальным набором сумм, если для любых двух непустых непересекающихся подмножеств B и C справедливы следующие свойства: S (B) ≠ S (C); т. е. суммы подмножеств не могут быть равны. Если B содержит больше элементов, чем C, то S (B)&gt; S (C). Если S (A) минимизировано для данного n, мы назовем его оптимальным специальным набором сумм. Первые пять оптимальных специальных наборов сумм приведены ниже. n = 1: {1} n = 2: {1, 2} n = 3: {2, 3, 4} n = 4: {3, 5, 6, 7} n = 5: {6, 9, 11 , 12, 13}. Кажется, что для данного оптимального множества A = {a1, a2, ..., an} следующий оптимальный набор имеет вид B = {b, a1 + b, a2 + b,. .., an + b}, где b является «средним» элементом предыдущей строки. Применяя это «правило», мы ожидаем, что оптимальное множество для n = 6 будет A = {11, 17, 20, 22, 23, 24}, причем S (A) = 117. Однако это не оптимальный набор , поскольку мы просто применили алгоритм для обеспечения почти оптимального набора. Оптимальным для n = 6 является A = {11, 18, 19, 20, 22, 25}, с S (A) = 115 и соответствующей заданной строкой: 111819202225. Учитывая, что A - оптимальная специальная сумма, установленная для n = 7, найдите свою строку набора. ПРИМЕЧАНИЕ. Эта проблема связана с проблемой 105 и проблемой 106. </section>
<section id='description'>
Пусть S (A) представляет сумму элементов из множества A размера n. Мы будем называть это специальным набором сумм, если для любых двух непустых непересекающихся подмножеств B и C справедливы следующие свойства: S (B) ≠ S (C); т. е. суммы подмножеств не могут быть равны. Если B содержит больше элементов, чем C, то S (B)&gt; S (C). Если S (A) минимизировано для данного n, мы назовем его оптимальным специальным набором сумм. Первые пять оптимальных специальных наборов сумм приведены ниже. n = 1: {1} n = 2: {1, 2} n = 3: {2, 3, 4} n = 4: {3, 5, 6, 7} n = 5: {6, 9, 11 , 12, 13}. Кажется, что для данного оптимального множества A = {a1, a2, ..., an} следующий оптимальный набор имеет вид B = {b, a1 + b, a2 + b,. .., an + b}, где b является «средним» элементом предыдущей строки. Применяя это «правило», мы ожидаем, что оптимальное множество для n = 6 будет A = {11, 17, 20, 22, 23, 24}, причем S (A) = 117. Однако это не оптимальный набор , поскольку мы просто применили алгоритм для обеспечения почти оптимального набора. Оптимальным для n = 6 является A = {11, 18, 19, 20, 22, 25}, с S (A) = 115 и соответствующей заданной строкой: 111819202225. Учитывая, что A - оптимальная специальная сумма, установленная для n = 7, найдите свою строку набора. ПРИМЕЧАНИЕ. Эта проблема связана с проблемой 105 и проблемой 106.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 103: Специальные суммы подмнож
```yml
tests:
- text: <code>euler103()</code> должен вернуть 20313839404245.
testString: 'assert.strictEqual(euler103(), 20313839404245, "<code>euler103()</code> should return 20313839404245.");'
- text: <code>euler103()</code> should return 20313839404245.
testString: assert.strictEqual(euler103(), 20313839404245);
```
@@ -42,8 +45,6 @@ euler103();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler103();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d51000cf542c50fee6
challengeType: 5
title: 'Problem 104: Pandigital Fibonacci ends'
videoUrl: ''
forumTopicId: 301728
localeTitle: 'Задача 104: Финальные фибоначчиевые фишки'
---
## Description
<section id="description"> Последовательность Фибоначчи определяется рекуррентным соотношением: Fn = Fn-1 + Fn-2, где F1 = 1 и F2 = 1. Оказывается, что F541, содержащий 113 цифр, является первым числом Фибоначчи, для которого последние девять цифры 1-9 pandigital (содержат все цифры от 1 до 9, но не обязательно в порядке). И F2749, который содержит 575 цифр, является первым числом Фибоначчи, для которого первые девять цифр являются 1-9 pandigital. Учитывая, что Fk является первым числом Фибоначчи, для которого первые девять цифр И последние девять цифр являются 1-9 pandigital, найдите k. </section>
<section id='description'>
Последовательность Фибоначчи определяется рекуррентным соотношением: Fn = Fn-1 + Fn-2, где F1 = 1 и F2 = 1. Оказывается, что F541, содержащий 113 цифр, является первым числом Фибоначчи, для которого последние девять цифры 1-9 pandigital (содержат все цифры от 1 до 9, но не обязательно в порядке). И F2749, который содержит 575 цифр, является первым числом Фибоначчи, для которого первые девять цифр являются 1-9 pandigital. Учитывая, что Fk является первым числом Фибоначчи, для которого первые девять цифр И последние девять цифр являются 1-9 pandigital, найдите k.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 104: Финальные фибоначчиевые ф
```yml
tests:
- text: <code>euler104()</code> должен возвращать 329468.
testString: 'assert.strictEqual(euler104(), 329468, "<code>euler104()</code> should return 329468.");'
- text: <code>euler104()</code> should return 329468.
testString: assert.strictEqual(euler104(), 329468);
```
@@ -42,8 +45,6 @@ euler104();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler104();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d61000cf542c50fee8
challengeType: 5
title: 'Problem 105: Special subset sums: testing'
videoUrl: ''
forumTopicId: 301729
localeTitle: 'Задача 105: специальные суммы подмножеств: тестирование'
---
## Description
<section id="description"> Пусть S (A) представляет сумму элементов из множества A размера n. Мы будем называть это специальным набором сумм, если для любых двух непустых непересекающихся подмножеств B и C справедливы следующие свойства: S (B) ≠ S (C); т. е. суммы подмножеств не могут быть равны. Если B содержит больше элементов, чем C, то S (B)&gt; S (C). Например, {81, 88, 75, 42, 87, 84, 86, 65} не является специальной суммой, потому что 65 + 87 + 88 = 75 + 81 + 84, тогда как {157, 150, 164, 119, 79 , 159, 161, 139, 158} удовлетворяет обоим правилам для всех возможных комбинаций пар подмножеств и S (A) = 1286. Используя sets.txt (правый щелчок и «Сохранить ссылку / цель как ...»), текстовый файл 4K с сотнями наборов, содержащих от семи до двенадцати элементов (два приведенных выше примера являются первыми двумя наборами в файле), определите все специальные суммы, A1, A2, ..., Ak и найдем значение S ( A1) + S (A2) + ... + S (Ak). ПРИМЕЧАНИЕ. Эта проблема связана с проблемой 103 и задачей 106. </section>
<section id='description'>
Пусть S (A) представляет сумму элементов из множества A размера n. Мы будем называть это специальным набором сумм, если для любых двух непустых непересекающихся подмножеств B и C справедливы следующие свойства: S (B) ≠ S (C); т. е. суммы подмножеств не могут быть равны. Если B содержит больше элементов, чем C, то S (B)&gt; S (C). Например, {81, 88, 75, 42, 87, 84, 86, 65} не является специальной суммой, потому что 65 + 87 + 88 = 75 + 81 + 84, тогда как {157, 150, 164, 119, 79 , 159, 161, 139, 158} удовлетворяет обоим правилам для всех возможных комбинаций пар подмножеств и S (A) = 1286. Используя sets.txt (правый щелчок и «Сохранить ссылку / цель как ...»), текстовый файл 4K с сотнями наборов, содержащих от семи до двенадцати элементов (два приведенных выше примера являются первыми двумя наборами в файле), определите все специальные суммы, A1, A2, ..., Ak и найдем значение S ( A1) + S (A2) + ... + S (Ak). ПРИМЕЧАНИЕ. Эта проблема связана с проблемой 103 и задачей 106.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 105: специальные суммы подмнож
```yml
tests:
- text: <code>euler105()</code> должен возвращать 73702.
testString: 'assert.strictEqual(euler105(), 73702, "<code>euler105()</code> should return 73702.");'
- text: <code>euler105()</code> should return 73702.
testString: assert.strictEqual(euler105(), 73702);
```
@@ -42,8 +45,6 @@ euler105();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler105();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d71000cf542c50fee9
challengeType: 5
title: 'Problem 106: Special subset sums: meta-testing'
videoUrl: ''
forumTopicId: 301730
localeTitle: 'Задача 106: Специальные суммы подмножества: мета-тестирование'
---
## Description
<section id="description"> Пусть S (A) представляет сумму элементов из множества A размера n. Мы будем называть это специальным набором сумм, если для любых двух непустых непересекающихся подмножеств B и C справедливы следующие свойства: S (B) ≠ S (C); т. е. суммы подмножеств не могут быть равны. Если B содержит больше элементов, чем C, то S (B)&gt; S (C). Для этой задачи будем считать, что данное множество содержит n строго возрастающих элементов и оно уже удовлетворяет второму правилу. Удивительно, но из 25 возможных пар подмножеств, которые могут быть получены из множества, для которого n = 4, только 1 из этих пар необходимо проверить на равенство (первое правило). Аналогично, когда n = 7, необходимо проверить только 70 из 966 подмножеств. При n = 12, сколько из 261625 подмножеств, которые могут быть получены, необходимо проверить на равенство? ПРИМЕЧАНИЕ. Эта проблема связана с проблемой 103 и проблемой 105. </section>
<section id='description'>
Пусть S (A) представляет сумму элементов из множества A размера n. Мы будем называть это специальным набором сумм, если для любых двух непустых непересекающихся подмножеств B и C справедливы следующие свойства: S (B) ≠ S (C); т. е. суммы подмножеств не могут быть равны. Если B содержит больше элементов, чем C, то S (B)&gt; S (C). Для этой задачи будем считать, что данное множество содержит n строго возрастающих элементов и оно уже удовлетворяет второму правилу. Удивительно, но из 25 возможных пар подмножеств, которые могут быть получены из множества, для которого n = 4, только 1 из этих пар необходимо проверить на равенство (первое правило). Аналогично, когда n = 7, необходимо проверить только 70 из 966 подмножеств. При n = 12, сколько из 261625 подмножеств, которые могут быть получены, необходимо проверить на равенство? ПРИМЕЧАНИЕ. Эта проблема связана с проблемой 103 и проблемой 105.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 106: Специальные суммы подмнож
```yml
tests:
- text: <code>euler106()</code> должен возвращать 21384.
testString: 'assert.strictEqual(euler106(), 21384, "<code>euler106()</code> should return 21384.");'
- text: <code>euler106()</code> should return 21384.
testString: assert.strictEqual(euler106(), 21384);
```
@@ -42,8 +45,6 @@ euler106();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler106();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d91000cf542c50feea
challengeType: 5
title: 'Problem 107: Minimal network'
videoUrl: ''
forumTopicId: 301731
localeTitle: 'Проблема 107: Минимальная сеть'
---
## Description
<section id="description"> Следующая неориентированная сеть состоит из семи вершин и двенадцати ребер с общим весом 243. <p> Та же сеть может быть представлена ​​матрицей ниже. ABCDEFG A-161221 --- B16--1720-- C12--28-31- D211728-181923 E-20-18--11 F - 3119--27 G --- 231127- Однако возможно оптимизировать сеть, удалив некоторые ребра и все еще убедитесь, что все точки в сети остаются подключенными. Ниже показана сеть, которая обеспечивает максимальную экономию. Он имеет вес 93, что составляет экономию 243 - 93 = 150 от исходной сети. </p><p> Используя network.txt (щелчок правой кнопкой мыши и «Сохранить ссылку / цель как ...»), текстовый файл 6K, содержащий сеть со сорока вершинами и представленную в матричной форме, найдет максимальную экономию, которая может быть достигнута путем удаления избыточных краев в то время как что сеть остается подключенной. </p></section>
<section id='description'>
Следующая неориентированная сеть состоит из семи вершин и двенадцати ребер с общим весом 243. <p> Та же сеть может быть представлена ​​матрицей ниже. ABCDEFG A-161221 --- B16--1720-- C12--28-31- D211728-181923 E-20-18--11 F - 3119--27 G --- 231127- Однако возможно оптимизировать сеть, удалив некоторые ребра и все еще убедитесь, что все точки в сети остаются подключенными. Ниже показана сеть, которая обеспечивает максимальную экономию. Он имеет вес 93, что составляет экономию 243 - 93 = 150 от исходной сети. </p><p> Используя network.txt (щелчок правой кнопкой мыши и «Сохранить ссылку / цель как ...»), текстовый файл 6K, содержащий сеть со сорока вершинами и представленную в матричной форме, найдет максимальную экономию, которая может быть достигнута путем удаления избыточных краев в то время как что сеть остается подключенной. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Проблема 107: Минимальная сеть'
```yml
tests:
- text: <code>euler107()</code> должен вернуть 259679.
testString: 'assert.strictEqual(euler107(), 259679, "<code>euler107()</code> should return 259679.");'
- text: <code>euler107()</code> should return 259679.
testString: assert.strictEqual(euler107(), 259679);
```
@@ -42,8 +45,6 @@ euler107();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler107();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3d91000cf542c50feeb
challengeType: 5
title: 'Problem 108: Diophantine Reciprocals I'
videoUrl: ''
forumTopicId: 301732
localeTitle: 'Задача 108: диофантовы входы I'
---
## Description
<section id="description"> В следующем уравнении x, y и n - целые положительные числа. 1 / <var>x</var> + 1 / <var>y</var> = 1 / <var>n</var> Для <var>n</var> = 4 существует ровно три различных решения: 1/5 + 1/20 = 1/4 <br> 1/6 + 1/12 = 1/4 <br> 1/8 + 1/8 = 1/4. Какое наименьшее значение <var>n,</var> для которого количество различных решений превышает одну тысячу? </section>
<section id='description'>
В следующем уравнении x, y и n - целые положительные числа. 1 / <var>x</var> + 1 / <var>y</var> = 1 / <var>n</var> Для <var>n</var> = 4 существует ровно три различных решения: 1/5 + 1/20 = 1/4 <br> 1/6 + 1/12 = 1/4 <br> 1/8 + 1/8 = 1/4. Какое наименьшее значение <var>n,</var> для которого количество различных решений превышает одну тысячу?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 108: диофантовы входы I'
```yml
tests:
- text: <code>diophantineOne()</code> должен вернуть 180180.
testString: 'assert.strictEqual(diophantineOne(), 180180, "<code>diophantineOne()</code> should return 180180.");'
- text: <code>diophantineOne()</code> should return 180180.
testString: assert.strictEqual(diophantineOne(), 180180);
```
@@ -42,8 +45,6 @@ diophantineOne();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ diophantineOne();
```js
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 5900f3db1000cf542c50feec
challengeType: 5
title: 'Problem 109: Darts'
videoUrl: ''
forumTopicId: 301733
localeTitle: 'Задача 109: Дартс'
---
## Description
<section id="description"> В игре дартс игрок бросает три дротика на целевую доску, которая разделена на двадцать одинаковых размеров, пронумерованных от одного до двадцати. <p> Оценка дротика определяется количеством области, в которую попадает дротик. Дарт, вылетающий за пределы красного / зеленого внешнего кольца, имеет нулевое значение. Черные и кремовые области внутри этого кольца представляют собой одиночные баллы. Тем не менее, красное / зеленое внешнее кольцо и среднее кольцо оценивают двойные и высокие частоты соответственно. В центре доски расположены два концентрических круга, называемых бычьей областью или бычьим глазом. Внешний бык стоит 25 очков, а внутренний бык - в два раза, стоит 50 очков. Существует множество вариаций правил, но в самой популярной игре игроки начнут со счетом 301 или 501, и первым игроком, который снизит свою общую сумму до нуля, станет победителем. Тем не менее, нормально играть в систему «удваивает», а это означает, что игрок должен приземлить двойную (в том числе двойную бычьи глаза в центре доски) на свой последний дротик, чтобы выиграть; любой другой дротик, который уменьшил бы их общее количество до одного или ниже, означает, что оценка для этого набора из трех дротиков является «бюстом». Когда игрок может закончить свой текущий счет, он называется «проверка», а самая высокая проверка - 170: T20 T20 D25 (два тройных 20-х и двойной бык). Есть ровно одиннадцать различных способов проверки на счет 6: </p><p> D3 </p><p> D1 D2 </p><p> S2 D2 </p><p> D2 D1 </p><p> S4 D1 </p><p> S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 </p><p> Обратите внимание, что D1 D2 считается отличным от D2 D1, поскольку они заканчиваются в разных двухместных. Однако комбинация S1 T1 D1 считается такой же, как T1 S1 D1. Кроме того, мы не будем включать пропуски при рассмотрении комбинаций; например, D3 совпадает с 0 D3 и 0 0 D3. Невероятно 42336 различных способов проверки в целом. Сколько различных способов может пройти проверка игрока со счетом менее 100? </p></section>
<section id='description'>
В игре дартс игрок бросает три дротика на целевую доску, которая разделена на двадцать одинаковых размеров, пронумерованных от одного до двадцати. <p> Оценка дротика определяется количеством области, в которую попадает дротик. Дарт, вылетающий за пределы красного / зеленого внешнего кольца, имеет нулевое значение. Черные и кремовые области внутри этого кольца представляют собой одиночные баллы. Тем не менее, красное / зеленое внешнее кольцо и среднее кольцо оценивают двойные и высокие частоты соответственно. В центре доски расположены два концентрических круга, называемых бычьей областью или бычьим глазом. Внешний бык стоит 25 очков, а внутренний бык - в два раза, стоит 50 очков. Существует множество вариаций правил, но в самой популярной игре игроки начнут со счетом 301 или 501, и первым игроком, который снизит свою общую сумму до нуля, станет победителем. Тем не менее, нормально играть в систему «удваивает», а это означает, что игрок должен приземлить двойную (в том числе двойную бычьи глаза в центре доски) на свой последний дротик, чтобы выиграть; любой другой дротик, который уменьшил бы их общее количество до одного или ниже, означает, что оценка для этого набора из трех дротиков является «бюстом». Когда игрок может закончить свой текущий счет, он называется «проверка», а самая высокая проверка - 170: T20 T20 D25 (два тройных 20-х и двойной бык). Есть ровно одиннадцать различных способов проверки на счет 6: </p><p> D3 </p><p> D1 D2 </p><p> S2 D2 </p><p> D2 D1 </p><p> S4 D1 </p><p> S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 </p><p> Обратите внимание, что D1 D2 считается отличным от D2 D1, поскольку они заканчиваются в разных двухместных. Однако комбинация S1 T1 D1 считается такой же, как T1 S1 D1. Кроме того, мы не будем включать пропуски при рассмотрении комбинаций; например, D3 совпадает с 0 D3 и 0 0 D3. Невероятно 42336 различных способов проверки в целом. Сколько различных способов может пройти проверка игрока со счетом менее 100? </p>
</section>
## Instructions
undefined
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert.strictEqual(euler109(), 38182, "<code>euler109()</code> should return 38182.");'
- text: <code>euler109()</code> should return 38182.
testString: assert.strictEqual(euler109(), 38182);
```
@@ -41,8 +45,6 @@ euler109();
</div>
</section>
## Solution
@@ -51,4 +53,5 @@ euler109();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3781000cf542c50fe8a
challengeType: 5
title: 'Problem 11: Largest product in a grid'
videoUrl: ''
forumTopicId: 301734
localeTitle: 'Проблема 11: Крупнейший продукт в сетке'
---
## Description
<section id="description"> В сетке 20 × 20 ниже четыре цифры по диагональной линии отмечены красным цветом. <div style="text-align: center;"> 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 </div><div style="text-align: center;"> 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 </div><div style="text-align: center;"> 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 </div><div style="text-align: center;"> 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 </div><div style="text-align: center;"> 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 </div><div style="text-align: center;"> 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 </div><div style="text-align: center;"> 32 98 81 28 64 23 67 10 <span style="color: red"><b>26</b></span> 38 40 67 59 54 70 66 18 38 64 70 </div><div style="text-align: center;"> 67 26 20 68 02 62 12 20 95 <span style="color: red"><b>63</b></span> 94 39 63 08 40 91 66 49 94 21 </div><div style="text-align: center;"> 24 55 58 05 66 73 99 26 97 17 <span style="color: red"><b>78</b></span> 78 96 83 14 88 34 89 63 72 </div><div style="text-align: center;"> 21 36 23 09 75 00 76 44 20 45 35 <span style="color: red"><b>14</b></span> 00 61 33 97 34 31 33 95 </div><div style="text-align: center;"> 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 </div><div style="text-align: center;"> 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 </div><div style="text-align: center;"> 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 </div><div style="text-align: center;"> 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 </div><div style="text-align: center;"> 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 </div><div style="text-align: center;"> 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 </div><div style="text-align: center;"> 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 </div><div style="text-align: center;"> 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 </div><div style="text-align: center;"> 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 </div><div style="text-align: center;"> 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 </div><p> Произведение этих чисел составляет 26 × 63 × 78 × 14 = 1788696. Каково наибольшее произведение четырех соседних чисел в том же направлении (вверх, вниз, влево, вправо, или по диагонали) в данном <code>arr</code> сетке? </p></section>
<section id='description'>
В сетке 20 × 20 ниже четыре цифры по диагональной линии отмечены красным цветом. <div style="text-align: center;"> 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 </div><div style="text-align: center;"> 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 </div><div style="text-align: center;"> 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 </div><div style="text-align: center;"> 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 </div><div style="text-align: center;"> 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 </div><div style="text-align: center;"> 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 </div><div style="text-align: center;"> 32 98 81 28 64 23 67 10 <span style="color: red"><b>26</b></span> 38 40 67 59 54 70 66 18 38 64 70 </div><div style="text-align: center;"> 67 26 20 68 02 62 12 20 95 <span style="color: red"><b>63</b></span> 94 39 63 08 40 91 66 49 94 21 </div><div style="text-align: center;"> 24 55 58 05 66 73 99 26 97 17 <span style="color: red"><b>78</b></span> 78 96 83 14 88 34 89 63 72 </div><div style="text-align: center;"> 21 36 23 09 75 00 76 44 20 45 35 <span style="color: red"><b>14</b></span> 00 61 33 97 34 31 33 95 </div><div style="text-align: center;"> 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 </div><div style="text-align: center;"> 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 </div><div style="text-align: center;"> 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 </div><div style="text-align: center;"> 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 </div><div style="text-align: center;"> 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 </div><div style="text-align: center;"> 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 </div><div style="text-align: center;"> 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 </div><div style="text-align: center;"> 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 </div><div style="text-align: center;"> 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 </div><div style="text-align: center;"> 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 </div><p> Произведение этих чисел составляет 26 × 63 × 78 × 14 = 1788696. Каково наибольшее произведение четырех соседних чисел в том же направлении (вверх, вниз, влево, вправо, или по диагонали) в данном <code>arr</code> сетке? </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: 'Проблема 11: Крупнейший продукт в сет
```yml
tests:
- text: <code>largestGridProduct(grid)</code> должен возвращать 70600674.
testString: 'assert.strictEqual(largestGridProduct(grid), 70600674, "<code>largestGridProduct(grid)</code> should return 70600674.");'
- text: <code>largestGridProduct(testGrid)</code> должен возвращать 14169081.
testString: 'assert.strictEqual(largestGridProduct(testGrid), 14169081, "<code>largestGridProduct(testGrid)</code> should return 14169081.");'
- text: <code>largestGridProduct(grid)</code> should return 70600674.
testString: assert.strictEqual(largestGridProduct(grid), 70600674);
- text: <code>largestGridProduct(testGrid)</code> should return 14169081.
testString: assert.strictEqual(largestGridProduct(testGrid), 14169081);
```
@@ -76,14 +79,86 @@ largestGridProduct(testGrid);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function largestGridProduct(arr) {
let maxProduct = 0;
let currProduct = 0;
function maxProductChecker(n) {
if (n > maxProduct) {
return maxProduct = n;
}
}
// loop rows
for (let r = 0; r < arr.length; r++) {
// loop columns
for (let c = 0; c < arr[r].length; c++) {
const limit = arr[r].length - 3;
// check horizontal
if (c < limit) {
currProduct = arr[r][c] * arr[r][c + 1] * arr[r][c + 2] * arr[r][c + 3];
maxProductChecker(currProduct);
}
// check vertical
if (r < limit) {
currProduct = arr[r][c] * arr[r + 1][c] * arr[r + 2][c] * arr[r + 3][c];
maxProductChecker(currProduct);
}
// check diagonal [\]
if (c < limit && r < limit) {
currProduct = arr[r][c] * arr[r + 1][c + 1] * arr[r + 2][c + 2] * arr[r + 3][c + 3];
maxProductChecker(currProduct);
}
// check diagonal [/]
if (c > 3 && r < limit) {
currProduct = arr[r][c] * arr[r + 1][c - 1] * arr[r + 2][c - 2] * arr[r + 3][c - 3];
maxProductChecker(currProduct);
}
}
}
return maxProduct;
}
const grid = [ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
];
const testGrid = [
[40, 17, 81, 18, 57],
[74, 4, 36, 16, 29],
[36, 42, 69, 73, 45],
[51, 54, 69, 16, 92],
[7, 97, 57, 32, 16]
];
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3db1000cf542c50feed
challengeType: 5
title: 'Problem 110: Diophantine Reciprocals II'
videoUrl: ''
forumTopicId: 301735
localeTitle: 'Задача 110: диофантийские реципрокты II'
---
## Description
<section id="description"> В следующем уравнении x, y и n - целые положительные числа. 1 / <var>x</var> + 1 / <var>y</var> = 1 / <var>n.</var> Можно проверить, что при <var>n</var> = 1260 существует 113 различных решений, и это наименьшее значение <var>n,</var> для которого общее число различных решений превышает сто. Каково наименьшее значение <var>n,</var> для которого количество различных решений превышает четыре миллиона? </section>
<section id='description'>
В следующем уравнении x, y и n - целые положительные числа. 1 / <var>x</var> + 1 / <var>y</var> = 1 / <var>n.</var> Можно проверить, что при <var>n</var> = 1260 существует 113 различных решений, и это наименьшее значение <var>n,</var> для которого общее число различных решений превышает сто. Каково наименьшее значение <var>n,</var> для которого количество различных решений превышает четыре миллиона?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 110: диофантийские реципрокты
```yml
tests:
- text: <code>diophantineTwo</code> должен вернуть 9350130049860600.
testString: 'assert.strictEqual(diophantineTwo(), 9350130049860600, "<code>diophantineTwo()</code> should return 9350130049860600.");'
- text: <code>diophantineTwo()</code> should return 9350130049860600.
testString: assert.strictEqual(diophantineTwo(), 9350130049860600);
```
@@ -42,8 +45,6 @@ diophantineTwo();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ diophantineTwo();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3db1000cf542c50feee
challengeType: 5
title: 'Problem 111: Primes with runs'
videoUrl: ''
forumTopicId: 301736
localeTitle: 'Проблема 111: Primes с пробегами'
---
## Description
<section id="description"> Учитывая 4-значные простые числа, содержащие повторяющиеся цифры, ясно, что они не могут быть одинаковыми: 1111 делится на 11, 2222 делится на 22 и т. Д. Но есть девять четырехзначных простых чисел, содержащих три: 1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111. Мы будем говорить, что M (n, d) представляет максимальное количество повторных цифр для n- где d - повторяющаяся цифра, N (n, d) представляет количество таких простых чисел, а S (n, d) представляет собой сумму этих простых чисел. Таким образом, M (4, 1) = 3 является максимальным числом повторных цифр для 4-значного простого числа, где одна является повторной цифрой, то N (4, 1) = 9 таких простых чисел, а сумма этих простых чисел равна S (4, 1) = 22275. Оказывается, что при d = 0 возможно только M (4, 0) = 2 повторных цифры, но существует N (4, 0) = 13 таких случаев. Точно так же мы получаем следующие результаты для четырехзначных простых чисел. <p> Digit, d M (4, d) N (4, d) S (4, d) 0 2 13 67061 1 3 9 22275 2 3 1 2221 3 3 12 46214 4 3 2 8888 5 3 1 5557 6 3 1 6661 7 3 9 57863 8 3 1 8887 9 3 7 48073 </p><p> При d = 0 до 9 сумма всех S (4, d) равна 273700. Найдите сумму всех S (10, d). </p></section>
<section id='description'>
Учитывая 4-значные простые числа, содержащие повторяющиеся цифры, ясно, что они не могут быть одинаковыми: 1111 делится на 11, 2222 делится на 22 и т. Д. Но есть девять четырехзначных простых чисел, содержащих три: 1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111. Мы будем говорить, что M (n, d) представляет максимальное количество повторных цифр для n- где d - повторяющаяся цифра, N (n, d) представляет количество таких простых чисел, а S (n, d) представляет собой сумму этих простых чисел. Таким образом, M (4, 1) = 3 является максимальным числом повторных цифр для 4-значного простого числа, где одна является повторной цифрой, то N (4, 1) = 9 таких простых чисел, а сумма этих простых чисел равна S (4, 1) = 22275. Оказывается, что при d = 0 возможно только M (4, 0) = 2 повторных цифры, но существует N (4, 0) = 13 таких случаев. Точно так же мы получаем следующие результаты для четырехзначных простых чисел. <p> Digit, d M (4, d) N (4, d) S (4, d) 0 2 13 67061 1 3 9 22275 2 3 1 2221 3 3 12 46214 4 3 2 8888 5 3 1 5557 6 3 1 6661 7 3 9 57863 8 3 1 8887 9 3 7 48073 </p><p> При d = 0 до 9 сумма всех S (4, d) равна 273700. Найдите сумму всех S (10, d). </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Проблема 111: Primes с пробегами'
```yml
tests:
- text: ''
testString: 'assert.strictEqual(euler111(), 612407567715, "<code>euler111()</code> should return 612407567715.");'
- text: <code>euler111()</code> should return 612407567715.
testString: assert.strictEqual(euler111(), 612407567715);
```
@@ -42,8 +45,6 @@ euler111();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler111();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3dd1000cf542c50feef
challengeType: 5
title: 'Problem 112: Bouncy numbers'
videoUrl: ''
forumTopicId: 301738
localeTitle: 'Задача 112: Надувные номера'
---
## Description
<section id="description"> Работая слева направо, если цифра не превышена цифрой слева от нее, она называется все увеличивающимся числом; например, 134468. Аналогично, если цифра не будет превышена цифрой справа, она называется уменьшающимся числом; например, 66420. Мы будем называть положительное целое число, которое не увеличивает и не уменьшает «бодрящее» число; например, 155349. Очевидно, что не может быть никаких надувных чисел ниже ста, но чуть более половины чисел ниже одной тысячи (525) являются упругими. Фактически, наименьшее число, для которого доля бодрящих чисел вначале достигает 50%, составляет 538. Удивительно, что набирающие обороты цифры становятся все более распространенными, и к тому времени, когда мы достигнем 21780, доля надувных чисел равна 90%. Найдите наименьшее число, для которого доля надувных чисел составляет ровно 99%. </section>
<section id='description'>
Работая слева направо, если цифра не превышена цифрой слева от нее, она называется все увеличивающимся числом; например, 134468. Аналогично, если цифра не будет превышена цифрой справа, она называется уменьшающимся числом; например, 66420. Мы будем называть положительное целое число, которое не увеличивает и не уменьшает «бодрящее» число; например, 155349. Очевидно, что не может быть никаких надувных чисел ниже ста, но чуть более половины чисел ниже одной тысячи (525) являются упругими. Фактически, наименьшее число, для которого доля бодрящих чисел вначале достигает 50%, составляет 538. Удивительно, что набирающие обороты цифры становятся все более распространенными, и к тому времени, когда мы достигнем 21780, доля надувных чисел равна 90%. Найдите наименьшее число, для которого доля надувных чисел составляет ровно 99%.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 112: Надувные номера'
```yml
tests:
- text: <code>euler112()</code> должен вернуть 1587000.
testString: 'assert.strictEqual(euler112(), 1587000, "<code>euler112()</code> should return 1587000.");'
- text: <code>euler112()</code> should return 1587000.
testString: assert.strictEqual(euler112(), 1587000);
```
@@ -42,8 +45,6 @@ euler112();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler112();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3dd1000cf542c50fef0
challengeType: 5
title: 'Problem 113: Non-bouncy numbers'
videoUrl: ''
forumTopicId: 301739
localeTitle: 'Задача 113: Номера без ожирения'
---
## Description
<section id="description"> Работая слева направо, если цифра не превышена цифрой слева от нее, она называется все увеличивающимся числом; например, 134468. Аналогично, если цифра не будет превышена цифрой справа, она называется уменьшающимся числом; например, 66420. Мы будем называть положительное целое число, которое не увеличивает и не уменьшает «бодрящее» число; например, 155349. При увеличении n доля бодрящих чисел ниже n возрастает, так что всего лишь 12951 число ниже одного миллиона, которые не являются упругими и только 277032 числа, не несущественные, ниже 1010. Сколько чисел ниже googol (10100 ) не бод? </section>
<section id='description'>
Работая слева направо, если цифра не превышена цифрой слева от нее, она называется все увеличивающимся числом; например, 134468. Аналогично, если цифра не будет превышена цифрой справа, она называется уменьшающимся числом; например, 66420. Мы будем называть положительное целое число, которое не увеличивает и не уменьшает «бодрящее» число; например, 155349. При увеличении n доля бодрящих чисел ниже n возрастает, так что всего лишь 12951 число ниже одного миллиона, которые не являются упругими и только 277032 числа, не несущественные, ниже 1010. Сколько чисел ниже googol (10100 ) не бод?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 113: Номера без ожирения'
```yml
tests:
- text: <code>euler113()</code> должен вернуть 51161058134250.
testString: 'assert.strictEqual(euler113(), 51161058134250, "<code>euler113()</code> should return 51161058134250.");'
- text: <code>euler113()</code> should return 51161058134250.
testString: assert.strictEqual(euler113(), 51161058134250);
```
@@ -42,8 +45,6 @@ euler113();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler113();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e01000cf542c50fef2
challengeType: 5
title: 'Problem 114: Counting block combinations I'
videoUrl: ''
forumTopicId: 301740
localeTitle: 'Задача 114: Комбинации счетных блоков I'
---
## Description
<section id="description"> Строка длиной семь единиц имеет красные блоки с минимальной длиной в три единицы, размещенные на ней, так что любые два красных блока (которые допускаются к разным длинам) разделены по меньшей мере одним черным квадратом. Есть ровно семнадцать способов сделать это. <p> Сколько путей может быть заполнено длиной в пятьдесят единиц? ПРИМЕЧАНИЕ. Хотя приведенный выше пример не дает возможности, в общем, разрешается смешивать размеры блоков. Например, в строке длиной восемь единиц можно использовать красный (3), черный (1) и красный (4). </p></section>
<section id='description'>
Строка длиной семь единиц имеет красные блоки с минимальной длиной в три единицы, размещенные на ней, так что любые два красных блока (которые допускаются к разным длинам) разделены по меньшей мере одним черным квадратом. Есть ровно семнадцать способов сделать это. <p> Сколько путей может быть заполнено длиной в пятьдесят единиц? ПРИМЕЧАНИЕ. Хотя приведенный выше пример не дает возможности, в общем, разрешается смешивать размеры блоков. Например, в строке длиной восемь единиц можно использовать красный (3), черный (1) и красный (4). </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 114: Комбинации счетных блоков
```yml
tests:
- text: <code>euler114()</code> должен вернуть 16475640049.
testString: 'assert.strictEqual(euler114(), 16475640049, "<code>euler114()</code> should return 16475640049.");'
- text: <code>euler114()</code> should return 16475640049.
testString: assert.strictEqual(euler114(), 16475640049);
```
@@ -42,8 +45,6 @@ euler114();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler114();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3df1000cf542c50fef1
challengeType: 5
title: 'Problem 115: Counting block combinations II'
videoUrl: ''
forumTopicId: 301741
localeTitle: 'Задача 115: Комбинации счетных блоков II'
---
## Description
<section id="description"> ПРИМЕЧАНИЕ. Это более сложная версия задачи 114. Строка, измеряющая n единиц длины, имеет красные блоки с минимальной длиной м единиц, размещенных на ней, так что любые два красных блока (которые допускаются к разным длинам) разделяются по крайней мере, одним черным квадратом. Пусть функция заполнения, F (m, n), представляет количество способов заполнения строки. Например, F (3, 29) = 673135 и F (3, 30) = 1089155. То есть, при m = 3 можно видеть, что n = 30 является наименьшим значением, для которого функция заполнения один миллион. Точно так же при m = 10 можно проверить, что F (10, 56) = 880711 и F (10, 57) = 1148904, поэтому n = 57 является наименьшим значением, для которого функция заполнения один миллион. При m = 50 найдите наименьшее значение n, для которого функция заполнения заполнения сначала превышает один миллион. </section>
<section id='description'>
ПРИМЕЧАНИЕ. Это более сложная версия задачи 114. Строка, измеряющая n единиц длины, имеет красные блоки с минимальной длиной м единиц, размещенных на ней, так что любые два красных блока (которые допускаются к разным длинам) разделяются по крайней мере, одним черным квадратом. Пусть функция заполнения, F (m, n), представляет количество способов заполнения строки. Например, F (3, 29) = 673135 и F (3, 30) = 1089155. То есть, при m = 3 можно видеть, что n = 30 является наименьшим значением, для которого функция заполнения один миллион. Точно так же при m = 10 можно проверить, что F (10, 56) = 880711 и F (10, 57) = 1148904, поэтому n = 57 является наименьшим значением, для которого функция заполнения один миллион. При m = 50 найдите наименьшее значение n, для которого функция заполнения заполнения сначала превышает один миллион.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 115: Комбинации счетных блоков
```yml
tests:
- text: <code>euler115()</code> должен вернуть 168.
testString: 'assert.strictEqual(euler115(), 168, "<code>euler115()</code> should return 168.");'
- text: <code>euler115()</code> should return 168.
testString: assert.strictEqual(euler115(), 168);
```
@@ -42,8 +45,6 @@ euler115();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler115();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e01000cf542c50fef3
challengeType: 5
title: 'Problem 116: Red, green or blue tiles'
videoUrl: ''
forumTopicId: 301742
localeTitle: 'Проблема 116: красная, зеленая или синяя плитка'
---
## Description
<section id="description"> Ряд из пяти квадратов черного квадрата должен иметь несколько своих черепиц, замененных цветными продолговатыми плитами, выбранными из красного (длина два), зеленым (длина три) или синим (длина четыре). Если выбраны красные плитки, это может быть сделано всего семь способов. <p> Если выбраны зеленые плитки, есть три способа. </p><p> И если выбраны синие плитки, есть два пути. </p><p> Предполагая, что цвета не могут быть смешаны, есть 7 + 3 + 2 = 12 способов замены черных плит в строке длиной в пять единиц. Сколько различных способов можно заменить черные плитки длиной в пятьдесят единиц в длину, если цвета не могут быть смешаны и по крайней мере одна цветная плитка должна использоваться? ПРИМЕЧАНИЕ. Это связано с проблемой 117. </p></section>
<section id='description'>
Ряд из пяти квадратов черного квадрата должен иметь несколько своих черепиц, замененных цветными продолговатыми плитами, выбранными из красного (длина два), зеленым (длина три) или синим (длина четыре). Если выбраны красные плитки, это может быть сделано всего семь способов. <p> Если выбраны зеленые плитки, есть три способа. </p><p> И если выбраны синие плитки, есть два пути. </p><p> Предполагая, что цвета не могут быть смешаны, есть 7 + 3 + 2 = 12 способов замены черных плит в строке длиной в пять единиц. Сколько различных способов можно заменить черные плитки длиной в пятьдесят единиц в длину, если цвета не могут быть смешаны и по крайней мере одна цветная плитка должна использоваться? ПРИМЕЧАНИЕ. Это связано с проблемой 117. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Проблема 116: красная, зеленая или син
```yml
tests:
- text: <code>euler116()</code> должен вернуть 20492570929.
testString: 'assert.strictEqual(euler116(), 20492570929, "<code>euler116()</code> should return 20492570929.");'
- text: <code>euler116()</code> should return 20492570929.
testString: assert.strictEqual(euler116(), 20492570929);
```
@@ -42,8 +45,6 @@ euler116();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler116();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e21000cf542c50fef4
challengeType: 5
title: 'Problem 117: Red, green, and blue tiles'
videoUrl: ''
forumTopicId: 301743
localeTitle: 'Проблема 117: красная, зеленая и синяя плитка'
---
## Description
<section id="description"> Используя комбинацию черных квадратных плит и продолговатых плиток, выбранных из: красных плиток, измеряющих два блока, зеленых плит, измеряющих три единицы, и синих плит, измеряющих четыре единицы, можно плитку длиной в пять единиц длиной ровно пятнадцатью различными способами. <p> Сколько способов может содержать черепица длиной в пятьдесят единиц? ПРИМЕЧАНИЕ. Это связано с задачей 116. </p></section>
<section id='description'>
Используя комбинацию черных квадратных плит и продолговатых плиток, выбранных из: красных плиток, измеряющих два блока, зеленых плит, измеряющих три единицы, и синих плит, измеряющих четыре единицы, можно плитку длиной в пять единиц длиной ровно пятнадцатью различными способами. <p> Сколько способов может содержать черепица длиной в пятьдесят единиц? ПРИМЕЧАНИЕ. Это связано с задачей 116. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Проблема 117: красная, зеленая и синяя
```yml
tests:
- text: <code>euler117()</code> должен вернуть 100808458960497.
testString: 'assert.strictEqual(euler117(), 100808458960497, "<code>euler117()</code> should return 100808458960497.");'
- text: <code>euler117()</code> should return 100808458960497.
testString: assert.strictEqual(euler117(), 100808458960497);
```
@@ -42,8 +45,6 @@ euler117();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler117();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e21000cf542c50fef5
challengeType: 5
title: 'Problem 118: Pandigital prime sets'
videoUrl: ''
forumTopicId: 301744
localeTitle: 'Задача 118: Pandigital простые множества'
---
## Description
<section id="description"> Используя все цифры с 1 по 9 и конкатенируя их свободно, чтобы сформировать десятичные целые числа, могут быть сформированы различные множества. Интересно, что набор {2,5,47,89,631}, все элементы, принадлежащие ему, являются просторными. Сколько различных наборов, содержащих каждую из цифр от одного до девятого ровно один раз, содержат только простые элементы? </section>
<section id='description'>
Используя все цифры с 1 по 9 и конкатенируя их свободно, чтобы сформировать десятичные целые числа, могут быть сформированы различные множества. Интересно, что набор {2,5,47,89,631}, все элементы, принадлежащие ему, являются просторными. Сколько различных наборов, содержащих каждую из цифр от одного до девятого ровно один раз, содержат только простые элементы?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 118: Pandigital простые множества'
```yml
tests:
- text: <code>euler118()</code> должен возвращать 44680.
testString: 'assert.strictEqual(euler118(), 44680, "<code>euler118()</code> should return 44680.");'
- text: <code>euler118()</code> should return 44680.
testString: assert.strictEqual(euler118(), 44680);
```
@@ -42,8 +45,6 @@ euler118();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler118();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e41000cf542c50fef6
challengeType: 5
title: 'Problem 119: Digit power sum'
videoUrl: ''
forumTopicId: 301745
localeTitle: 'Задача 119: Суммарная сумма электроэнергии'
---
## Description
<section id="description"> Число 512 интересно, потому что оно равно сумме его цифр, поднятых до некоторой степени: 5 + 1 + 2 = 8 и 83 = 512. Другим примером числа с этим свойством является 614656 = 284. Мы определим быть n-м членом этой последовательности и настаивать на том, чтобы число должно содержать не менее двух цифр, чтобы иметь сумму. Вам дается, что a2 = 512 и a10 = 614656. Найдите a30. </section>
<section id='description'>
Число 512 интересно, потому что оно равно сумме его цифр, поднятых до некоторой степени: 5 + 1 + 2 = 8 и 83 = 512. Другим примером числа с этим свойством является 614656 = 284. Мы определим быть n-м членом этой последовательности и настаивать на том, чтобы число должно содержать не менее двух цифр, чтобы иметь сумму. Вам дается, что a2 = 512 и a10 = 614656. Найдите a30.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 119: Суммарная сумма электроэн
```yml
tests:
- text: <code>euler119()</code> должен вернуть 248155780267521.
testString: 'assert.strictEqual(euler119(), 248155780267521, "<code>euler119()</code> should return 248155780267521.");'
- text: <code>euler119()</code> should return 248155780267521.
testString: assert.strictEqual(euler119(), 248155780267521);
```
@@ -42,8 +45,6 @@ euler119();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler119();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3781000cf542c50fe8b
challengeType: 5
title: 'Problem 12: Highly divisible triangular number'
videoUrl: ''
forumTopicId: 301746
localeTitle: 'Задача 12: Высокое делимое треугольное число'
---
## Description
<section id="description"> Последовательность чисел треугольника порождается добавлением натуральных чисел. Таким образом, 7-й номер треугольника будет 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Первые десять терминов будут: <div style="text-align: center;"> 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... </div> Перечислим коэффициенты первых семи чисел треугольника: <div style="padding-left: 4em;"> <b>1:</b> 1 </div><div style="padding-left: 4em;"> <b>3:</b> 1, 3 </div><div style="padding-left: 4em;"> <b>6:</b> 1, 2, 3, 6 </div><div style="padding-left: 4em;"> <b>10:</b> 1, 2, 5, 10 </div><div style="padding-left: 4em;"> <b>15:</b> 1, 3, 5, 15 </div><div style="padding-left: 4em;"> <b>21:</b> 1, 3, 7, 21 </div><div style="padding-left: 4em;"> <b>28:</b> 1, 2, 4, 7, 14, 28 </div> Мы видим, что 28 - это первое число треугольников, состоящее из пяти делителей. Каково значение первого числа треугольников для <code>n</code> делителей? </section>
<section id='description'>
Последовательность чисел треугольника порождается добавлением натуральных чисел. Таким образом, 7-й номер треугольника будет 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Первые десять терминов будут: <div style="text-align: center;"> 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... </div> Перечислим коэффициенты первых семи чисел треугольника: <div style="padding-left: 4em;"> <b>1:</b> 1 </div><div style="padding-left: 4em;"> <b>3:</b> 1, 3 </div><div style="padding-left: 4em;"> <b>6:</b> 1, 2, 3, 6 </div><div style="padding-left: 4em;"> <b>10:</b> 1, 2, 5, 10 </div><div style="padding-left: 4em;"> <b>15:</b> 1, 3, 5, 15 </div><div style="padding-left: 4em;"> <b>21:</b> 1, 3, 7, 21 </div><div style="padding-left: 4em;"> <b>28:</b> 1, 2, 4, 7, 14, 28 </div> Мы видим, что 28 - это первое число треугольников, состоящее из пяти делителей. Каково значение первого числа треугольников для <code>n</code> делителей?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: 'Задача 12: Высокое делимое треугольн
```yml
tests:
- text: <code>divisibleTriangleNumber(5)</code> должен возвращать 28.
testString: 'assert.strictEqual(divisibleTriangleNumber(5), 28, "<code>divisibleTriangleNumber(5)</code> should return 28.");'
- text: <code>divisibleTriangleNumber(23)</code> должен возвращать 630.
testString: 'assert.strictEqual(divisibleTriangleNumber(23), 630, "<code>divisibleTriangleNumber(23)</code> should return 630.");'
- text: <code>divisibleTriangleNumber(167)</code> должен возвращать 1385280.
testString: 'assert.strictEqual(divisibleTriangleNumber(167), 1385280, "<code>divisibleTriangleNumber(167)</code> should return 1385280.");'
- text: <code>divisibleTriangleNumber(374)</code> должен возвращать 17907120.
testString: 'assert.strictEqual(divisibleTriangleNumber(374), 17907120, "<code>divisibleTriangleNumber(374)</code> should return 17907120.");'
- text: <code>divisibleTriangleNumber(500)</code> должен возвращать 76576500.
testString: 'assert.strictEqual(divisibleTriangleNumber(500), 76576500, "<code>divisibleTriangleNumber(500)</code> should return 76576500.");'
- text: <code>divisibleTriangleNumber(5)</code> should return 28.
testString: assert.strictEqual(divisibleTriangleNumber(5), 28);
- text: <code>divisibleTriangleNumber(23)</code> should return 630.
testString: assert.strictEqual(divisibleTriangleNumber(23), 630);
- text: <code>divisibleTriangleNumber(167)</code> should return 1385280.
testString: assert.strictEqual(divisibleTriangleNumber(167), 1385280);
- text: <code>divisibleTriangleNumber(374)</code> should return 17907120.
testString: assert.strictEqual(divisibleTriangleNumber(374), 17907120);
- text: <code>divisibleTriangleNumber(500)</code> should return 76576500.
testString: assert.strictEqual(divisibleTriangleNumber(500), 76576500);
```
@@ -50,14 +53,42 @@ divisibleTriangleNumber(500);
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function divisibleTriangleNumber(n) {
let counter = 1;
let triangleNumber = counter++;
function getFactors(num) {
let factors = [];
let possibleFactor = 1;
let sqrt = Math.sqrt(num);
while (possibleFactor <= sqrt) {
if (num % possibleFactor == 0) {
factors.push(possibleFactor);
var otherPossibleFactor = num / possibleFactor;
if (otherPossibleFactor > possibleFactor) {
factors.push(otherPossibleFactor);
}
}
possibleFactor++;
}
return factors;
}
while (getFactors(triangleNumber).length < n) {
triangleNumber += counter++;
}
console.log(triangleNumber)
return triangleNumber;
}
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e41000cf542c50fef7
challengeType: 5
title: 'Problem 120: Square remainders'
videoUrl: ''
forumTopicId: 301747
localeTitle: 'Задача 120: Квадратные остатки'
---
## Description
<section id="description"> Пусть r - остаток, когда (a-1) n + (a + 1) n делится на a2. Например, если a = 7 и n = 3, то r = 42: 63 + 83 = 728 ≡ 42 mod 49. А при изменении n также будет r, но при a = 7 получается, что rmax = 42. Для 3 ≤ a ≤ 1000 найдите Σ rmax. </section>
<section id='description'>
Пусть r - остаток, когда (a-1) n + (a + 1) n делится на a2. Например, если a = 7 и n = 3, то r = 42: 63 + 83 = 728 ≡ 42 mod 49. А при изменении n также будет r, но при a = 7 получается, что rmax = 42. Для 3 ≤ a ≤ 1000 найдите Σ rmax.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 120: Квадратные остатки'
```yml
tests:
- text: <code>euler120()</code> должен вернуть 333082500.
testString: 'assert.strictEqual(euler120(), 333082500, "<code>euler120()</code> should return 333082500.");'
- text: <code>euler120()</code> should return 333082500.
testString: assert.strictEqual(euler120(), 333082500);
```
@@ -42,8 +45,6 @@ euler120();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler120();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e51000cf542c50fef8
challengeType: 5
title: 'Problem 121: Disc game prize fund'
videoUrl: ''
forumTopicId: 301748
localeTitle: 'Задача 121: Призовой фонд призовой игры'
---
## Description
<section id="description"> Сумка содержит один красный диск и один синий диск. В азартной игре игрок берет диск в случайном порядке, и его цвет отмечается. После каждого поворота диск возвращается в сумку, добавляется дополнительный красный диск, а другой диск берется произвольно. Игрок платит 1 фунт за игру и выигрывает, если в конце игры они взяли больше синих дисков, чем красные диски. Если игра будет сыграна на четыре оборота, вероятность выигрыша игрока будет равна 11/120, и поэтому максимальный призовой фонд, который банкир должен выделить для победы в этой игре, составит 10 фунтов стерлингов, прежде чем они ожидают, что они понесут убыток. Обратите внимание, что любая выплата будет целым числом фунтов, а также включает первоначальную £ 1, выплаченную за игру, поэтому в примере, когда игрок фактически выигрывает 9 фунтов. Найдите максимальный призовой фонд, который должен быть выделен для одной игры, в которой исполняется пятнадцать ходов. </section>
<section id='description'>
Сумка содержит один красный диск и один синий диск. В азартной игре игрок берет диск в случайном порядке, и его цвет отмечается. После каждого поворота диск возвращается в сумку, добавляется дополнительный красный диск, а другой диск берется произвольно. Игрок платит 1 фунт за игру и выигрывает, если в конце игры они взяли больше синих дисков, чем красные диски. Если игра будет сыграна на четыре оборота, вероятность выигрыша игрока будет равна 11/120, и поэтому максимальный призовой фонд, который банкир должен выделить для победы в этой игре, составит 10 фунтов стерлингов, прежде чем они ожидают, что они понесут убыток. Обратите внимание, что любая выплата будет целым числом фунтов, а также включает первоначальную £ 1, выплаченную за игру, поэтому в примере, когда игрок фактически выигрывает 9 фунтов. Найдите максимальный призовой фонд, который должен быть выделен для одной игры, в которой исполняется пятнадцать ходов.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 121: Призовой фонд призовой иг
```yml
tests:
- text: <code>euler121()</code> должен вернуть 2269.
testString: 'assert.strictEqual(euler121(), 2269, "<code>euler121()</code> should return 2269.");'
- text: <code>euler121()</code> should return 2269.
testString: assert.strictEqual(euler121(), 2269);
```
@@ -42,8 +45,6 @@ euler121();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler121();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e61000cf542c50fef9
challengeType: 5
title: 'Problem 122: Efficient exponentiation'
videoUrl: ''
forumTopicId: 301749
localeTitle: 'Задача 122: Эффективное возведение в степень'
---
## Description
<section id="description"> Самый наивный способ вычисления n15 требует четырнадцати умножений: n × n × ... × n = n15 Но используя «двоичный» метод, вы можете вычислить его в шести умножениях: n × n = n2n2 × n2 = n4n4 × n4 = n8n8 × n4 = n12n12 × n2 = n14n14 × n = n15 Однако еще можно вычислить его только в пяти умножениях: n × n = n2n2 × n = n3n3 × n3 = n6n6 × n6 = n12n12 × n3 = n15 Определим m (k) - минимальное количество умножений для вычисления nk; например m (15) = 5. Для 1 ≤ k ≤ 200 найдите Σ m (k). </section>
<section id='description'>
Самый наивный способ вычисления n15 требует четырнадцати умножений: n × n × ... × n = n15 Но используя «двоичный» метод, вы можете вычислить его в шести умножениях: n × n = n2n2 × n2 = n4n4 × n4 = n8n8 × n4 = n12n12 × n2 = n14n14 × n = n15 Однако еще можно вычислить его только в пяти умножениях: n × n = n2n2 × n = n3n3 × n3 = n6n6 × n6 = n12n12 × n3 = n15 Определим m (k) - минимальное количество умножений для вычисления nk; например m (15) = 5. Для 1 ≤ k ≤ 200 найдите Σ m (k).
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 122: Эффективное возведение в
```yml
tests:
- text: <code>euler122()</code> должен вернуть 1582.
testString: 'assert.strictEqual(euler122(), 1582, "<code>euler122()</code> should return 1582.");'
- text: <code>euler122()</code> should return 1582.
testString: assert.strictEqual(euler122(), 1582);
```
@@ -42,8 +45,6 @@ euler122();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler122();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e71000cf542c50fefa
challengeType: 5
title: 'Problem 123: Prime square remainders'
videoUrl: ''
forumTopicId: 301750
localeTitle: 'Задача 123: остатки Prime Square'
---
## Description
<section id="description"> Пусть pn - n-е число простых чисел: 2, 3, 5, 7, 11, ... и r - остаток, когда (pn-1) n + (pn + 1) n делится на pn2. Например, когда n = 3, p3 = 5 и 43 + 63 = 280 ≡ 5 mod 25. Наименьшее значение n, для которого остаток сначала превышает 109, составляет 7037. Найдите наименьшее значение n, для которого остаток сначала превышает 1010. </section>
<section id='description'>
Пусть pn - n-е число простых чисел: 2, 3, 5, 7, 11, ... и r - остаток, когда (pn-1) n + (pn + 1) n делится на pn2. Например, когда n = 3, p3 = 5 и 43 + 63 = 280 ≡ 5 mod 25. Наименьшее значение n, для которого остаток сначала превышает 109, составляет 7037. Найдите наименьшее значение n, для которого остаток сначала превышает 1010.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 123: остатки Prime Square'
```yml
tests:
- text: <code>euler123()</code> должен вернуть 21035.
testString: 'assert.strictEqual(euler123(), 21035, "<code>euler123()</code> should return 21035.");'
- text: <code>euler123()</code> should return 21035.
testString: assert.strictEqual(euler123(), 21035);
```
@@ -42,8 +45,6 @@ euler123();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler123();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e81000cf542c50fefb
challengeType: 5
title: 'Problem 124: Ordered radicals'
videoUrl: ''
forumTopicId: 301751
localeTitle: 'Задача 124: упорядоченные радикалы'
---
## Description
<section id="description"> Радиус n, rad (n), является произведением различных простых множителей n. Например, 504 = 23 × 32 × 7, поэтому rad (504) = 2 × 3 × 7 = 42. Если мы вычисляем rad (n) для 1 ≤ n ≤ 10, то сортируем их по rad (n) и сортируем на n, если радикальные значения равны, получаем: Unsorted <p> Сортированный n rad (n) </p><p> n rad (n) k 11 </p><p> 111 22 </p><p> 222 33 </p><p> 423 42 </p><p> 824 55 </p><p> 335 66 </p><p> 936 77 </p><p> 557 82 </p><p> 668 93 </p><p> 779 1010 </p><p> 101010 Пусть E (k) - k-й элемент в отсортированном n столбце; например, E (4) = 8 и E (6) = 9. Если rad (n) сортируется для 1 ≤ n ≤ 100000, найдите E (10000). </p></section>
<section id='description'>
Радиус n, rad (n), является произведением различных простых множителей n. Например, 504 = 23 × 32 × 7, поэтому rad (504) = 2 × 3 × 7 = 42. Если мы вычисляем rad (n) для 1 ≤ n ≤ 10, то сортируем их по rad (n) и сортируем на n, если радикальные значения равны, получаем: Unsorted <p> Сортированный n rad (n) </p><p> n rad (n) k 11 </p><p> 111 22 </p><p> 222 33 </p><p> 423 42 </p><p> 824 55 </p><p> 335 66 </p><p> 936 77 </p><p> 557 82 </p><p> 668 93 </p><p> 779 1010 </p><p> 101010 Пусть E (k) - k-й элемент в отсортированном n столбце; например, E (4) = 8 и E (6) = 9. Если rad (n) сортируется для 1 ≤ n ≤ 100000, найдите E (10000). </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 124: упорядоченные радикалы'
```yml
tests:
- text: <code>euler124()</code> должен возвращать 21417.
testString: 'assert.strictEqual(euler124(), 21417, "<code>euler124()</code> should return 21417.");'
- text: <code>euler124()</code> should return 21417.
testString: assert.strictEqual(euler124(), 21417);
```
@@ -42,8 +45,6 @@ euler124();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler124();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3e91000cf542c50fefc
challengeType: 5
title: 'Problem 125: Palindromic sums'
videoUrl: ''
forumTopicId: 301752
localeTitle: 'Задача 125: Палиндромические суммы'
---
## Description
<section id="description"> Палиндромный номер 595 интересен тем, что его можно записать в виде суммы последовательных квадратов: 62 + 72 + 82 + 92 + 102 + 112 + 122. В точности одиннадцать палиндромов ниже одной тысячи, которые могут быть записаны как последовательные квадратные суммы, и сумма этих палиндромов равна 4164. Заметим, что 1 = 02 + 12 не было включено, так как эта проблема связана с квадратами положительных целых чисел. Найдите сумму всех чисел менее 108, которые являются палиндромными и могут быть записаны как сумма последовательных квадратов. </section>
<section id='description'>
Палиндромный номер 595 интересен тем, что его можно записать в виде суммы последовательных квадратов: 62 + 72 + 82 + 92 + 102 + 112 + 122. В точности одиннадцать палиндромов ниже одной тысячи, которые могут быть записаны как последовательные квадратные суммы, и сумма этих палиндромов равна 4164. Заметим, что 1 = 02 + 12 не было включено, так как эта проблема связана с квадратами положительных целых чисел. Найдите сумму всех чисел менее 108, которые являются палиндромными и могут быть записаны как сумма последовательных квадратов.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 125: Палиндромические суммы'
```yml
tests:
- text: <code>euler125()</code> должен возвращать 2906969179.
testString: 'assert.strictEqual(euler125(), 2906969179, "<code>euler125()</code> should return 2906969179.");'
- text: <code>euler125()</code> should return 2906969179.
testString: assert.strictEqual(euler125(), 2906969179);
```
@@ -42,8 +45,6 @@ euler125();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler125();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3ea1000cf542c50fefd
challengeType: 5
title: 'Problem 126: Cuboid layers'
videoUrl: ''
forumTopicId: 301753
localeTitle: 'Задача 126: Кубоидные слои'
---
## Description
<section id="description"> Минимальное количество кубов для покрытия каждой видимой поверхности на кубоиде размером 3 x 2 x 1 составляет двадцать два. <p> Если мы затем добавим второй слой в это твердое тело, для покрытия каждой видимой поверхности потребуется сорок шесть кубов, для третьего слоя потребуется семьдесят восемь кубов, а четвертому слою потребуется сто восемнадцать кубов, чтобы покрыть каждую видимую грань , Однако первый слой на кубоиде размером 5 х 1 х 1 также требует двадцать два куба; аналогично, первый слой на кубоидах размером 5 x 3 x 1, 7 x 2 x 1 и 11 x 1 x 1 содержит сорок шесть кубов. Мы определим C (n) для представления числа кубоидов, содержащих n кубов в одном из своих слоев. Таким образом, C (22) = 2, C (46) = 4, C (78) = 5 и C (118) = 8. Оказывается, что 154 - наименьшее значение n, для которого C (n) = 10. Найдите наименьшее значение n, для которого C (n) = 1000. </p></section>
<section id='description'>
Минимальное количество кубов для покрытия каждой видимой поверхности на кубоиде размером 3 x 2 x 1 составляет двадцать два. <p> Если мы затем добавим второй слой в это твердое тело, для покрытия каждой видимой поверхности потребуется сорок шесть кубов, для третьего слоя потребуется семьдесят восемь кубов, а четвертому слою потребуется сто восемнадцать кубов, чтобы покрыть каждую видимую грань , Однако первый слой на кубоиде размером 5 х 1 х 1 также требует двадцать два куба; аналогично, первый слой на кубоидах размером 5 x 3 x 1, 7 x 2 x 1 и 11 x 1 x 1 содержит сорок шесть кубов. Мы определим C (n) для представления числа кубоидов, содержащих n кубов в одном из своих слоев. Таким образом, C (22) = 2, C (46) = 4, C (78) = 5 и C (118) = 8. Оказывается, что 154 - наименьшее значение n, для которого C (n) = 10. Найдите наименьшее значение n, для которого C (n) = 1000. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 126: Кубоидные слои'
```yml
tests:
- text: <code>euler126()</code> должен вернуть 18522.
testString: 'assert.strictEqual(euler126(), 18522, "<code>euler126()</code> should return 18522.");'
- text: <code>euler126()</code> should return 18522.
testString: assert.strictEqual(euler126(), 18522);
```
@@ -42,8 +45,6 @@ euler126();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler126();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3ec1000cf542c50fefe
challengeType: 5
title: 'Problem 127: abc-hits'
videoUrl: ''
forumTopicId: 301754
localeTitle: 'Задача 127: abc-hits'
---
## Description
<section id="description"> Радикал n, rad (n), является произведением различных простых множителей n. Например, 504 = 23 × 32 × 7, поэтому rad (504) = 2 × 3 × 7 = 42. Мы определим триплет положительных целых чисел (a, b, c) как abc-hit, если: GCD ( a, b) = GCD (a, c) = GCD (b, c) = 1 a &lt;ba + b = c rad (abc) &lt;c Например, (5, 27, 32) является abc-hit, потому что : GCD (5, 27) = GCD (5, 32) = GCD (27, 32) = 1 5 &lt;27 5 + 27 = 32 рад (4320) = 30 &lt;32 Оказывается, abc-хиты довольно редки и существует только тридцать один abc-хиты для c &lt;1000, с Σc = 12523. Найдите Σc для c &lt;120000. </section>
<section id='description'>
Радикал n, rad (n), является произведением различных простых множителей n. Например, 504 = 23 × 32 × 7, поэтому rad (504) = 2 × 3 × 7 = 42. Мы определим триплет положительных целых чисел (a, b, c) как abc-hit, если: GCD ( a, b) = GCD (a, c) = GCD (b, c) = 1 a &lt;ba + b = c rad (abc) &lt;c Например, (5, 27, 32) является abc-hit, потому что : GCD (5, 27) = GCD (5, 32) = GCD (27, 32) = 1 5 &lt;27 5 + 27 = 32 рад (4320) = 30 &lt;32 Оказывается, abc-хиты довольно редки и существует только тридцать один abc-хиты для c &lt;1000, с Σc = 12523. Найдите Σc для c &lt;120000.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 127: abc-hits'
```yml
tests:
- text: <code>euler127()</code> должен вернуть 18407904.
testString: 'assert.strictEqual(euler127(), 18407904, "<code>euler127()</code> should return 18407904.");'
- text: <code>euler127()</code> should return 18407904.
testString: assert.strictEqual(euler127(), 18407904);
```
@@ -42,8 +45,6 @@ euler127();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler127();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3ec1000cf542c50feff
challengeType: 5
title: 'Problem 128: Hexagonal tile differences'
videoUrl: ''
forumTopicId: 301755
localeTitle: 'Задача 128: Различия в гексагональной черепице'
---
## Description
<section id="description"> Шестиугольная плитка с номером 1 окружена кольцом шести гексагональных плит, начиная с «12 часов» и пронумеровав плитки с 2 по 7 против часовой стрелки. Таким же образом добавляются новые кольца, причем следующие кольца имеют номера от 8 до 19, от 20 до 37, от 38 до 61 и т. Д. На приведенной ниже диаграмме показаны первые три кольца. <p> Найдя разницу между плиткой n и каждым из ее шести соседей, мы определим PD (n) как число тех различий, которые являются первичными. Например, работая по часовой стрелке вокруг плитки 8, разница составляет 12, 29, 11, 6, 1 и 13. Таким образом, PD (8) = 3. Таким же образом различия вокруг плитки 17 равны 1, 17, 16, 1 , 11 и 10, следовательно, PD (17) = 2. Можно показать, что максимальное значение PD (n) равно 3. Если все плитки, для которых PD (n) = 3, указаны в порядке возрастания, чтобы сформировать последовательность, 10-я плитка будет 271. Найдите 2000-ю черепицу в этой последовательности. </p></section>
<section id='description'>
Шестиугольная плитка с номером 1 окружена кольцом шести гексагональных плит, начиная с «12 часов» и пронумеровав плитки с 2 по 7 против часовой стрелки. Таким же образом добавляются новые кольца, причем следующие кольца имеют номера от 8 до 19, от 20 до 37, от 38 до 61 и т. Д. На приведенной ниже диаграмме показаны первые три кольца. <p> Найдя разницу между плиткой n и каждым из ее шести соседей, мы определим PD (n) как число тех различий, которые являются первичными. Например, работая по часовой стрелке вокруг плитки 8, разница составляет 12, 29, 11, 6, 1 и 13. Таким образом, PD (8) = 3. Таким же образом различия вокруг плитки 17 равны 1, 17, 16, 1 , 11 и 10, следовательно, PD (17) = 2. Можно показать, что максимальное значение PD (n) равно 3. Если все плитки, для которых PD (n) = 3, указаны в порядке возрастания, чтобы сформировать последовательность, 10-я плитка будет 271. Найдите 2000-ю черепицу в этой последовательности. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 128: Различия в гексагональной
```yml
tests:
- text: <code>euler128()</code> должен возвращать 14516824220.
testString: 'assert.strictEqual(euler128(), 14516824220, "<code>euler128()</code> should return 14516824220.");'
- text: <code>euler128()</code> should return 14516824220.
testString: assert.strictEqual(euler128(), 14516824220);
```
@@ -42,8 +45,6 @@ euler128();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler128();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3ef1000cf542c50ff01
challengeType: 5
title: 'Problem 129: Repunit divisibility'
videoUrl: ''
forumTopicId: 301756
localeTitle: 'Задача 129: делимость репликации'
---
## Description
<section id="description"> Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k; например, R (6) = 111111. Учитывая, что n является положительным целым числом, а GCD (n, 10) = 1, можно показать, что всегда существует значение k, для которого R (k) делится на n , и пусть A (n) - наименьшее такое значение k; например, A (7) = 6 и A (41) = 5. Наименьшее значение n, для которого A (n) сначала превышает десять, равно 17. Найдите наименьшее значение n, для которого A (n) млн. </section>
<section id='description'>
Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k; например, R (6) = 111111. Учитывая, что n является положительным целым числом, а GCD (n, 10) = 1, можно показать, что всегда существует значение k, для которого R (k) делится на n , и пусть A (n) - наименьшее такое значение k; например, A (7) = 6 и A (41) = 5. Наименьшее значение n, для которого A (n) сначала превышает десять, равно 17. Найдите наименьшее значение n, для которого A (n) млн.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 129: делимость репликации'
```yml
tests:
- text: <code>euler129()</code> должен возвращать 1000023.
testString: 'assert.strictEqual(euler129(), 1000023, "<code>euler129()</code> should return 1000023.");'
- text: <code>euler129()</code> should return 1000023.
testString: assert.strictEqual(euler129(), 1000023);
```
@@ -42,8 +45,6 @@ euler129();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler129();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3ee1000cf542c50ff00
challengeType: 5
title: 'Problem 130: Composites with prime repunit property'
videoUrl: ''
forumTopicId: 301758
localeTitle: 'Задача 130: Композиты с основным свойством repunit'
---
## Description
<section id="description"> Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k; например, R (6) = 111111. Учитывая, что n является положительным целым числом, а GCD (n, 10) = 1, можно показать, что всегда существует значение k, для которого R (k) делится на n , и пусть A (n) - наименьшее такое значение k; например, A (7) = 6 и A (41) = 5. Вам дано, что для всех простых чисел p&gt; 5 p-1 делится на A (p). Например, когда p = 41, A (41) = 5 и 40 делится на 5. Однако имеются редкие составные значения, для которых это также верно; первые пять примеров составляют 91, 259, 451, 481 и 703. Найдите сумму первых двадцати пяти составных значений n, для которых GCD (n, 10) = 1 и n - 1 делится на A (n). </section>
<section id='description'>
Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k; например, R (6) = 111111. Учитывая, что n является положительным целым числом, а GCD (n, 10) = 1, можно показать, что всегда существует значение k, для которого R (k) делится на n , и пусть A (n) - наименьшее такое значение k; например, A (7) = 6 и A (41) = 5. Вам дано, что для всех простых чисел p&gt; 5 p-1 делится на A (p). Например, когда p = 41, A (41) = 5 и 40 делится на 5. Однако имеются редкие составные значения, для которых это также верно; первые пять примеров составляют 91, 259, 451, 481 и 703. Найдите сумму первых двадцати пяти составных значений n, для которых GCD (n, 10) = 1 и n - 1 делится на A (n).
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 130: Композиты с основным свой
```yml
tests:
- text: <code>euler130()</code> должен вернуть 149253.
testString: 'assert.strictEqual(euler130(), 149253, "<code>euler130()</code> should return 149253.");'
- text: <code>euler130()</code> should return 149253.
testString: assert.strictEqual(euler130(), 149253);
```
@@ -42,8 +45,6 @@ euler130();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler130();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3ef1000cf542c50ff02
challengeType: 5
title: 'Problem 131: Prime cube partnership'
videoUrl: ''
forumTopicId: 301759
localeTitle: 'Задача 131: Партнерство с премьер-кубом'
---
## Description
<section id="description"> Имеются некоторые простые значения p, для которых существует натуральное число n, такое, что выражение n3 + n2p является совершенным кубом. Например, когда p = 19, 83 + 82 × 19 = 123. Что, пожалуй, наиболее удивительно, так это то, что для каждого числа с этим свойством значение n уникально, и только четыре таких простых числа ниже ста. Сколько простых чисел ниже одного миллиона имеют это замечательное свойство? </section>
<section id='description'>
Имеются некоторые простые значения p, для которых существует натуральное число n, такое, что выражение n3 + n2p является совершенным кубом. Например, когда p = 19, 83 + 82 × 19 = 123. Что, пожалуй, наиболее удивительно, так это то, что для каждого числа с этим свойством значение n уникально, и только четыре таких простых числа ниже ста. Сколько простых чисел ниже одного миллиона имеют это замечательное свойство?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 131: Партнерство с премьер-куб
```yml
tests:
- text: <code>euler131()</code> должен вернуть 173.
testString: 'assert.strictEqual(euler131(), 173, "<code>euler131()</code> should return 173.");'
- text: <code>euler131()</code> should return 173.
testString: assert.strictEqual(euler131(), 173);
```
@@ -42,8 +45,6 @@ euler131();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler131();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3f11000cf542c50ff03
challengeType: 5
title: 'Problem 132: Large repunit factors'
videoUrl: ''
forumTopicId: 301760
localeTitle: 'Задача 132: Большие факторы репутации'
---
## Description
<section id="description"> Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k. Например, R (10) = 1111111111 = 11 × 41 × 271 × 9091, а сумма этих простых коэффициентов равна 9414. Найдите сумму первых сорока простых множителей R (109). </section>
<section id='description'>
Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k. Например, R (10) = 1111111111 = 11 × 41 × 271 × 9091, а сумма этих простых коэффициентов равна 9414. Найдите сумму первых сорока простых множителей R (109).
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 132: Большие факторы репутации
```yml
tests:
- text: <code>euler132()</code> должен возвращать 843296.
testString: 'assert.strictEqual(euler132(), 843296, "<code>euler132()</code> should return 843296.");'
- text: <code>euler132()</code> should return 843296.
testString: assert.strictEqual(euler132(), 843296);
```
@@ -42,8 +45,6 @@ euler132();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler132();
```js
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 5900f3f21000cf542c50ff04
challengeType: 5
title: 'Problem 133: Repunit nonfactors'
videoUrl: ''
forumTopicId: 301761
localeTitle: 'Задача 133: Рефанирование нефакторов'
---
## Description
<section id="description"> Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k; например, R (6) = 111111. Рассмотрим репутации вида R (10n). Хотя R (10), R (100) или R (1000) не делятся на 17, R (10000) делится на 17. Но не существует значения n, для которого R (10n) будет делить на 19. В факт, замечательно, что 11, 17, 41 и 73 являются единственными четырьмя штрихами ниже ста, которые могут быть фактором R (10n). Найдите сумму всех простых чисел ниже ста тысяч, которые никогда не будут фактором R (10n). </section>
<section id='description'>
Число, состоящее полностью из них, называется repunit. Определим R (k) как репутацию длины k; например, R (6) = 111111. Рассмотрим репутации вида R (10n). Хотя R (10), R (100) или R (1000) не делятся на 17, R (10000) делится на 17. Но не существует значения n, для которого R (10n) будет делить на 19. В факт, замечательно, что 11, 17, 41 и 73 являются единственными четырьмя штрихами ниже ста, которые могут быть фактором R (10n). Найдите сумму всех простых чисел ниже ста тысяч, которые никогда не будут фактором R (10n).
</section>
## Instructions
undefined
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert.strictEqual(euler133(), 453647705, "<code>euler133()</code> should return 453647705.");'
- text: <code>euler133()</code> should return 453647705.
testString: assert.strictEqual(euler133(), 453647705);
```
@@ -41,8 +45,6 @@ euler133();
</div>
</section>
## Solution
@@ -51,4 +53,5 @@ euler133();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,20 @@
id: 5900f3f21000cf542c50ff05
challengeType: 5
title: 'Problem 134: Prime pair connection'
videoUrl: ''
forumTopicId: 301762
localeTitle: 'Проблема 134: Соединение с главной парой'
---
## Description
undefined
<section id='description'>
Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p1 whilst also being divisible by p2.
In fact, with the exception of p1 = 3 and p2 = 5, for every pair of consecutive primes, p2 > p1, there exist values of n for which the last digits are formed by p1 and n is divisible by p2. Let S be the smallest of these values of n.
Find ∑ S for every pair of consecutive primes with 5 ≤ p1 ≤ 1000000.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +23,8 @@ undefined
```yml
tests:
- text: <code>euler134()</code> должен вернуть 18613426663617120.
testString: 'assert.strictEqual(euler134(), 18613426663617120, "<code>euler134()</code> should return 18613426663617120.");'
- text: <code>euler134()</code> should return 18613426663617120.
testString: assert.strictEqual(euler134(), 18613426663617120);
```
@@ -42,8 +47,6 @@ euler134();
</div>
</section>
## Solution
@@ -52,4 +55,5 @@ euler134();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3f31000cf542c50ff06
challengeType: 5
title: 'Problem 135: Same differences'
videoUrl: ''
forumTopicId: 301763
localeTitle: 'Проблема 135: Те же различия'
---
## Description
<section id="description"> Для положительных целых чисел x, y и z являются последовательными членами арифметической прогрессии, наименьшее значение натурального числа n, для которого уравнение x2 - y2 - z2 = n имеет ровно два решения: n = 27: 342 - 272 - 202 = 122 - 92 - 62 = 27 Оказывается, что n = 1155 является наименьшим значением, которое имеет ровно десять решений. Сколько значений n менее одного миллиона имеет ровно десять различных решений? </section>
<section id='description'>
Для положительных целых чисел x, y и z являются последовательными членами арифметической прогрессии, наименьшее значение натурального числа n, для которого уравнение x2 - y2 - z2 = n имеет ровно два решения: n = 27: 342 - 272 - 202 = 122 - 92 - 62 = 27 Оказывается, что n = 1155 является наименьшим значением, которое имеет ровно десять решений. Сколько значений n менее одного миллиона имеет ровно десять различных решений?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Проблема 135: Те же различия'
```yml
tests:
- text: <code>euler135()</code> должен вернуть 4989.
testString: 'assert.strictEqual(euler135(), 4989, "<code>euler135()</code> should return 4989.");'
- text: <code>euler135()</code> should return 4989.
testString: assert.strictEqual(euler135(), 4989);
```
@@ -42,8 +45,6 @@ euler135();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler135();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3f51000cf542c50ff07
challengeType: 5
title: 'Problem 136: Singleton difference'
videoUrl: ''
forumTopicId: 301764
localeTitle: 'Задача 136: разность Синглтона'
---
## Description
<section id="description"> Положительные целые числа x, y и z являются последовательными членами арифметической прогрессии. Учитывая, что n является положительным целым числом, уравнение x2 - y2 - z2 = n имеет ровно одно решение, когда n = 20: 132 - 102 - 72 = 20 Фактически, существует двадцать пять значений n ниже ста, для которых уравнение имеет единственное решение. Сколько значений n менее пятидесяти миллионов имеет ровно одно решение? </section>
<section id='description'>
Положительные целые числа x, y и z являются последовательными членами арифметической прогрессии. Учитывая, что n является положительным целым числом, уравнение x2 - y2 - z2 = n имеет ровно одно решение, когда n = 20: 132 - 102 - 72 = 20 Фактически, существует двадцать пять значений n ниже ста, для которых уравнение имеет единственное решение. Сколько значений n менее пятидесяти миллионов имеет ровно одно решение?
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 136: разность Синглтона'
```yml
tests:
- text: <code>euler136()</code> должен вернуть 2544559.
testString: 'assert.strictEqual(euler136(), 2544559, "<code>euler136()</code> should return 2544559.");'
- text: <code>euler136()</code> should return 2544559.
testString: assert.strictEqual(euler136(), 2544559);
```
@@ -42,8 +45,6 @@ euler136();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler136();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3f51000cf542c50ff08
challengeType: 5
title: 'Problem 137: Fibonacci golden nuggets'
videoUrl: ''
forumTopicId: 301765
localeTitle: 'Задача 137: золотые самородки Фибоначчи'
---
## Description
<section id="description"> Рассмотрим бесконечный полиномиальный ряд AF (x) = xF1 + x2F2 + x3F3 + ..., где Fk - k-й член в последовательности Фибоначчи: 1, 1, 2, 3, 5, 8, ...; то есть Fk = Fk-1 + Fk-2, F1 = 1 и F2 = 1. Для этой задачи нас будут интересовать значения x, для которых AF (x) является натуральным числом. Удивительно, что AF (1/2) = (1/2) .1 + (1/2) 2,1 + (1/2) 3,2 + (1/2) 4,3 + (1/2) 5,5 + ... <p> = 1/2 + 1/4 + 2/8 + 3/16 + 5/32 + ... </p><p> = 2 Соответствующие значения x для первых пяти натуральных чисел показаны ниже. </p><p> xAF (x) √2-11 1/22 (√13-2) / 33 (√89-5) / 84 (√34-3) / 55 </p><p> Будем называть AF (x) золотым саморождением, если x рационально, потому что они становятся все реже; например, 10-й золотой самородок - 74049690. Найдите 15-й золотой самородок. </p></section>
<section id='description'>
Рассмотрим бесконечный полиномиальный ряд AF (x) = xF1 + x2F2 + x3F3 + ..., где Fk - k-й член в последовательности Фибоначчи: 1, 1, 2, 3, 5, 8, ...; то есть Fk = Fk-1 + Fk-2, F1 = 1 и F2 = 1. Для этой задачи нас будут интересовать значения x, для которых AF (x) является натуральным числом. Удивительно, что AF (1/2) = (1/2) .1 + (1/2) 2,1 + (1/2) 3,2 + (1/2) 4,3 + (1/2) 5,5 + ... <p> = 1/2 + 1/4 + 2/8 + 3/16 + 5/32 + ... </p><p> = 2 Соответствующие значения x для первых пяти натуральных чисел показаны ниже. </p><p> xAF (x) √2-11 1/22 (√13-2) / 33 (√89-5) / 84 (√34-3) / 55 </p><p> Будем называть AF (x) золотым саморождением, если x рационально, потому что они становятся все реже; например, 10-й золотой самородок - 74049690. Найдите 15-й золотой самородок. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 137: золотые самородки Фибонач
```yml
tests:
- text: <code>euler137()</code> должен вернуть 1120149658760.
testString: 'assert.strictEqual(euler137(), 1120149658760, "<code>euler137()</code> should return 1120149658760.");'
- text: <code>euler137()</code> should return 1120149658760.
testString: assert.strictEqual(euler137(), 1120149658760);
```
@@ -42,8 +45,6 @@ euler137();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler137();
```js
// solution required
```
</section>

View File

@@ -2,15 +2,18 @@
id: 5900f3f61000cf542c50ff09
challengeType: 5
title: 'Problem 138: Special isosceles triangles'
videoUrl: ''
forumTopicId: 301766
localeTitle: 'Задача 138: Специальные равнобедренные треугольники'
---
## Description
<section id="description"> Рассмотрим равнобедренный треугольник с длиной основания, b = 16 и ногами, L = 17. <p> Используя теорему Пифагора, можно видеть, что высота треугольника h = √ (172 - 82) = 15, что на единицу меньше базовой длины. При b = 272 и L = 305 мы получаем h = 273, что больше, чем базовая длина, и это второй наименьший равнобедренный треугольник со свойством h = b ± 1. Найти Σ L для двенадцати наименьших равнобедренных треугольники, для которых h = b ± 1 и b, L - натуральные числа. </p></section>
<section id='description'>
Рассмотрим равнобедренный треугольник с длиной основания, b = 16 и ногами, L = 17. <p> Используя теорему Пифагора, можно видеть, что высота треугольника h = √ (172 - 82) = 15, что на единицу меньше базовой длины. При b = 272 и L = 305 мы получаем h = 273, что больше, чем базовая длина, и это второй наименьший равнобедренный треугольник со свойством h = b ± 1. Найти Σ L для двенадцати наименьших равнобедренных треугольники, для которых h = b ± 1 и b, L - натуральные числа. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,8 +21,8 @@ localeTitle: 'Задача 138: Специальные равнобедренн
```yml
tests:
- text: <code>euler138()</code> должен вернуть 1118049290473932.
testString: 'assert.strictEqual(euler138(), 1118049290473932, "<code>euler138()</code> should return 1118049290473932.");'
- text: <code>euler138()</code> should return 1118049290473932.
testString: assert.strictEqual(euler138(), 1118049290473932);
```
@@ -42,8 +45,6 @@ euler138();
</div>
</section>
## Solution
@@ -52,4 +53,5 @@ euler138();
```js
// solution required
```
</section>

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