fix(curriculum): fix challenges for russian language

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

View File

@@ -2,15 +2,18 @@
title: 100 doors
id: 594810f028c0303b75339acb
challengeType: 5
videoUrl: ''
forumTopicId: 302217
localeTitle: 100 дверей
---
## Description
<section id="description"><p> Есть 100 дверей подряд, все изначально закрыты. Вы делаете 100 проходов у дверей. В первый раз, зайдите в каждую дверь и «переключите» дверь (если дверь закрыта, откройте ее, если она открыта, закройте ее). Во второй раз заходите только к каждой второй двери (т. Е. К двери №2, №4, №6, ...) и переключите ее. В третий раз посетите каждую 3-ю дверь (т. Е. Дверь № 3, №6, №9, ...) и т. Д., Пока вы не посетите только 100-ю дверь. </p><p> Внедрите функцию определения состояния дверей после последнего прохода. Верните конечный результат в массив, только если номер двери включен в массив, если он открыт. </p></section>
<section id='description'>
<p> Есть 100 дверей подряд, все изначально закрыты. Вы делаете 100 проходов у дверей. В первый раз, зайдите в каждую дверь и «переключите» дверь (если дверь закрыта, откройте ее, если она открыта, закройте ее). Во второй раз заходите только к каждой второй двери (т. Е. К двери №2, №4, №6, ...) и переключите ее. В третий раз посетите каждую 3-ю дверь (т. Е. Дверь № 3, №6, №9, ...) и т. Д., Пока вы не посетите только 100-ю дверь. </p><p> Внедрите функцию определения состояния дверей после последнего прохода. Верните конечный результат в массив, только если номер двери включен в массив, если он открыт. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.
</section>
## Tests
@@ -18,12 +21,12 @@ localeTitle: 100 дверей
```yml
tests:
- text: <code>getFinalOpenedDoors</code> - это функция.
testString: 'assert(typeof getFinalOpenedDoors === "function", "<code>getFinalOpenedDoors</code> is a function.");'
- text: <code>getFinalOpenedDoors</code> должен возвращать массив.
testString: 'assert(Array.isArray(getFinalOpenedDoors(100)), "<code>getFinalOpenedDoors</code> should return an array.");'
- text: <code>getFinalOpenedDoors</code> не <code>getFinalOpenedDoors</code> правильных результатов.
testString: 'assert.deepEqual(getFinalOpenedDoors(100), solution, "<code>getFinalOpenedDoors</code> did not produce the correct results.");'
- text: <code>getFinalOpenedDoors</code> is a function.
testString: assert(typeof getFinalOpenedDoors === 'function');
- text: <code>getFinalOpenedDoors</code> should return an array.
testString: assert(Array.isArray(getFinalOpenedDoors(100)));
- text: <code>getFinalOpenedDoors</code> did not produce the correct results.
testString: assert.deepEqual(getFinalOpenedDoors(100), solution);
```
@@ -35,7 +38,7 @@ tests:
<div id='js-seed'>
```js
function getFinalOpenedDoors (numDoors) {
function getFinalOpenedDoors(numDoors) {
// Good luck!
}
@@ -43,12 +46,12 @@ function getFinalOpenedDoors (numDoors) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const solution = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];
```
</div>
@@ -59,6 +62,17 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function getFinalOpenedDoors(numDoors) {
// this is the final pattern (always squares).
// thus, the most efficient solution simply returns an array of squares up to numDoors).
const finalState = [];
let i = 1;
while (Math.pow(i, 2) <= numDoors) {
finalState.push(Math.pow(i, 2));
i++;
}
return finalState;
}
```
</section>

View File

@@ -2,15 +2,33 @@
title: 24 game
id: 5951e88f64ebf159166a1176
challengeType: 5
videoUrl: ''
forumTopicId: 302218
localeTitle: 24 игра
---
## Description
<section id="description"><p> Реализуйте функцию, которая принимает в качестве аргумента строку из четырех цифр: каждая цифра от 1 ──► 9 (включительно) с разрешенными повторениями и возвращает арифметическое выражение, которое оценивается с номером 24. Если такого решения не существует, не существует никакого решения ». </p><p> Правила: </p> Допускаются только следующие операторы / функции: умножение, деление, сложение, вычитание. Отдел должен использовать с плавающей точкой или рациональную арифметику и т. Д. Для сохранения остатков. Формирование нескольких цифр из предоставленных цифр не разрешено. (Таким образом, ответ 12 + 12 при наличии 1, 2, 2 и 1 неверен). Порядок цифр, когда они указаны, не обязательно сохраняется. <p> Пример ввода: </p> <code>solve24(&quot;4878&quot;);</code> <code>solve24(&quot;1234&quot;);</code> <code>solve24(&quot;6789&quot;);</code> <code>solve24(&quot;1127&quot;);</code> <p> Пример выходов (строк): </p> <code>(7-8/8)*4</code> <code>3*1*4*2</code> <code>(6*8)/(9-7)</code> <code>(1+7)*(2+1)</code> </section>
<section id='description'>
<p> Реализуйте функцию, которая принимает в качестве аргумента строку из четырех цифр: каждая цифра от 1 ──► 9 (включительно) с разрешенными повторениями и возвращает арифметическое выражение, которое оценивается с номером 24. Если такого решения не существует, не существует никакого решения ». </p><p> Правила: </p> Допускаются только следующие операторы / функции: умножение, деление, сложение, вычитание. Отдел должен использовать с плавающей точкой или рациональную арифметику и т. Д. Для сохранения остатков. Формирование нескольких цифр из предоставленных цифр не разрешено. (Таким образом, ответ 12 + 12 при наличии 1, 2, 2 и 1 неверен). Порядок цифр, когда они указаны, не обязательно сохраняется. <p> Пример ввода: </p> <code>solve24(&quot;4878&quot;);</code> <code>solve24(&quot;1234&quot;);</code> <code>solve24(&quot;6789&quot;);</code> <code>solve24(&quot;1127&quot;);</code> <p> Пример выходов (строк): </p> <code>(7-8/8)*4</code> <code>3*1*4*2</code> <code>(6*8)/(9-7)</code> <code>(1+7)*(2+1)</code>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function that takes a string of four digits as its argument, with each digit from 1 to 9 (inclusive) with repetitions allowed, and returns an arithmetic expression that evaluates to the number 24. If no such solution exists, return "no solution exists".
<h4><strong>Rules:</strong></h4>
<ul>
<li> Only the following operators/functions are allowed: multiplication, division, addition, subtraction. </li>
<li> Division should use floating point or rational arithmetic, etc, to preserve remainders. </li>
<li> Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). </li>
<li> The order of the digits when given does not have to be preserved. </li>
</ul>
| Example input | Example output |
| ----------------------------- | ------------------------- |
| <code>solve24("4878");</code> | <code>(7-8/8)\*4</code> |
| <code>solve24("1234");</code> | <code>3_1_4\*2</code> |
| <code>solve24("6789");</code> | <code>(6\*8)/(9-7)</code> |
| <code>solve24("1127");</code> | <code>(1+7)\*(2+1)</code> |
</section>
## Tests
@@ -18,16 +36,16 @@ localeTitle: 24 игра
```yml
tests:
- text: <code>solve24</code> - функция.
testString: 'assert(typeof solve24 === "function", "<code>solve24</code> is a function.");'
- text: <code>solve24(&quot;4878&quot;)</code> должен вернуться <code>(7-8/8)*4</code> или <code>4*(7-8/8)</code>
testString: 'assert(include(answers[0], solve24(testCases[0])), "<code>solve24("4878")</code> should return <code>(7-8/8)*4</code> or <code>4*(7-8/8)</code>");'
- text: <code>solve24(&quot;1234&quot;)</code> должен возвращать любое расположение <code>1*2*3*4</code>
testString: 'assert(include(answers[1], solve24(testCases[1])), "<code>solve24("1234")</code> should return any arrangement of <code>1*2*3*4</code>");'
- text: <code>solve24(&quot;6789&quot;)</code> должен возвращать <code>(6*8)/(9-7)</code> или <code>(8*6)/(9-7)</code>
testString: 'assert(include(answers[2], solve24(testCases[2])), "<code>solve24("6789")</code> should return <code>(6*8)/(9-7)</code> or <code>(8*6)/(9-7)</code>");'
- text: <code>solve24(&quot;1127&quot;)</code> должен возвращать перестановку <code>(1+7)*(1*2)</code>
testString: 'assert(include(answers[3], solve24(testCases[3])), "<code>solve24("1127")</code> should return a permutation of <code>(1+7)*(1*2)</code>");'
- text: <code>solve24</code> is a function.
testString: assert(typeof solve24 === 'function');
- text: <code>solve24("4878")</code> should return <code>(7-8/8)*4</code> or <code>4*(7-8/8)</code>
testString: assert(include(answers[0], solve24(testCases[0])));
- text: <code>solve24("1234")</code> should return any arrangement of <code>1*2*3*4</code>
testString: assert(include(answers[1], solve24(testCases[1])));
- text: <code>solve24("6789")</code> should return <code>(6*8)/(9-7)</code> or <code>(8*6)/(9-7)</code>
testString: assert(include(answers[2], solve24(testCases[2])));
- text: <code>solve24("1127")</code> should return a permutation of <code>(1+7)*(1*2)</code>
testString: assert(include(answers[3], solve24(testCases[3])));
```
@@ -48,12 +66,29 @@ function solve24 (numStr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [
'4878',
'1234',
'6789',
'1127'
];
const answers = [
['(7-8/8)*4', '4*(7-8/8)', '(4-8+7)*8', '(4+7-8)*8', '(7+4-8)*8', '(7-8+4)*8', '8*(4-8+7)', '8*(4+7-8)', '8*(7+4-8)', '8*(7-8+4)'],
['1*2*3*4', '1*2*4*3', '1*3*2*4', '1*3*4*2', '1*4*2*3', '1*4*3*2', '2*1*3*4', '2*1*4*3', '2*3*1*4', '2*3*4*1', '2*4*3*1', '2*4*1*3', '3*1*2*4', '3*1*4*2', '3*2*1*4', '3*2*4*1', '3*4*1*2', '3*4*2*1', '4*1*2*3', '4*1*3*2', '4*2*1*3', '4*2*3*1', '4*3*1*2', '4*3*2*1', '(1+2+3)*4', '(1+3+2)*4', '(2+1+3)*4', '(2+3+1)*4', '(3+1+2)*4', '(3+2+1)*4', '4*(1+2+3)', '4*(2+1+3)', '4*(2+3+1)', '4*(3+1+2)', '4*(3+2+1)'],
['(6*8)/(9-7)', '(8*6)/(9-7)', '6*8/(9-7)', '8*6/(9-7)'],
['(1+7)*(2+1)', '(1+7)*(1+2)', '(1+2)*(1+7)', '(1+2)*(7+1)', '(2+1)*(1+7)', '(7+1)*(2+1)']
];
function include(ansArr, res) {
const index = ansArr.indexOf(res);
return index >= 0;
}
```
</div>
@@ -64,6 +99,75 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// noprotect
function solve24(numStr) {
const digitsArr = numStr.split('');
const answers = [];
const digitPermutations = [];
const operatorPermutations = [];
function generateDigitPermutations (digits, permutations = []) {
if (digits.length === 0) {
digitPermutations.push(permutations);
}
else {
for (let i = 0; i < digits.length; i++) {
const curr = digits.slice();
const next = curr.splice(i, 1);
generateDigitPermutations(curr.slice(), permutations.concat(next));
}
}
}
function generateOperatorPermutations (permutations = []) {
const operators = ['+', '-', '*', '/'];
if (permutations.length === 3) {
operatorPermutations.push(permutations);
}
else {
for (let i = 0; i < operators.length; i++) {
const curr = permutations.slice();
curr.push(operators[i]);
generateOperatorPermutations(curr);
}
}
}
generateDigitPermutations(digitsArr);
generateOperatorPermutations();
interleave();
return answers[0];
function interleave () {
for (let i = 0; i < digitPermutations.length; i++) {
for (let j = 0; j < operatorPermutations.length; j++) {
const d = digitPermutations[i];
const o = operatorPermutations[j];
const perm = [
`${d[0]}${o[0]}${d[1]}${o[1]}${d[2]}${o[2]}${d[3]}`,
`(${d[0]}${o[0]}${d[1]})${o[1]}${d[2]}${o[2]}${d[3]}`,
`${d[0]}${o[0]}(${d[1]}${o[1]}${d[2]})${o[2]}${d[3]}`,
`${d[0]}${o[0]}${d[1]}${o[1]}(${d[2]}${o[2]}${d[3]})`,
`${d[0]}${o[0]}(${d[1]}${o[1]}${d[2]}${o[2]}${d[3]})`,
`(${d[0]}${o[0]}${d[1]}${o[1]}${d[2]})${o[2]}${d[3]}`,
`(${d[0]}${o[0]}${d[1]})${o[1]}(${d[2]}${o[2]}${d[3]})`
];
perm.forEach(combination => {
const res = eval(combination);
if (res === 24) {
return answers.push(combination);
}
});
}
}
}
}
```
</section>

View File

@@ -2,21 +2,24 @@
title: 9 billion names of God the integer
id: 5949b579404977fbaefcd736
challengeType: 5
videoUrl: ''
forumTopicId: 302219
localeTitle: 9 миллиардов имен Бога - целое число
---
## Description
<section id="description"><p> Эта задача - вариация <a href="https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary" title="wp: Девять миллиардов имен Бога # Plot_summary">рассказа Артура Кларка</a> . </p><p> (Решители должны знать о последствиях выполнения этой задачи.) </p><p> Подробно, чтобы указать, что подразумевается под «именем»: </p><p> Целое число 1 имеет 1 имя «1». </p><p> Целое число 2 имеет 2 имени «1 + 1» и «2». </p><p> Целое число 3 имеет 3 имени «1 + 1 + 1», «2 + 1» и «3». </p><p> Целое число 4 имеет 5 имен «1 + 1 + 1 + 1», «2 + 1 + 1», «2 + 2», «3 + 1», «4». </p><p> Целое число 5 имеет 7 имен «1 + 1 + 1 + 1 + 1», «2 + 1 + 1 + 1», «2 + 2 + 1», «3 + 1 + 1», «3 + 2», «4 + 1», «5». </p><p> Это можно визуализировать в следующем виде: </p><pre> 1
<section id='description'>
<p> Эта задача - вариация <a href="https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary" title="wp: Девять миллиардов имен Бога # Plot_summary">рассказа Артура Кларка</a> . </p><p> (Решители должны знать о последствиях выполнения этой задачи.) </p><p> Подробно, чтобы указать, что подразумевается под «именем»: </p><p> Целое число 1 имеет 1 имя «1». </p><p> Целое число 2 имеет 2 имени «1 + 1» и «2». </p><p> Целое число 3 имеет 3 имени «1 + 1 + 1», «2 + 1» и «3». </p><p> Целое число 4 имеет 5 имен «1 + 1 + 1 + 1», «2 + 1 + 1», «2 + 2», «3 + 1», «4». </p><p> Целое число 5 имеет 7 имен «1 + 1 + 1 + 1 + 1», «2 + 1 + 1 + 1», «2 + 2 + 1», «3 + 1 + 1», «3 + 2», «4 + 1», «5». </p><p> Это можно визуализировать в следующем виде: </p><pre> 1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
</pre><p> Где строка $ n $ соответствует целому числу $ n $, а каждый столбец $ C $ в строке $ m $ слева направо соответствует числу имен, начинающихся с $ C $. </p><p> Необязательно заметим, что сумма $ n $ -ой строки $ P (n) $ является <a href="http://mathworld.wolfram.com/PartitionFunctionP.html" title="ссылка: http://mathworld.wolfram.com/PartitionFunctionP.html">целочисленной статистикой</a> . </p> задача <p> Реализуйте функцию, которая возвращает сумму $ n $ -ой строки. </p></section>
</pre><p> Где строка $ n $ соответствует целому числу $ n $, а каждый столбец $ C $ в строке $ m $ слева направо соответствует числу имен, начинающихся с $ C $. </p><p> Необязательно заметим, что сумма $ n $ -ой строки $ P (n) $ является <a href="http://mathworld.wolfram.com/PartitionFunctionP.html" title="ссылка: http://mathworld.wolfram.com/PartitionFunctionP.html">целочисленной статистикой</a> . </p> задача <p> Реализуйте функцию, которая возвращает сумму $ n $ -ой строки. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function that returns the sum of the $n$-th row.
</section>
## Tests
@@ -24,20 +27,20 @@ localeTitle: 9 миллиардов имен Бога - целое число
```yml
tests:
- text: <code>numberOfNames</code> - это функция.
testString: 'assert(typeof numberOfNames === "function", "<code>numberOfNames</code> is a function.");'
- text: <code>numberOfNames(5)</code> должно равняться 7.
testString: 'assert.equal(numberOfNames(5), 7, "<code>numberOfNames(5)</code> should equal 7.");'
- text: <code>numberOfNames(12)</code> должно равняться 77.
testString: 'assert.equal(numberOfNames(12), 77, "<code>numberOfNames(12)</code> should equal 77.");'
- text: <code>numberOfNames(18)</code> должно равняться 385.
testString: 'assert.equal(numberOfNames(18), 385, "<code>numberOfNames(18)</code> should equal 385.");'
- text: <code>numberOfNames(23)</code> должно равняться 1255.
testString: 'assert.equal(numberOfNames(23), 1255, "<code>numberOfNames(23)</code> should equal 1255.");'
- text: <code>numberOfNames(42)</code> должен равняться 53174.
testString: 'assert.equal(numberOfNames(42), 53174, "<code>numberOfNames(42)</code> should equal 53174.");'
- text: <code>numberOfNames(123)</code> должно равняться 2552338241.
testString: 'assert.equal(numberOfNames(123), 2552338241, "<code>numberOfNames(123)</code> should equal 2552338241.");'
- text: <code>numberOfNames</code> is a function.
testString: assert(typeof numberOfNames === 'function');
- text: <code>numberOfNames(5)</code> should equal 7.
testString: assert.equal(numberOfNames(5), 7);
- text: <code>numberOfNames(12)</code> should equal 77.
testString: assert.equal(numberOfNames(12), 77);
- text: <code>numberOfNames(18)</code> should equal 385.
testString: assert.equal(numberOfNames(18), 385);
- text: <code>numberOfNames(23)</code> should equal 1255.
testString: assert.equal(numberOfNames(23), 1255);
- text: <code>numberOfNames(42)</code> should equal 53174.
testString: assert.equal(numberOfNames(42), 53174);
- text: <code>numberOfNames(123)</code> should equal 2552338241.
testString: assert.equal(numberOfNames(123), 2552338241);
```
@@ -49,7 +52,7 @@ tests:
<div id='js-seed'>
```js
function numberOfNames (num) {
function numberOfNames(num) {
// Good luck!
return true;
}
@@ -58,14 +61,27 @@ function numberOfNames (num) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function numberOfNames(num) {
const cache = [
[1]
];
for (let l = cache.length; l < num + 1; l++) {
let Aa;
let Mi;
const r = [0];
for (let x = 1; x < l + 1; x++) {
r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);
}
cache.push(r);
}
return cache[num][cache[num].length - 1];
}
```
</section>

View File

@@ -2,15 +2,23 @@
title: ABC Problem
id: 594810f028c0303b75339acc
challengeType: 5
videoUrl: ''
forumTopicId: 302220
localeTitle: Проблема с ABC
---
## Description
<section id="description"><p> Вам предоставляется коллекция блоков ABC (например, блоков алфавита детства). На каждом блоке есть 20 блоков с двумя буквами. На всех сторонах блоков гарантируется полный алфавит. Сбор образцов блоков: </p><p> (БО) </p><p> (КСК) </p><p> (DQ) </p><p> (CP) </p><p> (НС) </p><p> (GT) </p><p> (RE) </p><p> (ТГ) </p><p> (КТ) </p><p> (ФС) </p><p> (ДВ) </p><p> (HU) </p><p> (VI) </p><p> (AN) </p><p> (ОВ) </p><p> (ЭР) </p><p> (ФС) </p><p> (LY) </p><p> (ПК) </p><p> (ЗМ) </p><p> Некоторые правила, которые следует учитывать: </p> Когда используется буква на блоке, этот блок нельзя использовать снова. Функция должна быть нечувствительна к регистру. <p> Реализуйте функцию, которая принимает строку (слово) и определяет, может ли слово быть записано с данным набором блоков. </p></section>
<section id='description'>
<p> Вам предоставляется коллекция блоков ABC (например, блоков алфавита детства). На каждом блоке есть 20 блоков с двумя буквами. На всех сторонах блоков гарантируется полный алфавит. Сбор образцов блоков: </p><p> (БО) </p><p> (КСК) </p><p> (DQ) </p><p> (CP) </p><p> (НС) </p><p> (GT) </p><p> (RE) </p><p> (ТГ) </p><p> (КТ) </p><p> (ФС) </p><p> (ДВ) </p><p> (HU) </p><p> (VI) </p><p> (AN) </p><p> (ОВ) </p><p> (ЭР) </p><p> (ФС) </p><p> (LY) </p><p> (ПК) </p><p> (ЗМ) </p><p> Некоторые правила, которые следует учитывать: </p> Когда используется буква на блоке, этот блок нельзя использовать снова. Функция должна быть нечувствительна к регистру. <p> Реализуйте функцию, которая принимает строку (слово) и определяет, может ли слово быть записано с данным набором блоков. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
Some rules to keep in mind:
<ul>
<li>Once a letter on a block is used, that block cannot be used again.</li>
<li>The function should be case-insensitive.</li>
</ul>
</section>
## Tests
@@ -18,22 +26,22 @@ localeTitle: Проблема с ABC
```yml
tests:
- text: <code>canMakeWord</code> - это функция.
testString: 'assert(typeof canMakeWord === "function", "<code>canMakeWord</code> is a function.");'
- text: <code>canMakeWord</code> должен возвращать логическое значение.
testString: 'assert(typeof canMakeWord("hi") === "boolean", "<code>canMakeWord</code> should return a boolean.");'
- text: <code>canMakeWord(&quot;bark&quot;)</code> должен возвращать true.
testString: 'assert(canMakeWord(words[0]), "<code>canMakeWord("bark")</code> should return true.");'
- text: <code>canMakeWord(&quot;BooK&quot;)</code> должен возвращать false.
testString: 'assert(!canMakeWord(words[1]), "<code>canMakeWord("BooK")</code> should return false.");'
- text: <code>canMakeWord(&quot;TReAT&quot;)</code> должен возвращать true.
testString: 'assert(canMakeWord(words[2]), "<code>canMakeWord("TReAT")</code> should return true.");'
- text: <code>canMakeWord(&quot;COMMON&quot;)</code> должен возвращать false.
testString: 'assert(!canMakeWord(words[3]), "<code>canMakeWord("COMMON")</code> should return false.");'
- text: <code>canMakeWord(&quot;squAD&quot;)</code> должен возвращать true.
testString: 'assert(canMakeWord(words[4]), "<code>canMakeWord("squAD")</code> should return true.");'
- text: <code>canMakeWord(&quot;conFUSE&quot;)</code> должен возвращать true.
testString: 'assert(canMakeWord(words[5]), "<code>canMakeWord("conFUSE")</code> should return true.");'
- text: <code>canMakeWord</code> is a function.
testString: assert(typeof canMakeWord === 'function');
- text: <code>canMakeWord</code> should return a boolean.
testString: assert(typeof canMakeWord('hi') === 'boolean');
- text: <code>canMakeWord("bark")</code> should return true.
testString: assert(canMakeWord(words[0]));
- text: <code>canMakeWord("BooK")</code> should return false.
testString: assert(!canMakeWord(words[1]));
- text: <code>canMakeWord("TReAT")</code> should return true.
testString: assert(canMakeWord(words[2]));
- text: <code>canMakeWord("COMMON")</code> should return false.
testString: assert(!canMakeWord(words[3]));
- text: <code>canMakeWord("squAD")</code> should return true.
testString: assert(canMakeWord(words[4]));
- text: <code>canMakeWord("conFUSE")</code> should return true.
testString: assert(canMakeWord(words[5]));
```
@@ -45,7 +53,7 @@ tests:
<div id='js-seed'>
```js
function canMakeWord (word) {
function canMakeWord(word) {
// Good luck!
}
@@ -53,12 +61,12 @@ function canMakeWord (word) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const words = ['bark', 'BooK', 'TReAT', 'COMMON', 'squAD', 'conFUSE'];
```
</div>
@@ -69,6 +77,27 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function canMakeWord(word) {
const characters = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM';
const blocks = characters.split(' ').map(pair => pair.split(''));
const letters = [...word.toUpperCase()];
let length = letters.length;
const copy = new Set(blocks);
letters.forEach(letter => {
for (let block of copy) {
const index = block.indexOf(letter);
if (index !== -1) {
length--;
copy.delete(block);
break;
}
}
});
return !length;
}
```
</section>

View File

@@ -1,16 +1,19 @@
---
title: 'Abundant, deficient and perfect number classifications'
title: Abundant, deficient and perfect number classifications
id: 594810f028c0303b75339acd
challengeType: 5
videoUrl: ''
localeTitle: 'Обильные, неполные и совершенные классификации номеров'
forumTopicId: 302221
localeTitle: Обильные, неполные и совершенные классификации номеров
---
## Description
<section id="description"><p> Они определяют три классификации положительных целых чисел на основе их <a href="http://rosettacode.org/wiki/Proper divisors" title="Собственные делители">правильных делителей</a> . </p><p> Пусть $ P (n) $ - сумма собственных делителей n, где собственные делители - все натуральные n, отличные от n. </p><p> Если <code>P(n) &lt; n</code> то n классифицируется как «несовершенный», </p><p> Если <code>P(n) === n</code> то n классифицируется как &quot;совершенный&quot; </p><p> Если <code>P(n) &gt; n</code> то n классифицируется как &quot;обильное&quot; </p><p> Пример: </p><p> 6 имеет собственные делители 1, 2 и 3. </p><p> 1 + 2 + 3 = 6, поэтому 6 классифицируется как совершенное число. </p><p> Внедрите функцию, которая вычисляет, сколько целых чисел от 1 до 20 000 (включительно) находятся в каждом из трех классов. Выведите результат как массив в следующем формате <code>[deficient, perfect, abundant]</code> . </p></section>
<section id='description'>
<p> Они определяют три классификации положительных целых чисел на основе их <a href="http://rosettacode.org/wiki/Proper divisors" title="Собственные делители">правильных делителей</a> . </p><p> Пусть $ P (n) $ - сумма собственных делителей n, где собственные делители - все натуральные n, отличные от n. </p><p> Если <code>P(n) &lt; n</code> то n классифицируется как «несовершенный», </p><p> Если <code>P(n) === n</code> то n классифицируется как &quot;совершенный&quot; </p><p> Если <code>P(n) &gt; n</code> то n классифицируется как &quot;обильное&quot; </p><p> Пример: </p><p> 6 имеет собственные делители 1, 2 и 3. </p><p> 1 + 2 + 3 = 6, поэтому 6 классифицируется как совершенное число. </p><p> Внедрите функцию, которая вычисляет, сколько целых чисел от 1 до 20 000 (включительно) находятся в каждом из трех классов. Выведите результат как массив в следующем формате <code>[deficient, perfect, abundant]</code> . </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function that calculates how many of the integers from <code>1</code> to <code>20,000</code> (inclusive) are in each of the three classes. Output the result as an array in the following format <code>[deficient, perfect, abundant]</code>.
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: 'Обильные, неполные и совершенные кл
```yml
tests:
- text: <code>getDPA</code> - это функция.
testString: 'assert(typeof getDPA === "function", "<code>getDPA</code> is a function.");'
- text: <code>getDPA</code> должен возвращать массив.
testString: 'assert(Array.isArray(getDPA(100)), "<code>getDPA</code> should return an array.");'
- text: Возвращаемое значение <code>getDPA</code> должно иметь длину 3.
testString: 'assert(getDPA(100).length === 3, "<code>getDPA</code> return value should have a length of 3.");'
- text: '<code>getDPA(20000)</code> должен равняться [15043, 4, 4953]'
testString: 'assert.deepEqual(getDPA(20000), solution, "<code>getDPA(20000)</code> should equal [15043, 4, 4953]");'
- text: <code>getDPA</code> is a function.
testString: assert(typeof getDPA === 'function');
- text: <code>getDPA</code> should return an array.
testString: assert(Array.isArray(getDPA(100)));
- text: <code>getDPA</code> return value should have a length of 3.
testString: assert(getDPA(100).length === 3);
- text: <code>getDPA(20000)</code> should equal [15043, 4, 4953]
testString: assert.deepEqual(getDPA(20000), solution);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function getDPA (num) {
function getDPA(num) {
// Good luck!
}
@@ -45,12 +48,12 @@ function getDPA (num) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const solution = [15043, 4, 4953];
```
</div>
@@ -61,6 +64,23 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function getDPA(num) {
const dpa = [1, 0, 0];
for (let n = 2; n <= num; n += 1) {
let ds = 1;
const e = Math.sqrt(n);
for (let d = 2; d < e; d += 1) {
if (n % d === 0) {
ds += d + (n / d);
}
}
if (n % e === 0) {
ds += e;
}
dpa[ds < n ? 0 : ds === n ? 1 : 2] += 1;
}
return dpa;
}
```
</section>

View File

@@ -2,15 +2,22 @@
title: Accumulator factory
id: 594810f028c0303b75339ace
challengeType: 5
videoUrl: ''
forumTopicId: 302222
localeTitle: Аккумуляторный завод
---
## Description
<section id="description"><p> Создайте функцию, которая принимает один (числовой) аргумент и возвращает другую функцию, которая является аккумулятором. Возвращенная функция аккумулятора, в свою очередь, также принимает один числовой аргумент и возвращает сумму всех числовых значений, переданных до этого аккумулятора (включая начальное значение, переданное при создании аккумулятора). </p><p> Правила: </p><p> Не используйте глобальные переменные. </p><p> Подсказка: </p><p> Закрытие сохраняет внешнее состояние. </p></section>
<section id='description'>
<p> Создайте функцию, которая принимает один (числовой) аргумент и возвращает другую функцию, которая является аккумулятором. Возвращенная функция аккумулятора, в свою очередь, также принимает один числовой аргумент и возвращает сумму всех числовых значений, переданных до этого аккумулятора (включая начальное значение, переданное при создании аккумулятора). </p><p> Правила: </p><p> Не используйте глобальные переменные. </p><p> Подсказка: </p><p> Закрытие сохраняет внешнее состояние. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them.
<strong>Rules:</strong>
Do not use global variables.
<strong>Hint:</strong>
Closures save outer state.
</section>
## Tests
@@ -18,14 +25,14 @@ localeTitle: Аккумуляторный завод
```yml
tests:
- text: <code>accumulator</code> - это функция.
testString: 'assert(typeof accumulator === "function", "<code>accumulator</code> is a function.");'
- text: <code>accumulator(0)</code> должен возвращать функцию.
testString: 'assert(typeof accumulator(0) === "function", "<code>accumulator(0)</code> should return a function.");'
- text: <code>accumulator(0)(2)</code> должен вернуть номер.
testString: 'assert(typeof accumulator(0)(2) === "number", "<code>accumulator(0)(2)</code> should return a number.");'
- text: 'Передача значений 3, -4, 1.5 и 5 должна возвращать 5.5.'
testString: 'assert(testFn(5) === 5.5, "Passing in the values 3, -4, 1.5, and 5 should return 5.5.");'
- text: <code>accumulator</code> is a function.
testString: assert(typeof accumulator === 'function');
- text: <code>accumulator(0)</code> should return a function.
testString: assert(typeof accumulator(0) === 'function');
- text: <code>accumulator(0)(2)</code> should return a number.
testString: assert(typeof accumulator(0)(2) === 'number');
- text: Passing in the values 3, -4, 1.5, and 5 should return 5.5.
testString: assert(testFn(5) === 5.5);
```
@@ -37,7 +44,7 @@ tests:
<div id='js-seed'>
```js
function accumulator (sum) {
function accumulator(sum) {
// Good luck!
}
@@ -45,12 +52,16 @@ function accumulator (sum) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testFn = typeof accumulator(3) === 'function' && accumulator(3);
if (testFn) {
testFn(-4);
testFn(1.5);
}
```
</div>
@@ -61,6 +72,11 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function accumulator(sum) {
return function(n) {
return sum += n;
};
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Ackermann function
id: 594810f028c0303b75339acf
challengeType: 5
videoUrl: ''
forumTopicId: 302223
localeTitle: Функция Аккермана
---
## Description
<section id="description"><p> Функция Аккермана является классическим примером рекурсивной функции, особенно потому, что она не является примитивной рекурсивной функцией. Он растет очень быстро в стоимости, равно как и размер его дерева вызовов. </p><p> Функция Аккермана обычно определяется следующим образом: </p> $$ A (m, n) = \ begin {cases} n + 1 &amp; \ mbox {if} m = 0 \\ A (m-1, 1) &amp; \ mbox {if} m&gt; 0 \ mbox {и} n = 0 \\ A (m-1, A (m, n-1)) &amp; \ mbox {if} m&gt; 0 \ mbox {и} n&gt; 0. \ end {cases} $$ <p> Его аргументы никогда не отрицательны и всегда заканчиваются. Напишите функцию, которая возвращает значение $ A (m, n) $. Произвольная точность предпочтительнее (поскольку функция растет так быстро), но не требуется. </p></section>
<section id='description'>
<p> Функция Аккермана является классическим примером рекурсивной функции, особенно потому, что она не является примитивной рекурсивной функцией. Он растет очень быстро в стоимости, равно как и размер его дерева вызовов. </p><p> Функция Аккермана обычно определяется следующим образом: </p> $$ A (m, n) = \ begin {cases} n + 1 &amp; \ mbox {if} m = 0 \\ A (m-1, 1) &amp; \ mbox {if} m&gt; 0 \ mbox {и} n = 0 \\ A (m-1, A (m, n-1)) &amp; \ mbox {if} m&gt; 0 \ mbox {и} n&gt; 0. \ end {cases} $$ <p> Его аргументы никогда не отрицательны и всегда заканчиваются. Напишите функцию, которая возвращает значение $ A (m, n) $. Произвольная точность предпочтительнее (поскольку функция растет так быстро), но не требуется. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Функция Аккермана
```yml
tests:
- text: <code>ack</code> - функция.
testString: 'assert(typeof ack === "function", "<code>ack</code> is a function.");'
- text: '<code>ack(0, 0)</code> должен возвращать 1.'
testString: 'assert(ack(0, 0) === 1, "<code>ack(0, 0)</code> should return 1.");'
- text: '<code>ack(1, 1)</code> должен вернуть 3.'
testString: 'assert(ack(1, 1) === 3, "<code>ack(1, 1)</code> should return 3.");'
- text: '<code>ack(2, 5)</code> должен вернуть 13.'
testString: 'assert(ack(2, 5) === 13, "<code>ack(2, 5)</code> should return 13.");'
- text: '<code>ack(3, 3)</code> должен вернуть 61.'
testString: 'assert(ack(3, 3) === 61, "<code>ack(3, 3)</code> should return 61.");'
- text: <code>ack</code> is a function.
testString: assert(typeof ack === 'function');
- text: <code>ack(0, 0)</code> should return 1.
testString: assert(ack(0, 0) === 1);
- text: <code>ack(1, 1)</code> should return 3.
testString: assert(ack(1, 1) === 3);
- text: <code>ack(2, 5)</code> should return 13.
testString: assert(ack(2, 5) === 13);
- text: <code>ack(3, 3)</code> should return 61.
testString: assert(ack(3, 3) === 61);
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function ack (m, n) {
function ack(m, n) {
// Good luck!
}
@@ -47,14 +50,15 @@ function ack (m, n) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function ack(m, n) {
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Align columns
id: 594810f028c0303b75339ad0
challengeType: 5
videoUrl: ''
forumTopicId: 302224
localeTitle: Выровнять столбцы
---
## Description
<section id="description"><p> Учитывая текстовый файл многих строк, где поля в строке обозначаются одним символом <code>$</code> , напишите программу, которая выравнивает каждый столбец полей, гарантируя, что слова в каждом столбце разделены хотя бы одним пробелом. Кроме того, разрешите каждое слово в столбце быть либо оправданным, либо оправданным, либо оправданным по центру в его столбце. </p><p> Используйте следующий текст для тестирования своих программ: </p><pre> Учитывая $ в $ текста $ файл $ из $ многих $ линий
<section id='description'>
<p> Учитывая текстовый файл многих строк, где поля в строке обозначаются одним символом <code>$</code> , напишите программу, которая выравнивает каждый столбец полей, гарантируя, что слова в каждом столбце разделены хотя бы одним пробелом. Кроме того, разрешите каждое слово в столбце быть либо оправданным, либо оправданным, либо оправданным по центру в его столбце. </p><p> Используйте следующий текст для тестирования своих программ: </p><pre> Учитывая $ в $ текста $ файл $ из $ многих $ линий
где $ поля $ в $ а $ линия $
составляют $ очерчены $ на $ «доллар» в размере $ одноместный $ символа $
написать $ в $ программе
@@ -17,10 +18,36 @@ localeTitle: Выровнять столбцы
Кроме того, $ позволяют $ за $ каждого $ слова $ в $ A $ столбец $ до $ быть $ либо $ остался $
оправданный, $ права $ оправдано
или $ центр $ оправдана $ в $ его $ колонке.
</pre><p> Обратите внимание, что: </p> Примеры строк ввода текста могут или не могут иметь завершающие символы доллара. Все столбцы должны иметь одинаковое выравнивание. Последовательные символы пробела, создаваемые рядом с концом строк, несущественны для целей задачи. Текст вывода будет отображаться моноширинным шрифтом в текстовом редакторе или базовом терминале. Минимальное пространство между столбцами должно быть вычислено из текста, а не жестко закодировано. Не требуется добавлять разделительные символы между столбцами или вокруг них. </section>
</pre><p> Обратите внимание, что: </p> Примеры строк ввода текста могут или не могут иметь завершающие символы доллара. Все столбцы должны иметь одинаковое выравнивание. Последовательные символы пробела, создаваемые рядом с концом строк, несущественны для целей задачи. Текст вывода будет отображаться моноширинным шрифтом в текстовом редакторе или базовом терминале. Минимальное пространство между столбцами должно быть вычислено из текста, а не жестко закодировано. Не требуется добавлять разделительные символы между столбцами или вокруг них.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Use the following text to test your programs:
<pre>
Given$a$text$file$of$many$lines
where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character
write$a$program
that$aligns$each$column$of$fields
by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified
or$center$justified$within$its$column.
</pre>
<strong>Note that:</strong>
<ul>
<li>The example input texts lines may, or may not, have trailing dollar characters.</li>
<li>All columns should share the same alignment.</li>
<li>Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.</li>
<li>Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.</li>
<li>The minimum space between columns should be computed from the text and not hard-coded.</li>
<li>It is not a requirement to add separating characters between or around columns.</li>
</ul>
</section>
## Tests
@@ -28,14 +55,14 @@ localeTitle: Выровнять столбцы
```yml
tests:
- text: <code>formatText</code> - это функция.
testString: 'assert(typeof formatText === "function", "<code>formatText</code> is a function.");'
- text: '<code>formatText</code> с указанным выше вводом и «правильным» обоснованием должен <code>formatText</code> следующее:'
testString: 'assert.strictEqual(formatText(testInput, "right"), rightAligned, "<code>formatText</code> with the above input and "right" justification should produce the following: ");'
- text: '<code>formatText</code> с указанным выше вводом и «левым» обоснованием должен <code>formatText</code> следующее:'
testString: 'assert.strictEqual(formatText(testInput, "left"), leftAligned, "<code>formatText</code> with the above input and "left" justification should produce the following: ");'
- text: '<code>formatText</code> с указанным выше вводом и выравниванием «центра» должно приводить к следующему:'
testString: 'assert.strictEqual(formatText(testInput, "center"), centerAligned, "<code>formatText</code> with the above input and "center" justification should produce the following: ");'
- text: <code>formatText</code> is a function.
testString: assert(typeof formatText === 'function');
- text: '<code>formatText</code> with the above input and "right" justification should produce the following: '
testString: assert.strictEqual(formatText(testInput, 'right'), rightAligned);
- text: '<code>formatText</code> with the above input and "left" justification should produce the following: '
testString: assert.strictEqual(formatText(testInput, 'left'), leftAligned);
- text: '<code>formatText</code> with the above input and "center" justification should produce the following: '
testString: assert.strictEqual(formatText(testInput, 'center'), centerAligned);
```
@@ -60,7 +87,7 @@ const testArr = [
'or$center$justified$within$its$column.'
];
function formatText (input, justification) {
function formatText(input, justification) {
// Good luck!
}
@@ -68,12 +95,56 @@ function formatText (input, justification) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testInput = [
'Given$a$text$file$of$many$lines',
'where$fields$within$a$line$',
'are$delineated$by$a$single$\"dollar\"$character',
'write$a$program',
'that$aligns$each$column$of$fields$',
'by$ensuring$that$words$in$each$',
'column$are$separated$by$at$least$one$space.',
'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
'justified,$right$justified',
'or$center$justified$within$its$column.'
];
const rightAligned = ' Given a text file of many lines\n' +
' where fields within a line \n' +
' are delineated by a single "dollar" character\n' +
' write a program\n' +
' that aligns each column of fields \n' +
' by ensuring that words in each \n' +
' column are separated by at least one space.\n' +
' Further, allow for each word in a column to be either left \n' +
'justified, right justified\n' +
' or center justified within its column.';
const leftAligned = 'Given a text file of many lines \n' +
'where fields within a line \n' +
'are delineated by a single "dollar" character\n' +
'write a program \n' +
'that aligns each column of fields \n' +
'by ensuring that words in each \n' +
'column are separated by at least one space.\n' +
'Further, allow for each word in a column to be either left \n' +
'justified, right justified\n' +
'or center justified within its column. ';
const centerAligned = ' Given a text file of many lines \n' +
' where fields within a line \n' +
' are delineated by a single \"dollar\" character\n' +
' write a program \n' +
' that aligns each column of fields \n' +
' by ensuring that words in each \n' +
' column are separated by at least one space.\n' +
' Further, allow for each word in a column to be either left \n' +
'justified, right justified\n' +
' or center justified within its column. ';
```
</div>
@@ -84,6 +155,57 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
const testArr = [
'Given$a$text$file$of$many$lines',
'where$fields$within$a$line$',
'are$delineated$by$a$single$"dollar"$character',
'write$a$program',
'that$aligns$each$column$of$fields$',
'by$ensuring$that$words$in$each$',
'column$are$separated$by$at$least$one$space.',
'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
'justified,$right$justified',
'or$center$justified$within$its$column.'
];
String.prototype.repeat = function (n) { return new Array(1 + parseInt(n)).join(this); };
function formatText(input, justification) {
let x, y, max, cols = 0, diff, left, right;
for (x = 0; x < input.length; x++) {
input[x] = input[x].split('$');
if (input[x].length > cols) {
cols = input[x].length;
}
}
for (x = 0; x < cols; x++) {
max = 0;
for (y = 0; y < input.length; y++) {
if (input[y][x] && max < input[y][x].length) {
max = input[y][x].length;
}
}
for (y = 0; y < input.length; y++) {
if (input[y][x]) {
diff = (max - input[y][x].length) / 2;
left = ' '.repeat(Math.floor(diff));
right = ' '.repeat(Math.ceil(diff));
if (justification === 'left') {
right += left; left = '';
}
if (justification === 'right') {
left += right; right = '';
}
input[y][x] = left + input[y][x] + right;
}
}
}
for (x = 0; x < input.length; x++) {
input[x] = input[x].join(' ');
}
input = input.join('\n');
return input;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Amicable pairs
id: 5949b579404977fbaefcd737
challengeType: 5
videoUrl: ''
forumTopicId: 302225
localeTitle: Дружественные пары
---
## Description
<section id="description"> Два целых числа $ N $ и $ M $ называются <a href="https://en.wikipedia.org/wiki/Amicable numbers" title="wp: дружественные номера">дружественными парами,</a> если $ N \ neq M $ и сумма <a href="http://rosettacode.org/wiki/Proper divisors" title="Собственные делители">собственных делителей</a> $ N $ ($ \ mathrm {sum} (\ mathrm {propDivs} (N)) $) $ = M $, а также $ \ mathrm {sum} (\ mathrm {propDivs} (M)) = N $. Пример: 1184 и 1210 являются дружной парой с соответствующими делителями: 1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 и 1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 соответственно. Задача: рассчитать и показать здесь дружественные пары ниже 20 000 (их восемь). Связанные задачи <a href="http://rosettacode.org/wiki/Proper divisors" title="Собственные делители">Правильные делители</a> <a href="http://rosettacode.org/wiki/Abundant, deficient and perfect number classifications" title="Обильные, неполные и совершенные классификации номеров">Обильные, неполные и совершенные классификации чисел Классификация</a> <a href="http://rosettacode.org/wiki/Aliquot sequence classifications" title="Классификация последовательности аликвот">последовательности аликвот</a> и ее дружественная классификация. </section>
<section id='description'>
Два целых числа $ N $ и $ M $ называются <a href="https://en.wikipedia.org/wiki/Amicable numbers" title="wp: дружественные номера">дружественными парами,</a> если $ N \ neq M $ и сумма <a href="http://rosettacode.org/wiki/Proper divisors" title="Собственные делители">собственных делителей</a> $ N $ ($ \ mathrm {sum} (\ mathrm {propDivs} (N)) $) $ = M $, а также $ \ mathrm {sum} (\ mathrm {propDivs} (M)) = N $. Пример: 1184 и 1210 являются дружной парой с соответствующими делителями: 1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 и 1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 соответственно. Задача: рассчитать и показать здесь дружественные пары ниже 20 000 (их восемь). Связанные задачи <a href="http://rosettacode.org/wiki/Proper divisors" title="Собственные делители">Правильные делители</a> <a href="http://rosettacode.org/wiki/Abundant, deficient and perfect number classifications" title="Обильные, неполные и совершенные классификации номеров">Обильные, неполные и совершенные классификации чисел Классификация</a> <a href="http://rosettacode.org/wiki/Aliquot sequence classifications" title="Классификация последовательности аликвот">последовательности аликвот</a> и ее дружественная классификация.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Calculate and show here the Amicable pairs below 20,000 (there are eight).
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Дружественные пары
```yml
tests:
- text: <code>amicablePairsUpTo</code> - это функция.
testString: 'assert(typeof amicablePairsUpTo === "function", "<code>amicablePairsUpTo</code> is a function.");'
- text: '<code>amicablePairsUpTo(300)</code> должен возвратить <code>[[220,284]]</code> .'
testString: 'assert.deepEqual(amicablePairsUpTo(300), answer300, "<code>amicablePairsUpTo(300)</code> should return <code>[[220,284]]</code>.");'
- text: '<code>amicablePairsUpTo(3000)</code> должен вернуть <code>[[220,284],[1184,1210],[2620,2924]]</code> .'
testString: 'assert.deepEqual(amicablePairsUpTo(3000), answer3000, "<code>amicablePairsUpTo(3000)</code> should return <code>[[220,284],[1184,1210],[2620,2924]]</code>.");'
- text: '<code>amicablePairsUpTo(20000)</code> должен возвращать <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code> .'
testString: 'assert.deepEqual(amicablePairsUpTo(20000), answer20000, "<code>amicablePairsUpTo(20000)</code> should return <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code>.");'
- text: <code>amicablePairsUpTo</code> is a function.
testString: assert(typeof amicablePairsUpTo === 'function');
- text: <code>amicablePairsUpTo(300)</code> should return <code>[[220,284]]</code>.
testString: assert.deepEqual(amicablePairsUpTo(300), answer300);
- text: <code>amicablePairsUpTo(3000)</code> should return <code>[[220,284],[1184,1210],[2620,2924]]</code>.
testString: assert.deepEqual(amicablePairsUpTo(3000), answer3000);
- text: <code>amicablePairsUpTo(20000)</code> should return <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code>.
testString: assert.deepEqual(amicablePairsUpTo(20000), answer20000);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function amicablePairsUpTo (maxNum) {
function amicablePairsUpTo(maxNum) {
// Good luck!
return true;
}
@@ -46,12 +49,27 @@ function amicablePairsUpTo (maxNum) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const answer300 = [[220, 284]];
const answer3000 = [
[220, 284],
[1184, 1210],
[2620, 2924]
];
const answer20000 = [
[220, 284],
[1184, 1210],
[2620, 2924],
[5020, 5564],
[6232, 6368],
[10744, 10856],
[12285, 14595],
[17296, 18416]
];
```
</div>
@@ -62,6 +80,45 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// amicablePairsUpTo :: Int -> [(Int, Int)]
function amicablePairsUpTo(maxNum) {
return range(1, maxNum)
.map(x => properDivisors(x)
.reduce((a, b) => a + b, 0))
.reduce((a, m, i, lst) => {
const n = i + 1;
return (m > n) && lst[m - 1] === n ?
a.concat([
[n, m]
]) : a;
}, []);
}
// properDivisors :: Int -> [Int]
function properDivisors(n) {
if (n < 2) return [];
const rRoot = Math.sqrt(n);
const intRoot = Math.floor(rRoot);
const blnPerfectSquare = rRoot === intRoot;
const lows = range(1, intRoot)
.filter(x => (n % x) === 0);
return lows.concat(lows.slice(1)
.map(x => n / x)
.reverse()
.slice(blnPerfectSquare | 0));
}
// Int -> Int -> Maybe Int -> [Int]
function range(m, n, step) {
const d = (step || 1) * (n >= m ? 1 : -1);
return Array.from({
length: Math.floor((n - m) / d) + 1
}, (_, i) => m + (i * d));
}
```
</section>

View File

@@ -1,16 +1,19 @@
---
title: Averages-Mode
title: Averages/Mode
id: 594d8d0ab97724821379b1e6
challengeType: 5
videoUrl: ''
forumTopicId: 302226
localeTitle: Сред-Mode
---
## Description
<section id="description"><p> Напишите программу , чтобы найти <a href="https://en.wikipedia.org/wiki/Mode (statistics)" title="wp: Режим (статистика)">режим</a> значение коллекции. </p><p> Случай, когда коллекция пуст, может быть проигнорирован. Необходимо следить за тем, чтобы режим не был уникальным. </p><p> Если это не подходит или возможно поддерживать общую коллекцию, используйте вектор (массив), если это возможно. Если это не подходит или возможно поддерживать неопределенный тип значения, используйте целые числа. </p></section>
<section id='description'>
<p> Напишите программу , чтобы найти <a href="https://en.wikipedia.org/wiki/Mode (statistics)" title="wp: Режим (статистика)">режим</a> значение коллекции. </p><p> Случай, когда коллекция пуст, может быть проигнорирован. Необходимо следить за тем, чтобы режим не был уникальным. </p><p> Если это не подходит или возможно поддерживать общую коллекцию, используйте вектор (массив), если это возможно. Если это не подходит или возможно поддерживать неопределенный тип значения, используйте целые числа. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,12 +21,12 @@ localeTitle: Сред-Mode
```yml
tests:
- text: <code>mode</code> - это функция.
testString: 'assert(typeof mode === "function", "<code>mode</code> is a function.");'
- text: '<code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> должен равняться <code>[6]</code>'
testString: 'assert.deepEqual(mode(arr1), [6], "<code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>");'
- text: '<code>mode([1, 2, 4, 4, 1])</code> должен быть равен <code>[1, 4]</code> .'
testString: 'assert.deepEqual(mode(arr2).sort(), [1, 4], "<code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.");'
- text: <code>mode</code> is a function.
testString: assert(typeof mode === 'function');
- text: <code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>
testString: assert.deepEqual(mode(arr1), [6]);
- text: <code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.
testString: assert.deepEqual(mode(arr2).sort(), [1, 4]);
```
@@ -35,7 +38,7 @@ tests:
<div id='js-seed'>
```js
function mode (arr) {
function mode(arr) {
// Good luck!
return true;
}
@@ -44,12 +47,13 @@ function mode (arr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
const arr2 = [1, 2, 4, 4, 1];
```
</div>
@@ -60,6 +64,27 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function mode(arr) {
const counter = {};
let result = [];
let max = 0;
// for (const i in arr) {
arr.forEach(el => {
if (!(el in counter)) {
counter[el] = 0;
}
counter[el]++;
if (counter[el] === max) {
result.push(el);
}
else if (counter[el] > max) {
max = counter[el];
result = [el];
}
});
return result;
}
```
</section>

View File

@@ -1,13 +1,14 @@
---
title: Averages-Pythagorean means
title: Averages/Pythagorean means
id: 594d966a1467eb84194f0086
challengeType: 5
videoUrl: ''
forumTopicId: 302227
localeTitle: Средние значения - пифагорейские средства
---
## Description
<section id="description"><p class="rosetta__paragraph"> Вычислите все три <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/Pythagorean means" title="wp: Пифагорейский означает">пифагорейских средства</a> набора целых чисел от <big>1</big> до <big>10</big> (включительно). </p><p class="rosetta__paragraph"> Покажите, что для этого набора натуральных чисел <big>$ A (x_1, \ ldots, x_n) \ geq G (x_1, \ ldots, x_n) \ geq H (x_1, \ ldots, x_n) $</big> . </p> Наиболее распространенным из трех означает <a class="rosetta__link--rosetta" href="http://rosettacode.org/wiki/Averages/Arithmetic mean" title="Средние / Средние арифметические">среднее арифметическое</a> - это сумма списка, деленная на его длину: <big>$ A (x_1, \ ldots, x_n) = \ frac {x_1 + \ cdots + x_n} {n} $</big> <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/Geometric mean" title="wp: среднее геометрическое">Геометрическая Среднее означает</a> $ n $ -ый корень из произведения списка: <big>$ G (x_1, \ ldots, x_n) = \ sqrt [n] {x_1 \ cdots x_n} $</big> <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/Harmonic mean" title="wp: Гармоническое среднее">Гармоническое среднее</a> $ n $, деленное на сумму обратный каждому элементу в списке: <big>$ H (x_1, \ ldots, x_n) = \ frac {n} {\ frac {1} {x_1} + \ cdots + \ frac {1} {x_n}} $</big> <p class="rosetta__paragraph"> Предположим, что вход представляет собой упорядоченный массив всех включенных чисел. </p><p class="rosetta__paragraph"> Для ответа, пожалуйста, выведите объект в следующем формате: </p><pre class="rosetta__pre"> {
<section id='description'>
<p class="rosetta__paragraph"> Вычислите все три <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/Pythagorean means" title="wp: Пифагорейский означает">пифагорейских средства</a> набора целых чисел от <big>1</big> до <big>10</big> (включительно). </p><p class="rosetta__paragraph"> Покажите, что для этого набора натуральных чисел <big>$ A (x_1, \ ldots, x_n) \ geq G (x_1, \ ldots, x_n) \ geq H (x_1, \ ldots, x_n) $</big> . </p> Наиболее распространенным из трех означает <a class="rosetta__link--rosetta" href="http://rosettacode.org/wiki/Averages/Arithmetic mean" title="Средние / Средние арифметические">среднее арифметическое</a> - это сумма списка, деленная на его длину: <big>$ A (x_1, \ ldots, x_n) = \ frac {x_1 + \ cdots + x_n} {n} $</big> <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/Geometric mean" title="wp: среднее геометрическое">Геометрическая Среднее означает</a> $ n $ -ый корень из произведения списка: <big>$ G (x_1, \ ldots, x_n) = \ sqrt [n] {x_1 \ cdots x_n} $</big> <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/Harmonic mean" title="wp: Гармоническое среднее">Гармоническое среднее</a> $ n $, деленное на сумму обратный каждому элементу в списке: <big>$ H (x_1, \ ldots, x_n) = \ frac {n} {\ frac {1} {x_1} + \ cdots + \ frac {1} {x_n}} $</big> <p class="rosetta__paragraph"> Предположим, что вход представляет собой упорядоченный массив всех включенных чисел. </p><p class="rosetta__paragraph"> Для ответа, пожалуйста, выведите объект в следующем формате: </p><pre class="rosetta__pre"> {
значения: {
Арифметика: 5.5,
Геометрический: 4.528728688116765,
@@ -15,10 +16,25 @@ localeTitle: Средние значения - пифагорейские сре
},
test: &#39;является A&gt; = G&gt; = H? да&#39;
}
</pre></section>
</pre>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
When writing your function, assume the input is an ordered array of all inclusive numbers.
For the answer, please output an object in the following format:
```js
{
values: {
Arithmetic: 5.5,
Geometric: 4.528728688116765,
Harmonic: 3.414171521474055
},
test: 'is A >= G >= H ? yes'
}
```
</section>
## Tests
@@ -26,10 +42,10 @@ localeTitle: Средние значения - пифагорейские сре
```yml
tests:
- text: Функция <code>pythagoreanMeans</code> - это функция.
testString: 'assert(typeof pythagoreanMeans === "function", "<code>pythagoreanMeans</code> is a function.");'
- text: '<code>pythagoreanMeans([1, 2, ..., 10])</code> должен равняться тому же самому выходу.'
testString: 'assert.deepEqual(pythagoreanMeans(range1), answer1, "<code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.");'
- text: <code>pythagoreanMeans</code> is a function.
testString: assert(typeof pythagoreanMeans === 'function');
- text: <code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.
testString: assert.deepEqual(pythagoreanMeans(range1), answer1);
```
@@ -41,7 +57,7 @@ tests:
<div id='js-seed'>
```js
function pythagoreanMeans (rangeArr) {
function pythagoreanMeans(rangeArr) {
// Good luck!
}
@@ -49,12 +65,20 @@ function pythagoreanMeans (rangeArr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const range1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const answer1 = {
values: {
Arithmetic: 5.5,
Geometric: 4.528728688116765,
Harmonic: 3.414171521474055
},
test: 'is A >= G >= H ? yes'
};
```
</div>
@@ -65,6 +89,68 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function pythagoreanMeans(rangeArr) {
// arithmeticMean :: [Number] -> Number
const arithmeticMean = xs =>
foldl((sum, n) => sum + n, 0, xs) / length(xs);
// geometricMean :: [Number] -> Number
const geometricMean = xs =>
raise(foldl((product, x) => product * x, 1, xs), 1 / length(xs));
// harmonicMean :: [Number] -> Number
const harmonicMean = xs =>
length(xs) / foldl((invSum, n) => invSum + (1 / n), 0, xs);
// GENERIC FUNCTIONS ------------------------------------------------------
// A list of functions applied to a list of arguments
// <*> :: [(a -> b)] -> [a] -> [b]
const ap = (fs, xs) => //
Array.prototype.concat(...fs.map(f => //
Array.prototype.concat(...xs.map(x => [f(x)]))));
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// length :: [a] -> Int
const length = xs => xs.length;
// mapFromList :: [(k, v)] -> Dictionary
const mapFromList = kvs =>
foldl((a, [k, v]) =>
(a[(typeof k === 'string' && k)] = v, a), {}, kvs);
// raise :: Num -> Int -> Num
const raise = (n, e) => Math.pow(n, e);
/*
// show :: a -> String
// show :: a -> Int -> String
const show = (...x) =>
JSON.stringify.apply(
null, x.length > 1 ? [x[0], null, x[1]] : x
);
*/
// zip :: [a] -> [b] -> [(a,b)]
const zip = (xs, ys) =>
xs.slice(0, Math.min(xs.length, ys.length))
.map((x, i) => [x, ys[i]]);
// TEST -------------------------------------------------------------------
// mean :: Dictionary
const mean = mapFromList(zip(
['Arithmetic', 'Geometric', 'Harmonic'],
ap([arithmeticMean, geometricMean, harmonicMean], [
rangeArr
])
));
return {
values: mean,
test: `is A >= G >= H ? ${mean.Arithmetic >= mean.Geometric &&
mean.Geometric >= mean.Harmonic ? 'yes' : 'no'}`
};
}
```
</section>

View File

@@ -1,16 +1,19 @@
---
title: Averages-Root mean square
title: Averages/Root mean square
id: 594da033de4190850b893874
challengeType: 5
videoUrl: ''
forumTopicId: 302228
localeTitle: Средние значения - средний квадрат
---
## Description
<section id="description"><p> Вычислите <a href="https://en.wikipedia.org/wiki/Root mean square" title="wp: средний квадрат корня">средний квадрат корня</a> чисел от 1 до 10 включительно. </p><p> Корневой средний квадрат также известен по его инициалам RMS (или rms) и как квадратичное среднее. </p><p> RMS рассчитывается как среднее из квадратов чисел, с квадратным корнем: </p><p> <big>$$ x _ {\ mathrm {rms}} = \ sqrt {{{x_1} ^ 2 + {x_2} ^ 2 + \ cdots + {x_n} ^ 2} \ over n}. $$</big> </p></section>
<section id='description'>
<p> Вычислите <a href="https://en.wikipedia.org/wiki/Root mean square" title="wp: средний квадрат корня">средний квадрат корня</a> чисел от 1 до 10 включительно. </p><p> Корневой средний квадрат также известен по его инициалам RMS (или rms) и как квадратичное среднее. </p><p> RMS рассчитывается как среднее из квадратов чисел, с квадратным корнем: </p><p> <big>$$ x _ {\ mathrm {rms}} = \ sqrt {{{x_1} ^ 2 + {x_2} ^ 2 + \ cdots + {x_n} ^ 2} \ over n}. $$</big> </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Средние значения - средний квадрат
```yml
tests:
- text: <code>rms</code> - это функция.
testString: 'assert(typeof rms === "function", "<code>rms</code> is a function.");'
- text: '<code>rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])</code> должны равняться <code>6.2048368229954285</code> .'
testString: 'assert.equal(rms(arr1), answer1, "<code>rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])</code> should equal <code>6.2048368229954285</code>.");'
- text: <code>rms</code> is a function.
testString: assert(typeof rms === 'function');
- text: <code>rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])</code> should equal <code>6.2048368229954285</code>.
testString: assert.equal(rms(arr1), answer1);
```
@@ -33,7 +36,7 @@ tests:
<div id='js-seed'>
```js
function rms (arr) {
function rms(arr) {
// Good luck!
}
@@ -41,12 +44,13 @@ function rms (arr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const answer1 = 6.2048368229954285;
```
</div>
@@ -57,6 +61,10 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function rms(arr) {
const sumOfSquares = arr.reduce((s, x) => s + x * x, 0);
return Math.sqrt(sumOfSquares / arr.length);
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Babbage problem
id: 594db4d0dedb4c06a2a4cefd
challengeType: 5
videoUrl: ''
forumTopicId: 302229
localeTitle: Проблема с Бэббиджем
---
## Description
<section id="description"><p> <a href="https://en.wikipedia.org/wiki/Charles_Babbage" title="wp: Charles_Babbage">Чарльз Бэббидж</a> , смотрящий вперед на те проблемы, которые мог бы решить его аналитический движок, привел этот пример: </p><blockquote> Какое наименьшее положительное целое число, квадрат которого заканчивается цифрами 269 696? </blockquote><p> - Бэббидж, письмо лорду Боудену, 1837 год; см. Hollingdale and Tootill, <i>Electronic Computers</i> , второе издание, 1970, с. 125. </p><p> Он думал, что ответ может быть 99 736, чья площадь составляет 9 947 269 696; но он не мог быть уверен. </p><p> Задача состоит в том, чтобы выяснить, есть ли у Бэббиджа правильный ответ. </p><p> Реализуйте функцию, чтобы вернуть наименьшее целое число, удовлетворяющее задаче Бэббиджа. Если Бэббидж был прав, верните номер Бэббиджа. </p></section>
<section id='description'>
<p> <a href="https://en.wikipedia.org/wiki/Charles_Babbage" title="wp: Charles_Babbage">Чарльз Бэббидж</a> , смотрящий вперед на те проблемы, которые мог бы решить его аналитический движок, привел этот пример: </p><blockquote> Какое наименьшее положительное целое число, квадрат которого заканчивается цифрами 269 696? </blockquote><p> - Бэббидж, письмо лорду Боудену, 1837 год; см. Hollingdale and Tootill, <i>Electronic Computers</i> , второе издание, 1970, с. 125. </p><p> Он думал, что ответ может быть 99 736, чья площадь составляет 9 947 269 696; но он не мог быть уверен. </p><p> Задача состоит в том, чтобы выяснить, есть ли у Бэббиджа правильный ответ. </p><p> Реализуйте функцию, чтобы вернуть наименьшее целое число, удовлетворяющее задаче Бэббиджа. Если Бэббидж был прав, верните номер Бэббиджа. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function to return the lowest integer that satisfies the Babbage problem. If Babbage was right, return Babbage's number.
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Проблема с Бэббиджем
```yml
tests:
- text: <code>babbage</code> - это функция.
testString: 'assert(typeof babbage === "function", "<code>babbage</code> is a function.");'
- text: '<code>babbage(99736, 269696)</code> не должен возвращать 99736 (есть меньший ответ).'
testString: 'assert.equal(babbage(babbageAns, endDigits), answer, "<code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).");'
- text: <code>babbage</code> is a function.
testString: assert(typeof babbage === 'function');
- text: <code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).
testString: assert.equal(babbage(babbageAns, endDigits), answer);
```
@@ -33,7 +36,7 @@ tests:
<div id='js-seed'>
```js
function babbage (babbageNum, endDigits) {
function babbage(babbageNum, endDigits) {
// Good luck!
return true;
}
@@ -42,12 +45,14 @@ function babbage (babbageNum, endDigits) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const babbageAns = 99736;
const endDigits = 269696;
const answer = 25264;
```
</div>
@@ -58,6 +63,22 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function babbage(babbageAns, endDigits) {
const babbageNum = Math.pow(babbageAns, 2);
const babbageStartDigits = parseInt(babbageNum.toString().replace('269696', ''));
let answer = 99736;
// count down from this answer and save any sqrt int result. return lowest one
for (let i = babbageStartDigits; i >= 0; i--) {
const num = parseInt(i.toString().concat('269696'));
const result = Math.sqrt(num);
if (result === Math.floor(Math.sqrt(num))) {
answer = result;
}
}
return answer;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Balanced brackets
id: 594dc6c729e5700999302b45
challengeType: 5
videoUrl: ''
forumTopicId: 302230
localeTitle: Сбалансированные кронштейны
---
## Description
<section id="description"><p> Определите, сбалансирована ли сгенерированная строка скобок; то есть, состоит ли он целиком из пар открывающих / закрывающих скобок (в этом порядке), ни одно из которых не выполняется. </p> Примеры: <p class="rosetta__paragraph"> (пусто) true </p><p class="rosetta__paragraph"> <code>[]</code> true </p><p class="rosetta__paragraph"> <code>][</code> false </p><p class="rosetta__paragraph"> <code>[][]</code> true </p><p class="rosetta__paragraph"> <code>][][</code> false </p><p class="rosetta__paragraph"> <code>[]][[]</code> false </p><p class="rosetta__paragraph"> <code>[[[[]]]]</code> true </p></section>
<section id='description'>
<p> Определите, сбалансирована ли сгенерированная строка скобок; то есть, состоит ли он целиком из пар открывающих / закрывающих скобок (в этом порядке), ни одно из которых не выполняется. </p> Примеры: <p class="rosetta__paragraph"> (пусто) true </p><p class="rosetta__paragraph"> <code>[]</code> true </p><p class="rosetta__paragraph"> <code>][</code> false </p><p class="rosetta__paragraph"> <code>[][]</code> true </p><p class="rosetta__paragraph"> <code>][][</code> false </p><p class="rosetta__paragraph"> <code>[]][[]</code> false </p><p class="rosetta__paragraph"> <code>[[[[]]]]</code> true </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,44 +21,44 @@ localeTitle: Сбалансированные кронштейны
```yml
tests:
- text: <code>isBalanced</code> - это функция.
testString: 'assert(typeof isBalanced === "function", "<code>isBalanced</code> is a function.");'
- text: '<code>isBalanced(&quot;[]&quot;)</code> должен возвращать true.'
testString: 'assert(isBalanced(testCases[0]), "<code>isBalanced("[]")</code> should return true.");'
- text: '<code>isBalanced(&quot;]][[[][][][]][&quot;)</code> должен возвращать значение false.'
testString: 'assert(!isBalanced(testCases[1]), "<code>isBalanced("]][[[][][][]][")</code> should return false.");'
- text: '<code>isBalanced(&quot;[][[[[][][[[]]]]]]&quot;)</code> должен возвращать true.'
testString: 'assert(isBalanced(testCases[2]), "<code>isBalanced("[][[[[][][[[]]]]]]")</code> should return true.");'
- text: '<code>isBalanced(&quot;][&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[3]), "<code>isBalanced("][")</code> should return true.");'
- text: '<code>isBalanced(&quot;[[[]]]][[]&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[4]), "<code>isBalanced("[[[]]]][[]")</code> should return true.");'
- text: '<code>isBalanced(&quot;][[]&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[5]), "<code>isBalanced("][[]")</code> should return true.");'
- text: '<code>isBalanced(&quot;][[][]][[[]]&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[6]), "<code>isBalanced("][[][]][[[]]")</code> should return true.");'
- text: '<code>isBalanced(&quot;[[][]]][&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[7]), "<code>isBalanced("[[][]]][")</code> should return true.");'
- text: '<code>isBalanced(&quot;[[[]]][[]]]][][[&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[8]), "<code>isBalanced("[[[]]][[]]]][][[")</code> should return true.");'
- text: '<code>isBalanced(&quot;[]][[]]][[[[][]]&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[9]), "<code>isBalanced("[]][[]]][[[[][]]")</code> should return true.");'
- text: '<code>isBalanced(&quot;][]][[][&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[10]), "<code>isBalanced("][]][[][")</code> should return true.");'
- text: '<code>isBalanced(&quot;[[]][[][]]&quot;)</code> должен возвращать true.'
testString: 'assert(isBalanced(testCases[11]), "<code>isBalanced("[[]][[][]]")</code> should return true.");'
- text: '<code>isBalanced(&quot;[[]]&quot;)</code> должен возвращать true.'
testString: 'assert(isBalanced(testCases[12]), "<code>isBalanced("[[]]")</code> should return true.");'
- text: '<code>isBalanced(&quot;]][]][[]][[[&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[13]), "<code>isBalanced("]][]][[]][[[")</code> should return true.");'
- text: '<code>isBalanced(&quot;][]][][[&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[14]), "<code>isBalanced("][]][][[")</code> should return true.");'
- text: '<code>isBalanced(&quot;][][&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[15]), "<code>isBalanced("][][")</code> should return true.");'
- text: '<code>isBalanced(&quot;[[]]][][][[]][&quot;)</code> должен возвращать true.'
testString: 'assert(!isBalanced(testCases[16]), "<code>isBalanced("[[]]][][][[]][")</code> should return true.");'
- text: <code>isBalanced(&quot;&quot;)</code> должен возвращать true.
testString: 'assert(isBalanced(testCases[17]), "<code>isBalanced("")</code> should return true.");'
- text: <code>isBalanced</code> is a function.
testString: assert(typeof isBalanced === 'function');
- text: <code>isBalanced("[]")</code> should return true.
testString: assert(isBalanced(testCases[0]));
- text: <code>isBalanced("]][[[][][][]][")</code> should return false.
testString: assert(!isBalanced(testCases[1]));
- text: <code>isBalanced("[][[[[][][[[]]]]]]")</code> should return true.
testString: assert(isBalanced(testCases[2]));
- text: <code>isBalanced("][")</code> should return true.
testString: assert(!isBalanced(testCases[3]));
- text: <code>isBalanced("[[[]]]][[]")</code> should return true.
testString: assert(!isBalanced(testCases[4]));
- text: <code>isBalanced("][[]")</code> should return true.
testString: assert(!isBalanced(testCases[5]));
- text: <code>isBalanced("][[][]][[[]]")</code> should return true.
testString: assert(!isBalanced(testCases[6]));
- text: <code>isBalanced("[[][]]][")</code> should return true.
testString: assert(!isBalanced(testCases[7]));
- text: <code>isBalanced("[[[]]][[]]]][][[")</code> should return true.
testString: assert(!isBalanced(testCases[8]));
- text: <code>isBalanced("[]][[]]][[[[][]]")</code> should return true.
testString: assert(!isBalanced(testCases[9]));
- text: <code>isBalanced("][]][[][")</code> should return true.
testString: assert(!isBalanced(testCases[10]));
- text: <code>isBalanced("[[]][[][]]")</code> should return true.
testString: assert(isBalanced(testCases[11]));
- text: <code>isBalanced("[[]]")</code> should return true.
testString: assert(isBalanced(testCases[12]));
- text: <code>isBalanced("]][]][[]][[[")</code> should return true.
testString: assert(!isBalanced(testCases[13]));
- text: <code>isBalanced("][]][][[")</code> should return true.
testString: assert(!isBalanced(testCases[14]));
- text: <code>isBalanced("][][")</code> should return true.
testString: assert(!isBalanced(testCases[15]));
- text: <code>isBalanced("[[]]][][][[]][")</code> should return true.
testString: assert(!isBalanced(testCases[16]));
- text: <code>isBalanced("")</code> should return true.
testString: assert(isBalanced(testCases[17]));
```
@@ -67,7 +70,7 @@ tests:
<div id='js-seed'>
```js
function isBalanced (str) {
function isBalanced(str) {
// Good luck!
return true;
}
@@ -76,12 +79,31 @@ function isBalanced (str) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [
'[]',
']][[[][][][]][',
'[][[[[][][[[]]]]]]',
'][',
'[[[]]]][[]',
'][[]',
'][[][]][[[]]',
'[[][]]][',
'[[[]]][[]]]][][[',
'[]][[]]][[[[][]]',
'][]][[][',
'[[]][[][]]',
'[[]]',
']][]][[]][[[',
'][]][][[',
'][][',
'[[]]][][][[]][',
''
];
```
</div>
@@ -92,6 +114,16 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function isBalanced(str) {
if (str === '') return true;
let a = str;
let b;
do {
b = a;
a = a.replace(/\[\]/g, '');
} while (a !== b);
return !a;
}
```
</section>

View File

@@ -2,21 +2,39 @@
title: Circles of given radius through two points
id: 5951815dd895584b06884620
challengeType: 5
videoUrl: ''
forumTopicId: 302231
localeTitle: Круги заданного радиуса через две точки
---
## Description
<section id="description"><p> Учитывая две точки на плоскости и радиус, обычно через две точки могут быть проведены два круга заданного радиуса. </p> Исключения: радиус нуля должен рассматриваться как никогда не описывающий круги (за исключением случая, когда точки совпадают). Если точки совпадают, то может быть проведено бесконечное число кругов с точкой на их окружности, если радиус не равен нулю, а затем сворачивает круги в точку. Если точки образуют диаметр, верните один круг. Если точки слишком далеки друг от друга, круги не могут быть нарисованы. Задача: выполнить функцию, которая принимает две точки и радиус и возвращает два круга через эти точки. Для каждого результирующего круга укажите координаты для центра каждого круга, округленного до четырех десятичных цифр. Возвращает каждую координату в виде массива и координирует ее как массив массивов. Для краевых случаев возвращайте следующее: если точки находятся на диаметре, верните одну точку. Если радиус также равен нулю, верните <code>&quot;Radius Zero&quot;</code> . Если точки совпадают, верните <code>&quot;Coincident point. Infinite solutions&quot;</code> . Если точки находятся дальше друг от друга, чем диаметр, верните <code>&quot;No intersection. Points further apart than circle diameter&quot;</code> . Примеры входов: <pre> p1 p2 r
<section id='description'>
<p> Учитывая две точки на плоскости и радиус, обычно через две точки могут быть проведены два круга заданного радиуса. </p> Исключения: радиус нуля должен рассматриваться как никогда не описывающий круги (за исключением случая, когда точки совпадают). Если точки совпадают, то может быть проведено бесконечное число кругов с точкой на их окружности, если радиус не равен нулю, а затем сворачивает круги в точку. Если точки образуют диаметр, верните один круг. Если точки слишком далеки друг от друга, круги не могут быть нарисованы. Задача: выполнить функцию, которая принимает две точки и радиус и возвращает два круга через эти точки. Для каждого результирующего круга укажите координаты для центра каждого круга, округленного до четырех десятичных цифр. Возвращает каждую координату в виде массива и координирует ее как массив массивов. Для краевых случаев возвращайте следующее: если точки находятся на диаметре, верните одну точку. Если радиус также равен нулю, верните <code>&quot;Radius Zero&quot;</code> . Если точки совпадают, верните <code>&quot;Coincident point. Infinite solutions&quot;</code> . Если точки находятся дальше друг от друга, чем диаметр, верните <code>&quot;No intersection. Points further apart than circle diameter&quot;</code> . Примеры входов: <pre> p1 p2 r
0,1234, 0,9876 0,8765, 0,2345 2,0
0,0000, 2,0000 0,0000, 0,0000 1,0
0,1234, 0,9876 0,1234, 0,9876 2,0
0,1234, 0,9876 0,8765, 0,2345 0,5
0,1234, 0,9876 0,1234, 0,9876 0,0
</pre> Ref: <a href="http://mathforum.org/library/drmath/view/53027.html" title="ссылка: http://mathforum.org/library/drmath/view/53027.html">Поиск центра круга из двух точек и радиуса</a> из математического форума @ Drexel </section>
</pre> Ref: <a href="http://mathforum.org/library/drmath/view/53027.html" title="ссылка: http://mathforum.org/library/drmath/view/53027.html">Поиск центра круга из двух точек и радиуса</a> из математического форума @ Drexel
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function that takes two points and a radius and returns the two circles through those points. For each resulting circle, provide the coordinates for the center of each circle rounded to four decimal digits. Return each coordinate as an array, and coordinates as an array of arrays.
<strong>For edge cases, return the following:</strong>
<ul>
<li>If points are on the diameter, return one point. If the radius is also zero however, return <code>"Radius Zero"</code>.</li>
<li>If points are coincident, return <code>"Coincident point. Infinite solutions"</code>.</li>
<li>If points are farther apart than the diameter, return <code>"No intersection. Points further apart than circle diameter"</code>.</li>
</ul>
<strong>Sample inputs:</strong>
<pre>
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
</pre>
</section>
## Tests
@@ -24,18 +42,18 @@ localeTitle: Круги заданного радиуса через две то
```yml
tests:
- text: <code>getCircles</code> - это функция.
testString: 'assert(typeof getCircles === "function", "<code>getCircles</code> is a function.");'
- text: '<code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)</code> должны возвращать <code>[[1.8631, 1.9742], [-0.8632, -0.7521]]</code> .'
testString: 'assert.deepEqual(getCircles(...testCases[0]), answers[0], "<code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)</code> should return <code>[[1.8631, 1.9742], [-0.8632, -0.7521]]</code>.");'
- text: '<code>getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)</code> должны возвращать <code>[0, 1]</code>'
testString: 'assert.deepEqual(getCircles(...testCases[1]), answers[1], "<code>getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)</code> should return <code>[0, 1]</code>");'
- text: '<code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)</code> должны возвращать <code>Coincident point. Infinite solutions</code>'
testString: 'assert.deepEqual(getCircles(...testCases[2]), answers[2], "<code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)</code> should return <code>Coincident point. Infinite solutions</code>");'
- text: '<code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)</code> должен возвращать <code>No intersection. Points further apart than circle diameter</code>'
testString: 'assert.deepEqual(getCircles(...testCases[3]), answers[3], "<code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)</code> should return <code>No intersection. Points further apart than circle diameter</code>");'
- text: '<code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)</code> должны возвращать <code>Radius Zero</code>'
testString: 'assert.deepEqual(getCircles(...testCases[4]), answers[4], "<code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)</code> should return <code>Radius Zero</code>");'
- text: <code>getCircles</code> is a function.
testString: assert(typeof getCircles === 'function');
- text: <code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)</code> should return <code>[[1.8631, 1.9742], [-0.8632, -0.7521]]</code>.
testString: assert.deepEqual(getCircles(...testCases[0]), answers[0]);
- text: <code>getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)</code> should return <code>[0, 1]</code>
testString: assert.deepEqual(getCircles(...testCases[1]), answers[1]);
- text: <code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)</code> should return <code>Coincident point. Infinite solutions</code>
testString: assert.deepEqual(getCircles(...testCases[2]), answers[2]);
- text: <code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)</code> should return <code>No intersection. Points further apart than circle diameter</code>
testString: assert.deepEqual(getCircles(...testCases[3]), answers[3]);
- text: <code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)</code> should return <code>Radius Zero</code>
testString: assert.deepEqual(getCircles(...testCases[4]), answers[4]);
```
@@ -47,7 +65,7 @@ tests:
<div id='js-seed'>
```js
function getCircles (...args) {
function getCircles(...args) {
// Good luck!
return true;
}
@@ -56,12 +74,25 @@ function getCircles (...args) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [
[[0.1234, 0.9876], [0.8765, 0.2345], 2.0],
[[0.0000, 2.0000], [0.0000, 0.0000], 1.0],
[[0.1234, 0.9876], [0.1234, 0.9876], 2.0],
[[0.1234, 0.9876], [0.8765, 0.2345], 0.5],
[[0.1234, 0.9876], [0.1234, 0.9876], 0.0]
];
const answers = [
[[1.8631, 1.9742], [-0.8632, -0.7521]],
[0, 1],
'Coincident point. Infinite solutions',
'No intersection. Points further apart than circle diameter',
'Radius Zero'
];
```
</div>
@@ -72,6 +103,41 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;
const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1));
const solveF = (p, r) => t => [parseFloat((r * Math.cos(t) + p[0]).toFixed(4)), parseFloat((r * Math.sin(t) + p[1]).toFixed(4))];
const diamPoints = (p1, p2) => p1.map((e, i) => parseFloat((e + (p2[i] - e) / 2).toFixed(4)));
function getCircles(...args) {
const [p1, p2, s] = args;
const solve = solveF(p1, s);
const halfDist = hDist(p1, p2);
let msg = [];
switch (Math.sign(s - halfDist)) {
case 0:
msg = s ? diamPoints(p1, p2) :
'Radius Zero';
break;
case 1:
if (!halfDist) {
msg = 'Coincident point. Infinite solutions';
}
else {
const theta = pAng(p1, p2);
const theta2 = Math.acos(halfDist / s);
[1, -1].map(e => solve(theta + e * theta2)).forEach(
e => msg.push(e));
}
break;
case -1:
msg = 'No intersection. Points further apart than circle diameter';
break;
default:
msg = 'Reached the default';
}
return msg;
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Closest-pair problem
id: 5951a53863c8a34f02bf1bdc
challengeType: 5
videoUrl: ''
forumTopicId: 302232
localeTitle: Проблема ближайшей пары
---
## Description
<section id="description"> Задача: <p> Предоставить функцию для поиска ближайших двух точек среди множества заданных точек в двух измерениях, т. <a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Ближайшая проблема с двумя точками">Е. Решить задачу Ближайшей пары точек</a> в плоском случае. </p><p> Прямым решением является алгоритм O (n <sup>2</sup> ) (который мы можем назвать алгоритмом грубой силы); псевдокод (с использованием индексов) может быть простым: </p><pre> bruteForceClosestPair из P (1), P (2), ... P (N)
<section id='description'>
Задача: <p> Предоставить функцию для поиска ближайших двух точек среди множества заданных точек в двух измерениях, т. <a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Ближайшая проблема с двумя точками">Е. Решить задачу Ближайшей пары точек</a> в плоском случае. </p><p> Прямым решением является алгоритм O (n <sup>2</sup> ) (который мы можем назвать алгоритмом грубой силы); псевдокод (с использованием индексов) может быть простым: </p><pre> bruteForceClosestPair из P (1), P (2), ... P (N)
если N &lt;2, то
return ∞
еще
@@ -54,10 +55,12 @@ ENDIF
ENDFOR
вернуться ближайший, ближайший
ENDIF
</pre> Ссылки и дальнейшие чтения: <a href="http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf" title="ссылка: http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf">Самая близкая</a> <a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Ближайшая проблема с двумя точками">пара проблем точек</a> <a href="http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html" title="ссылка: http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html">Ближайшая пара (McGill)</a> <a href="http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf" title="ссылка: http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf">Ближайшая пара (UCSB)</a> <a href="http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf" title="ссылка: http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf">Ближайшая пара (WUStL)</a> <a href="http://www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt" title="ссылка: http://www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt">Ближайшая пара (IUPUI)</a> <p> Для ввода предположим, что аргумент представляет собой массив объектов (точек) с элементами <code>x</code> и <code>y</code> установленными в числа. Для вывода возвращаем объект, содержащий пары ключ: значение для <code>distance</code> и <code>pair</code> (т. Е. Пару из двух ближайших точек). </p></section>
</pre> Ссылки и дальнейшие чтения: <a href="http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf" title="ссылка: http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf">Самая близкая</a> <a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Ближайшая проблема с двумя точками">пара проблем точек</a> <a href="http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html" title="ссылка: http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html">Ближайшая пара (McGill)</a> <a href="http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf" title="ссылка: http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf">Ближайшая пара (UCSB)</a> <a href="http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf" title="ссылка: http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf">Ближайшая пара (WUStL)</a> <a href="http://www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt" title="ссылка: http://www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt">Ближайшая пара (IUPUI)</a> <p> Для ввода предположим, что аргумент представляет собой массив объектов (точек) с элементами <code>x</code> и <code>y</code> установленными в числа. Для вывода возвращаем объект, содержащий пары ключ: значение для <code>distance</code> и <code>pair</code> (т. Е. Пару из двух ближайших точек). </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -65,16 +68,16 @@ ENDIF
```yml
tests:
- text: <code>getClosestPair</code> - это функция.
testString: 'assert(typeof getClosestPair === "function", "<code>getClosestPair</code> is a function.");'
- text: Расстояние должно быть следующим.
testString: 'assert.equal(getClosestPair(points1).distance, answer1.distance, "Distance should be the following.");'
- text: Баллы должны быть следующими.
testString: 'assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points1))).pair, answer1.pair, "Points should be the following.");'
- text: Расстояние должно быть следующим.
testString: 'assert.equal(getClosestPair(points2).distance, answer2.distance, "Distance should be the following.");'
- text: Баллы должны быть следующими.
testString: 'assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points2))).pair, answer2.pair, "Points should be the following.");'
- text: <code>getClosestPair</code> is a function.
testString: assert(typeof getClosestPair === 'function');
- text: Distance should be the following.
testString: assert.equal(getClosestPair(points1).distance, answer1.distance);
- text: Points should be the following.
testString: assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points1))).pair, answer1.pair);
- text: Distance should be the following.
testString: assert.equal(getClosestPair(points2).distance, answer2.distance);
- text: Points should be the following.
testString: assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points2))).pair, answer2.pair);
```
@@ -86,18 +89,18 @@ tests:
<div id='js-seed'>
```js
const Point = function (x, y) {
const Point = function(x, y) {
this.x = x;
this.y = y;
};
Point.prototype.getX = function () {
Point.prototype.getX = function() {
return this.x;
};
Point.prototype.getY = function () {
Point.prototype.getY = function() {
return this.y;
};
function getClosestPair (pointsArr) {
function getClosestPair(pointsArr) {
// Good luck!
return true;
}
@@ -106,12 +109,112 @@ function getClosestPair (pointsArr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const points1 = [
new Point(0.748501, 4.09624),
new Point(3.00302, 5.26164),
new Point(3.61878, 9.52232),
new Point(7.46911, 4.71611),
new Point(5.7819, 2.69367),
new Point(2.34709, 8.74782),
new Point(2.87169, 5.97774),
new Point(6.33101, 0.463131),
new Point(7.46489, 4.6268),
new Point(1.45428, 0.087596)
];
const points2 = [
new Point(37100, 13118),
new Point(37134, 1963),
new Point(37181, 2008),
new Point(37276, 21611),
new Point(37307, 9320)
];
const answer1 = {
distance: 0.0894096443343775,
pair: [
{
x: 7.46489,
y: 4.6268
},
{
x: 7.46911,
y: 4.71611
}
]
};
const answer2 = {
distance: 65.06919393998976,
pair: [
{
x: 37134,
y: 1963
},
{
x: 37181,
y: 2008
}
]
};
const benchmarkPoints = [
new Point(16909, 54699),
new Point(14773, 61107),
new Point(95547, 45344),
new Point(95951, 17573),
new Point(5824, 41072),
new Point(8769, 52562),
new Point(21182, 41881),
new Point(53226, 45749),
new Point(68180, 887),
new Point(29322, 44017),
new Point(46817, 64975),
new Point(10501, 483),
new Point(57094, 60703),
new Point(23318, 35472),
new Point(72452, 88070),
new Point(67775, 28659),
new Point(19450, 20518),
new Point(17314, 26927),
new Point(98088, 11164),
new Point(25050, 56835),
new Point(8364, 6892),
new Point(37868, 18382),
new Point(23723, 7701),
new Point(55767, 11569),
new Point(70721, 66707),
new Point(31863, 9837),
new Point(49358, 30795),
new Point(13041, 39745),
new Point(59635, 26523),
new Point(25859, 1292),
new Point(1551, 53890),
new Point(70316, 94479),
new Point(48549, 86338),
new Point(46413, 92747),
new Point(27186, 50426),
new Point(27591, 22655),
new Point(10905, 46153),
new Point(40408, 84202),
new Point(52821, 73520),
new Point(84865, 77388),
new Point(99819, 32527),
new Point(34404, 75657),
new Point(78457, 96615),
new Point(42140, 5564),
new Point(62175, 92342),
new Point(54958, 67112),
new Point(4092, 19709),
new Point(99415, 60298),
new Point(51090, 52158),
new Point(48953, 58567)
];
```
</div>
@@ -122,6 +225,121 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
const Point = function(x, y) {
this.x = x;
this.y = y;
};
Point.prototype.getX = function() {
return this.x;
};
Point.prototype.getY = function() {
return this.y;
};
const mergeSort = function mergeSort(points, comp) {
if(points.length < 2) return points;
var n = points.length,
i = 0,
j = 0,
leftN = Math.floor(n / 2),
rightN = leftN;
var leftPart = mergeSort( points.slice(0, leftN), comp),
rightPart = mergeSort( points.slice(rightN), comp );
var sortedPart = [];
while((i < leftPart.length) && (j < rightPart.length)) {
if(comp(leftPart[i], rightPart[j]) < 0) {
sortedPart.push(leftPart[i]);
i += 1;
}
else {
sortedPart.push(rightPart[j]);
j += 1;
}
}
while(i < leftPart.length) {
sortedPart.push(leftPart[i]);
i += 1;
}
while(j < rightPart.length) {
sortedPart.push(rightPart[j]);
j += 1;
}
return sortedPart;
};
const closestPair = function _closestPair(Px, Py) {
if(Px.length < 2) return { distance: Infinity, pair: [ new Point(0, 0), new Point(0, 0) ] };
if(Px.length < 3) {
//find euclid distance
var d = Math.sqrt( Math.pow(Math.abs(Px[1].x - Px[0].x), 2) + Math.pow(Math.abs(Px[1].y - Px[0].y), 2) );
return {
distance: d,
pair: [ Px[0], Px[1] ]
};
}
var n = Px.length,
leftN = Math.floor(n / 2),
rightN = leftN;
var Xl = Px.slice(0, leftN),
Xr = Px.slice(rightN),
Xm = Xl[leftN - 1],
Yl = [],
Yr = [];
//separate Py
for(var i = 0; i < Py.length; i += 1) {
if(Py[i].x <= Xm.x)
Yl.push(Py[i]);
else
Yr.push(Py[i]);
}
var dLeft = _closestPair(Xl, Yl),
dRight = _closestPair(Xr, Yr);
var minDelta = dLeft.distance,
closestPair = dLeft.pair;
if(dLeft.distance > dRight.distance) {
minDelta = dRight.distance;
closestPair = dRight.pair;
}
//filter points around Xm within delta (minDelta)
var closeY = [];
for(i = 0; i < Py.length; i += 1) {
if(Math.abs(Py[i].x - Xm.x) < minDelta) closeY.push(Py[i]);
}
//find min within delta. 8 steps max
for(i = 0; i < closeY.length; i += 1) {
for(var j = i + 1; j < Math.min( (i + 8), closeY.length ); j += 1) {
var d = Math.sqrt( Math.pow(Math.abs(closeY[j].x - closeY[i].x), 2) + Math.pow(Math.abs(closeY[j].y - closeY[i].y), 2) );
if(d < minDelta) {
minDelta = d;
closestPair = [ closeY[i], closeY[j] ]
}
}
}
return {
distance: minDelta,
pair: closestPair
};
};
function getClosestPair(points) {
const sortX = function(a, b) { return (a.x < b.x) ? -1 : ((a.x > b.x) ? 1 : 0); }
const sortY = function(a, b) { return (a.y < b.y) ? -1 : ((a.y > b.y) ? 1 : 0); }
const Px = mergeSort(points, sortX);
const Py = mergeSort(points, sortY);
return closestPair(Px, Py);
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Combinations
id: 5958469238c0d8d2632f46db
challengeType: 5
videoUrl: ''
forumTopicId: 302233
localeTitle: Комбинации
---
## Description
<section id="description"> Задача: <p> Учитывая неотрицательные целые числа <big>m</big> и <big>n</big> , генерируйте все размерные <big>m</big> <a href="http://mathworld.wolfram.com/Combination.html" title="ссылка: http://mathworld.wolfram.com/Combination.html">комбинаций</a> целых чисел от <big>0</big> (ноль) до <big>n-1</big> в отсортированном порядке (каждая комбинация сортируется и вся таблица сортируется). </p> Пример: <p> <big>3</big> гребня <big>5</big> : </p><pre> 0 1 2
<section id='description'>
Задача: <p> Учитывая неотрицательные целые числа <big>m</big> и <big>n</big> , генерируйте все размерные <big>m</big> <a href="http://mathworld.wolfram.com/Combination.html" title="ссылка: http://mathworld.wolfram.com/Combination.html">комбинаций</a> целых чисел от <big>0</big> (ноль) до <big>n-1</big> в отсортированном порядке (каждая комбинация сортируется и вся таблица сортируется). </p> Пример: <p> <big>3</big> гребня <big>5</big> : </p><pre> 0 1 2
0 1 3
0 1 4
0 2 3
@@ -17,10 +18,12 @@ localeTitle: Комбинации
1 2 4
1 3 4
2 3 4
</pre></section>
</pre>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -28,12 +31,12 @@ localeTitle: Комбинации
```yml
tests:
- text: <code>combinations</code> - это функция.
testString: 'assert(typeof combinations === "function", "<code>combinations</code> is a function.");'
- text: '<code>combinations(3, 5)</code> должны возвращать <code>[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]</code> .'
testString: 'assert.deepEqual(combinations(testInput1[0], testInput1[1]), testOutput1, "<code>combinations(3, 5)</code> should return <code>[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]</code>.");'
- text: '<code>combinations(4, 6)</code> должны возвращать <code>[[0,1,2,3], [0,1,2,4], [0,1,2,5], [0,1,3,4], [0,1,3,5], [0,1,4,5], [0,2,3,4], [0,2,3,5], [0,2,4,5], [0,3,4,5], [1,2,3,4], [1,2,3,5], [1,2,4,5], [1,3,4,5], [2,3,4,5]]</code>'
testString: 'assert.deepEqual(combinations(testInput2[0], testInput2[1]), testOutput2, "<code>combinations(4, 6)</code> should return <code>[[0,1,2,3], [0,1,2,4], [0,1,2,5], [0,1,3,4], [0,1,3,5], [0,1,4,5], [0,2,3,4], [0,2,3,5], [0,2,4,5], [0,3,4,5], [1,2,3,4], [1,2,3,5], [1,2,4,5], [1,3,4,5], [2,3,4,5]]</code>");'
- text: <code>combinations</code> is a function.
testString: assert(typeof combinations === 'function');
- text: <code>combinations(3, 5)</code> should return <code>[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]</code>.
testString: assert.deepEqual(combinations(testInput1[0], testInput1[1]), testOutput1);
- text: <code>combinations(4, 6)</code> should return <code>[[0,1,2,3], [0,1,2,4], [0,1,2,5], [0,1,3,4], [0,1,3,5], [0,1,4,5], [0,2,3,4], [0,2,3,5], [0,2,4,5], [0,3,4,5], [1,2,3,4], [1,2,3,5], [1,2,4,5], [1,3,4,5], [2,3,4,5]]</code>
testString: assert.deepEqual(combinations(testInput2[0], testInput2[1]), testOutput2);
```
@@ -45,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function combinations (m, n) {
function combinations(m, n) {
// Good luck!
return true;
}
@@ -54,12 +57,16 @@ function combinations (m, n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testInput1 = [3, 5];
const testOutput1 = [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]];
const testInput2 = [4, 6];
const testOutput2 = [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]];
```
</div>
@@ -70,6 +77,28 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function combinations(m, n) {
const nArr = [...Array(n).keys()];
return (function generateCombinations (size, numArr) {
const ret = [];
for (let i = 0; i < numArr.length; i++) {
if (size === 1) {
ret.push([numArr[i]]);
}
else {
const sub = generateCombinations(size - 1, numArr.slice(i + 1, numArr.length));
for (let subI = 0; subI < sub.length; subI++) {
const next = sub[subI];
next.unshift(numArr[i]);
ret.push(next);
}
}
}
return ret;
}(m, nArr));
}
```
</section>

View File

@@ -2,15 +2,32 @@
title: Comma quibbling
id: 596e414344c3b2872167f0fe
challengeType: 5
videoUrl: ''
forumTopicId: 302234
localeTitle: Запястья
---
## Description
<section id="description"><p> Comma quibbling - это задача, первоначально заданная Эриком Липпертом в его <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx" title="ссылка: http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx">блоге</a> . </p> Задача: <p> Напишите функцию для генерации вывода строки, которая представляет собой конкатенацию входных слов из списка / последовательности, где: </p> Ввод без слов выводит строку вывода только двух символов скобок «{}». Ввод только одного слова, например [&quot;ABC&quot;], выводит строку вывода слова внутри двух фигурных скобок, например, &quot;{ABC}&quot;. Ввод двух слов, например [&quot;ABC&quot;, &quot;DEF&quot;], выдает строку вывода двух слов внутри двух фигурных скобок словами, разделенными строкой &quot;и&quot;, например &quot;{ABC и DEF}&quot;. Ввод трех или более слов, например [&quot;ABC&quot;, &quot;DEF&quot;, &quot;G&quot;, &quot;H&quot;], выводит строку вывода всего, кроме последнего слова, разделенного символом &quot;,&quot; с последним словом, разделенным символом &quot;и&quot; «и все в фигурных скобках; например, «{ABC, DEF, G и H}». <p> Протестируйте свою функцию со следующей серией входов, показывающей ваш вывод здесь, на этой странице: </p> [] # (Нет входных слов). [&quot;ABC&quot;] [&quot;ABC&quot;, &quot;DEF&quot;] [&quot;ABC&quot;, &quot;DEF&quot;, &quot;G&quot;, &quot;H&quot;] <p> Примечание. Предположим, что для этой задачи слова являются непустыми строками символов верхнего регистра. </p></section>
<section id='description'>
<p> Comma quibbling - это задача, первоначально заданная Эриком Липпертом в его <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx" title="ссылка: http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx">блоге</a> . </p> Задача: <p> Напишите функцию для генерации вывода строки, которая представляет собой конкатенацию входных слов из списка / последовательности, где: </p> Ввод без слов выводит строку вывода только двух символов скобок «{}». Ввод только одного слова, например [&quot;ABC&quot;], выводит строку вывода слова внутри двух фигурных скобок, например, &quot;{ABC}&quot;. Ввод двух слов, например [&quot;ABC&quot;, &quot;DEF&quot;], выдает строку вывода двух слов внутри двух фигурных скобок словами, разделенными строкой &quot;и&quot;, например &quot;{ABC и DEF}&quot;. Ввод трех или более слов, например [&quot;ABC&quot;, &quot;DEF&quot;, &quot;G&quot;, &quot;H&quot;], выводит строку вывода всего, кроме последнего слова, разделенного символом &quot;,&quot; с последним словом, разделенным символом &quot;и&quot; «и все в фигурных скобках; например, «{ABC, DEF, G и H}». <p> Протестируйте свою функцию со следующей серией входов, показывающей ваш вывод здесь, на этой странице: </p> [] # (Нет входных слов). [&quot;ABC&quot;] [&quot;ABC&quot;, &quot;DEF&quot;] [&quot;ABC&quot;, &quot;DEF&quot;, &quot;G&quot;, &quot;H&quot;] <p> Примечание. Предположим, что для этой задачи слова являются непустыми строками символов верхнего регистра. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
<ol>
<li>An input of no words produces the output string of just the two brace characters (<code>"{}"</code>)</li>
<li>An input of just one word, e.g. <code>["ABC"]</code>, produces the output string of the word inside the two braces, e.g. <code>"{ABC}"</code></li>
<li>An input of two words, e.g. <code>["ABC", "DEF"]</code>, produces the output string of the two words inside the two braces with the words separated by the string <code>" and "</code>, e.g. <code>"{ABC and DEF}"</code></li>
<li>An input of three or more words, e.g. <code>["ABC", "DEF", "G", "H"]</code>, produces the output string of all but the last word separated by <code>", "</code> with the last word separated by <code>" and "</code> and all within braces; e.g. <code>"{ABC, DEF, G and H}"</code></li>
</ol>
Test your function with the following series of inputs showing your output here on this page:
<ul>
<li>[] # (No input words).</li>
<li>["ABC"]</li>
<li>["ABC", "DEF"]</li>
<li>["ABC", "DEF", "G", "H"]</li>
</ul>
<strong>Note:</strong> Assume words are non-empty strings of uppercase characters for this task.
</section>
## Tests
@@ -18,18 +35,18 @@ localeTitle: Запястья
```yml
tests:
- text: <code>quibble</code> - это функция.
testString: 'assert(typeof quibble === "function", "<code>quibble</code> is a function.");'
- text: '<code>quibble([&quot;ABC&quot;])</code> должен возвращать строку.'
testString: 'assert(typeof quibble(["ABC"]) === "string", "<code>quibble(["ABC"])</code> should return a string.");'
- text: '<code>quibble([])</code> должен возвращать &quot;{}&quot;.'
testString: 'assert.equal(quibble(testCases[0]), results[0], "<code>quibble([])</code> should return "{}".");'
- text: '<code>quibble([&quot;ABC&quot;])</code> должен вернуть &quot;{ABC}&quot;.'
testString: 'assert.equal(quibble(testCases[1]), results[1], "<code>quibble(["ABC"])</code> should return "{ABC}".");'
- text: '<code>quibble([&quot;ABC&quot;, &quot;DEF&quot;])</code> должен возвращать &quot;{ABC и DEF}&quot;.'
testString: 'assert.equal(quibble(testCases[2]), results[2], "<code>quibble(["ABC", "DEF"])</code> should return "{ABC and DEF}".");'
- text: '<code>quibble([&quot;ABC&quot;, &quot;DEF&quot;, &quot;G&quot;, &quot;H&quot;])</code> должны возвращать &quot;{ABC, DEF, G и H}&quot;.'
testString: 'assert.equal(quibble(testCases[3]), results[3], "<code>quibble(["ABC", "DEF", "G", "H"])</code> should return "{ABC,DEF,G and H}".");'
- text: <code>quibble</code> is a function.
testString: assert(typeof quibble === 'function');
- text: <code>quibble(["ABC"])</code> should return a string.
testString: assert(typeof quibble(["ABC"]) === 'string');
- text: <code>quibble([])</code> should return "{}".
testString: assert.equal(quibble(testCases[0]), results[0]);
- text: <code>quibble(["ABC"])</code> should return "{ABC}".
testString: assert.equal(quibble(testCases[1]), results[1]);
- text: <code>quibble(["ABC", "DEF"])</code> should return "{ABC and DEF}".
testString: assert.equal(quibble(testCases[2]), results[2]);
- text: <code>quibble(["ABC", "DEF", "G", "H"])</code> should return "{ABC,DEF,G and H}".
testString: assert.equal(quibble(testCases[3]), results[3]);
```
@@ -41,7 +58,7 @@ tests:
<div id='js-seed'>
```js
function quibble (words) {
function quibble(words) {
// Good luck!
return true;
}
@@ -50,12 +67,13 @@ function quibble (words) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]];
const results = ["{}", "{ABC}", "{ABC and DEF}", "{ABC,DEF,G and H}"];
```
</div>
@@ -66,6 +84,13 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function quibble(words) {
return "{" +
words.slice(0, words.length - 1).join(",") +
(words.length > 1 ? " and " : "") +
(words[words.length - 1] || '') +
"}";
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Compare a list of strings
id: 596e457071c35c882915b3e4
challengeType: 5
videoUrl: ''
forumTopicId: 302235
localeTitle: Сравнить список строк
---
## Description
<section id="description"><p> Учитывая <a href="https://en.wikipedia.org/wiki/List_(abstract_data_type)" title="wp: List_ (abstract_data_type)">список</a> произвольно многих строк, реализуйте функцию для каждого из следующих условий: </p> если все они лексически равны, если каждая строка лексически меньше, чем одна после нее (т. е. является ли список в строгом порядке) </section>
<section id='description'>
<p> Учитывая <a href="https://en.wikipedia.org/wiki/List_(abstract_data_type)" title="wp: List_ (abstract_data_type)">список</a> произвольно многих строк, реализуйте функцию для каждого из следующих условий: </p> если все они лексически равны, если каждая строка лексически меньше, чем одна после нее (т. е. является ли список в строгом порядке)
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,30 +21,30 @@ localeTitle: Сравнить список строк
```yml
tests:
- text: <code>allEqual</code> - это функция.
testString: 'assert(typeof allEqual === "function", "<code>allEqual</code> is a function.");'
- text: <code>azSorted</code> - это функция.
testString: 'assert(typeof azSorted === "function", "<code>azSorted</code> is a function.");'
- text: '<code>allEqual([&quot;AA&quot;, &quot;AA&quot;, &quot;AA&quot;, &quot;AA&quot;])</code> возвращает true.'
testString: 'assert(allEqual(testCases[0]), "<code>allEqual(["AA", "AA", "AA", "AA"])</code> returns true.");'
- text: '<code>azSorted([&quot;AA&quot;, &quot;AA&quot;, &quot;AA&quot;, &quot;AA&quot;])</code> возвращает false.'
testString: 'assert(!azSorted(testCases[0]), "<code>azSorted(["AA", "AA", "AA", "AA"])</code> returns false.");'
- text: '<code>allEqual([&quot;AA&quot;, &quot;ACB&quot;, &quot;BB&quot;, &quot;CC&quot;])</code> возвращает false.'
testString: 'assert(!allEqual(testCases[1]), "<code>allEqual(["AA", "ACB", "BB", "CC"])</code> returns false.");'
- text: '<code>azSorted([&quot;AA&quot;, &quot;ACB&quot;, &quot;BB&quot;, &quot;CC&quot;])</code> возвращает true.'
testString: 'assert(azSorted(testCases[1]), "<code>azSorted(["AA", "ACB", "BB", "CC"])</code> returns true.");'
- text: '<code>allEqual([])</code> возвращает true.'
testString: 'assert(allEqual(testCases[2]), "<code>allEqual([])</code> returns true.");'
- text: '<code>azSorted([])</code> возвращает true.'
testString: 'assert(azSorted(testCases[2]), "<code>azSorted([])</code> returns true.");'
- text: '<code>allEqual([&quot;AA&quot;])</code> возвращает true.'
testString: 'assert(allEqual(testCases[3]), "<code>allEqual(["AA"])</code> returns true.");'
- text: '<code>azSorted([&quot;AA&quot;])</code> возвращает true.'
testString: 'assert(azSorted(testCases[3]), "<code>azSorted(["AA"])</code> returns true.");'
- text: '<code>allEqual([&quot;BB&quot;, &quot;AA&quot;])</code> возвращает false.'
testString: 'assert(!allEqual(testCases[4]), "<code>allEqual(["BB", "AA"])</code> returns false.");'
- text: '<code>azSorted([&quot;BB&quot;, &quot;AA&quot;])</code> возвращает false.'
testString: 'assert(!azSorted(testCases[4]), "<code>azSorted(["BB", "AA"])</code> returns false.");'
- text: <code>allEqual</code> is a function.
testString: assert(typeof allEqual === 'function');
- text: <code>azSorted</code> is a function.
testString: assert(typeof azSorted === 'function');
- text: <code>allEqual(["AA", "AA", "AA", "AA"])</code> returns true.
testString: assert(allEqual(testCases[0]));
- text: <code>azSorted(["AA", "AA", "AA", "AA"])</code> returns false.
testString: assert(!azSorted(testCases[0]));
- text: <code>allEqual(["AA", "ACB", "BB", "CC"])</code> returns false.
testString: assert(!allEqual(testCases[1]));
- text: <code>azSorted(["AA", "ACB", "BB", "CC"])</code> returns true.
testString: assert(azSorted(testCases[1]));
- text: <code>allEqual([])</code> returns true.
testString: assert(allEqual(testCases[2]));
- text: <code>azSorted([])</code> returns true.
testString: assert(azSorted(testCases[2]));
- text: <code>allEqual(["AA"])</code> returns true.
testString: assert(allEqual(testCases[3]));
- text: <code>azSorted(["AA"])</code> returns true.
testString: assert(azSorted(testCases[3]));
- text: <code>allEqual(["BB", "AA"])</code> returns false.
testString: assert(!allEqual(testCases[4]));
- text: <code>azSorted(["BB", "AA"])</code> returns false.
testString: assert(!azSorted(testCases[4]));
```
@@ -53,12 +56,12 @@ tests:
<div id='js-seed'>
```js
function allEqual (arr) {
function allEqual(arr) {
// Good luck!
return true;
}
function azSorted (arr) {
function azSorted(arr) {
// Good luck!
return true;
}
@@ -67,12 +70,12 @@ function azSorted (arr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [['AA', 'AA', 'AA', 'AA'], ['AA', 'ACB', 'BB', 'CC'], [], ['AA'], ['BB', 'AA']];
```
</div>
@@ -83,6 +86,21 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function allEqual(a) {
let out = true;
let i = 0;
while (++i < a.length) {
out = out && (a[i - 1] === a[i]);
} return out;
}
function azSorted(a) {
let out = true;
let i = 0;
while (++i < a.length) {
out = out && (a[i - 1] < a[i]);
} return out;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Convert seconds to compound duration
id: 596fd036dc1ab896c5db98b1
challengeType: 5
videoUrl: ''
forumTopicId: 302236
localeTitle: Преобразование секунд в составную продолжительность
---
## Description
<section id="description"> Задача: <p> Внедрите функцию, которая: </p> принимает положительное целое число, представляющее продолжительность в секундах в качестве входных данных (например, <code>100</code> ), и возвращает строку, которая показывает ту же самую длительность, разложенную на недели, дни, часы, минуты и секунды, как описано ниже (например, « <code>1 min, 40 sec</code> «). <p> Продемонстрируйте, что он проходит следующие три теста: </p><p style="font-size:115%; margin:1em 0 0 0"> Испытательные случаи </p><table><tbody><tr><th> номер ввода </th><th> номер выхода </th></tr><tr><td> 7259 </td><td> <code>2 hr, 59 sec</code> </td> </tr><tr><td> 86400 </td><td> <code>1 d</code> </td> </tr><tr><td> 6000000 </td><td> <code>9 wk, 6 d, 10 hr, 40 min</code> </td> </tr></tbody></table><p style="font-size:115%; margin:1em 0 0 0"> Детали </p> Следует использовать следующие пять единиц: <table><tbody><tr><th> Ед. изм </th><th> суффикс, используемый для вывода </th><th> преобразование </th></tr><tr><td> неделю </td><td> <code>wk</code> </td> <td> 1 неделя = 7 дней </td></tr><tr><td> день </td><td> <code>d</code> </td> <td> 1 день = 24 часа </td></tr><tr><td> час </td><td> <code>hr</code> </td> <td> 1 час = 60 минут </td></tr><tr><td> минут </td><td> <code>min</code> </td> <td> 1 минута = 60 секунд </td></tr><tr><td> второй </td><td> <code>sec</code> </td> <td></td></tr></tbody></table> Тем не менее, включают только количества с ненулевыми значениями на выходе (например, return « <code>1 d</code> », а не « <code>0 wk, 1 d, 0 hr, 0 min, 0 sec</code> »). Увеличивайте более высокий приоритет блоков по сравнению с меньшими (например, возврат <code>2 min, 10 sec</code> а не <code>1 min, 70 sec</code> или <code>130 sec</code> ). Обозначьте форматирование, показанное в тестовых сценариях (количества, отсортированные от наибольшего до наименьшего и разделенные запятой + пробелом, значение и единица каждая величина разделяется пробелом). <p></p><hr style="margin:1em 0;"><p></p></section>
<section id='description'>
Задача: <p> Внедрите функцию, которая: </p> принимает положительное целое число, представляющее продолжительность в секундах в качестве входных данных (например, <code>100</code> ), и возвращает строку, которая показывает ту же самую длительность, разложенную на недели, дни, часы, минуты и секунды, как описано ниже (например, « <code>1 min, 40 sec</code> «). <p> Продемонстрируйте, что он проходит следующие три теста: </p><p style="font-size:115%; margin:1em 0 0 0"> Испытательные случаи </p><table><tbody><tr><th> номер ввода </th><th> номер выхода </th></tr><tr><td> 7259 </td><td> <code>2 hr, 59 sec</code> </td> </tr><tr><td> 86400 </td><td> <code>1 d</code> </td> </tr><tr><td> 6000000 </td><td> <code>9 wk, 6 d, 10 hr, 40 min</code> </td> </tr></tbody></table><p style="font-size:115%; margin:1em 0 0 0"> Детали </p> Следует использовать следующие пять единиц: <table><tbody><tr><th> Ед. изм </th><th> суффикс, используемый для вывода </th><th> преобразование </th></tr><tr><td> неделю </td><td> <code>wk</code> </td> <td> 1 неделя = 7 дней </td></tr><tr><td> день </td><td> <code>d</code> </td> <td> 1 день = 24 часа </td></tr><tr><td> час </td><td> <code>hr</code> </td> <td> 1 час = 60 минут </td></tr><tr><td> минут </td><td> <code>min</code> </td> <td> 1 минута = 60 секунд </td></tr><tr><td> второй </td><td> <code>sec</code> </td> <td></td></tr></tbody></table> Тем не менее, включают только количества с ненулевыми значениями на выходе (например, return « <code>1 d</code> », а не « <code>0 wk, 1 d, 0 hr, 0 min, 0 sec</code> »). Увеличивайте более высокий приоритет блоков по сравнению с меньшими (например, возврат <code>2 min, 10 sec</code> а не <code>1 min, 70 sec</code> или <code>130 sec</code> ). Обозначьте форматирование, показанное в тестовых сценариях (количества, отсортированные от наибольшего до наименьшего и разделенные запятой + пробелом, значение и единица каждая величина разделяется пробелом). <p></p><hr style="margin:1em 0;"><p></p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Преобразование секунд в составную п
```yml
tests:
- text: <code>convertSeconds</code> - это функция.
testString: 'assert(typeof convertSeconds === "function", "<code>convertSeconds</code> is a function.");'
- text: '<code>convertSeconds(7259)</code> должен возвращаться <code>2 hr, 59 sec</code> .'
testString: 'assert.equal(convertSeconds(testCases[0]), results[0], "<code>convertSeconds(7259)</code> should return <code>2 hr, 59 sec</code>.");'
- text: <code>convertSeconds(86400)</code> должен возвращать <code>1 d</code> .
testString: 'assert.equal(convertSeconds(testCases[1]), results[1], "<code>convertSeconds(86400)</code> should return <code>1 d</code>.");'
- text: '<code>convertSeconds(6000000)</code> должен возвращать <code>9 wk, 6 d, 10 hr, 40 min</code> .'
testString: 'assert.equal(convertSeconds(testCases[2]), results[2], "<code>convertSeconds(6000000)</code> should return <code>9 wk, 6 d, 10 hr, 40 min</code>.");'
- text: <code>convertSeconds</code> is a function.
testString: assert(typeof convertSeconds === 'function');
- text: <code>convertSeconds(7259)</code> should return <code>2 hr, 59 sec</code>.
testString: assert.equal(convertSeconds(testCases[0]), results[0]);
- text: <code>convertSeconds(86400)</code> should return <code>1 d</code>.
testString: assert.equal(convertSeconds(testCases[1]), results[1]);
- text: <code>convertSeconds(6000000)</code> should return <code>9 wk, 6 d, 10 hr, 40 min</code>.
testString: assert.equal(convertSeconds(testCases[2]), results[2]);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function convertSeconds (sec) {
function convertSeconds(sec) {
// Good luck!
return true;
}
@@ -46,12 +49,13 @@ function convertSeconds (sec) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [7259, 86400, 6000000];
const results = ['2 hr, 59 sec', '1 d', '9 wk, 6 d, 10 hr, 40 min'];
```
</div>
@@ -62,6 +66,35 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function convertSeconds(sec) {
const localNames = ['wk', 'd', 'hr', 'min', 'sec'];
// compoundDuration :: [String] -> Int -> String
const compoundDuration = (labels, intSeconds) =>
weekParts(intSeconds)
.map((v, i) => [v, labels[i]])
.reduce((a, x) =>
a.concat(x[0] ? [`${x[0]} ${x[1] || '?'}`] : []), []
)
.join(', ');
// weekParts :: Int -> [Int]
const weekParts = intSeconds => [0, 7, 24, 60, 60]
.reduceRight((a, x) => {
const r = a.rem;
const mod = x !== 0 ? r % x : r;
return {
rem: (r - mod) / (x || 1),
parts: [mod].concat(a.parts)
};
}, {
rem: intSeconds,
parts: []
})
.parts;
return compoundDuration(localNames, sec);
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Count occurrences of a substring
id: 596fda99c69f779975a1b67d
challengeType: 5
videoUrl: ''
forumTopicId: 302237
localeTitle: Количество вхождений подстроки
---
## Description
<section id="description"> Задача: <p> Создайте функцию или покажите встроенную функцию, чтобы подсчитать количество неперекрывающихся вхождений подстроки внутри строки. </p><p> Функция должна принимать два аргумента: </p> первый аргумент - строка для поиска, а вторая - подстрока, которую нужно искать. <p> Он должен возвращать целочисленное число. </p><p> Соответствие должно давать наибольшее количество совпадающих совпадений. </p><p> В общем, это по существу означает совмещение слева направо или справа налево. </p></section>
<section id='description'>
Задача: <p> Создайте функцию или покажите встроенную функцию, чтобы подсчитать количество неперекрывающихся вхождений подстроки внутри строки. </p><p> Функция должна принимать два аргумента: </p> первый аргумент - строка для поиска, а вторая - подстрока, которую нужно искать. <p> Он должен возвращать целочисленное число. </p><p> Соответствие должно давать наибольшее количество совпадающих совпадений. </p><p> В общем, это по существу означает совмещение слева направо или справа налево. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Количество вхождений подстроки
```yml
tests:
- text: <code>countSubstring</code> - это функция.
testString: 'assert(typeof countSubstring === "function", "<code>countSubstring</code> is a function.");'
- text: '<code>countSubstring(&quot;the three truths&quot;, &quot;th&quot;)</code> должны возвращать <code>3</code> .'
testString: 'assert.equal(countSubstring(testCases[0], searchString[0]), results[0], "<code>countSubstring("the three truths", "th")</code> should return <code>3</code>.");'
- text: '<code>countSubstring(&quot;ababababab&quot;, &quot;abab&quot;)</code> должен возвращать <code>2</code> .'
testString: 'assert.equal(countSubstring(testCases[1], searchString[1]), results[1], "<code>countSubstring("ababababab", "abab")</code> should return <code>2</code>.");'
- text: '<code>countSubstring(&quot;abaabba*bbaba*bbab&quot;, &quot;a*b&quot;)</code> должен возвращать <code>2</code> .'
testString: 'assert.equal(countSubstring(testCases[2], searchString[2]), results[2], "<code>countSubstring("abaabba*bbaba*bbab", "a*b")</code> should return <code>2</code>.");'
- text: <code>countSubstring</code> is a function.
testString: assert(typeof countSubstring === 'function');
- text: <code>countSubstring("the three truths", "th")</code> should return <code>3</code>.
testString: assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
- text: <code>countSubstring("ababababab", "abab")</code> should return <code>2</code>.
testString: assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
- text: <code>countSubstring("abaabba*bbaba*bbab", "a*b")</code> should return <code>2</code>.
testString: assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function countSubstring (str, subStr) {
function countSubstring(str, subStr) {
// Good luck!
return true;
}
@@ -46,12 +49,14 @@ function countSubstring (str, subStr) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];
```
</div>
@@ -62,6 +67,11 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function countSubstring(str, subStr) {
const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
const matches = str.match(new RegExp(escapedSubStr, 'g'));
return matches ? matches.length : 0;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Count the coins
id: 59713bd26bdeb8a594fb9413
challengeType: 5
videoUrl: ''
forumTopicId: 302238
localeTitle: Подсчитайте монеты
---
## Description
<section id="description"><p> В <a href="https://en.wikipedia.org/wiki/United_States" title="ссылка: https://en.wikipedia.org/wiki/United_States">американской</a> валюте существует четыре типа обычных монет: </p> кварталы (25 центов), десять центов (10 центов), никель (5 центов) и пенни (1 цент) <p> Существует шесть способов внести изменения в 15 центов: </p> Копейка и никель Копейка и 5 пенни 3 никеля 2 никеля и 5 пенни Никель и 10 пенни 15 пенни Задача: <p> Внедрить функцию, чтобы определить, сколько способов внести изменения в доллар, используя эти общие монеты? (1 доллар = 100 центов). </p> Ссылка: <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52" title="ссылка: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52">алгоритм из MIT Press</a> . </section>
<section id='description'>
<p> В <a href="https://en.wikipedia.org/wiki/United_States" title="ссылка: https://en.wikipedia.org/wiki/United_States">американской</a> валюте существует четыре типа обычных монет: </p> кварталы (25 центов), десять центов (10 центов), никель (5 центов) и пенни (1 цент) <p> Существует шесть способов внести изменения в 15 центов: </p> Копейка и никель Копейка и 5 пенни 3 никеля 2 никеля и 5 пенни Никель и 10 пенни 15 пенни Задача: <p> Внедрить функцию, чтобы определить, сколько способов внести изменения в доллар, используя эти общие монеты? (1 доллар = 100 центов). </p> Ссылка: <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52" title="ссылка: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52">алгоритм из MIT Press</a> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function to determine how many ways there are to make change for a dollar using these common coins (1 dollar = 100 cents)
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Подсчитайте монеты
```yml
tests:
- text: <code>countCoins</code> - это функция.
testString: 'assert(typeof countCoins === "function", "<code>countCoins</code> is a function.");'
- text: <code>countCoints()</code> должен возвращать 242.
testString: 'assert.equal(countCoins(), 242, "<code>countCoints()</code> should return 242.");'
- text: <code>countCoins</code> is a function.
testString: assert(typeof countCoins === 'function');
- text: <code>countCoints()</code> should return 242.
testString: assert.equal(countCoins(), 242);
```
@@ -33,7 +36,7 @@ tests:
<div id='js-seed'>
```js
function countCoins () {
function countCoins() {
// Good luck!
return true;
}
@@ -42,14 +45,31 @@ function countCoins () {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function countCoins() {
let t = 100;
const operands = [1, 5, 10, 25];
const targetsLength = t + 1;
const operandsLength = operands.length;
t = [1];
for (let a = 0; a < operandsLength; a++) {
for (let b = 1; b < targetsLength; b++) {
// initialise undefined target
t[b] = t[b] ? t[b] : 0;
// accumulate target + operand ways
t[b] += (b < operands[a]) ? 0 : t[b - operands[a]];
}
}
return t[targetsLength - 1];
}
```
</section>

View File

@@ -2,15 +2,27 @@
title: Cramer's rule
id: 59713da0a428c1a62d7db430
challengeType: 5
videoUrl: ''
forumTopicId: 302239
localeTitle: Правило Крамера
---
## Description
<section id="description"><p> В <a href="https://en.wikipedia.org/wiki/linear algebra" title="wp: линейная алгебра">линейной алгебре</a> <a href="https://en.wikipedia.org/wiki/Cramer&#x27;s rule" title="wp: правило Крамера">правило Крамера</a> является явной формулой для решения <a href="https://en.wikipedia.org/wiki/system of linear equations" title="wp: система линейных уравнений">системы линейных уравнений</a> с таким количеством уравнений, как неизвестные, действительные всякий раз, когда система имеет единственное решение. Он выражает решение в терминах детерминантов матрицы (квадратного) коэффициента и полученных из нее матриц путем замены одного столбца на вектор правых частей уравнений. </p><p> Данный </p><p><big></big></p><p> <big>$ \ left \ {\ begin {matrix} a_1x + b_1y + c_1z &amp; = {\ color {red} d_1} \\ a_2x + b_2y + c_2z &amp; = {\ color {red} d_2} \\ a_3x + b_3y + c_3z &amp; = {\ цвет {красный} D_3} \ конец {матрица} \ правом. $</big> </p><p> который в матричном формате </p><p><big></big></p><p> <big>$ \ begin {bmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {bmatrix} \ begin {bmatrix} x \\ y \\ z \ end {bmatrix} = \ begin {bmatrix} {\ color {red} d_1} \\ {\ color {red} d_2} \\ {\ color {red} d_3} \ end {bmatrix}. $</big> </p><p> Тогда значения $ x, y $ и $ z $ можно найти следующим образом: </p><p><big></big></p><p> <big>$ x = \ frac {\ begin {vmatrix} {\ color {red} d_1} &amp; b_1 &amp; c_1 \\ {\ color {red} d_2} &amp; b_2 &amp; c_2 \\ {\ color {red} d_3} &amp; b_3 &amp; c_3 \ end {vmatrix}} {\ begin {vmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {vmatrix}}, \ quad y = \ frac {\ begin {vmatrix} } a_1 &amp; {\ color {red} d_1} &amp; c_1 \\ a_2 &amp; {\ color {red} d_2} &amp; c_2 \\ a_3 &amp; {\ color {red} d_3} &amp; c_3 \ end {vmatrix}} {\ begin {vmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {vmatrix}}, \ text {и} z = \ frac {\ begin {vmatrix} a_1 &amp; b_1 &amp; {\ color {red} d_1} \\ a_2 &amp; b_2 &amp; {\ color {red} d_2} \\ a_3 &amp; b_3 &amp; {\ color {red} d_3} \ end {vmatrix}} {\ begin {vmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {vmatrix}}. $</big> </p> задача <p> Учитывая следующую систему уравнений: </p><p> <big>$ \ begin {cases} 2w-x + 5y + z = -3 \\ 3w + 2x + 2y-6z = -32 \ w + 3x + 3y-z = -47 \\ 5w-2x-3y + 3z = 49 \\ \ end {cases} $</big> </p><p> решаем для <big>$ w $, $ x $, $ y $</big> и <big>$ z $</big> , используя правило Крамера. </p></section>
<section id='description'>
<p> В <a href="https://en.wikipedia.org/wiki/linear algebra" title="wp: линейная алгебра">линейной алгебре</a> <a href="https://en.wikipedia.org/wiki/Cramer&#x27;s rule" title="wp: правило Крамера">правило Крамера</a> является явной формулой для решения <a href="https://en.wikipedia.org/wiki/system of linear equations" title="wp: система линейных уравнений">системы линейных уравнений</a> с таким количеством уравнений, как неизвестные, действительные всякий раз, когда система имеет единственное решение. Он выражает решение в терминах детерминантов матрицы (квадратного) коэффициента и полученных из нее матриц путем замены одного столбца на вектор правых частей уравнений. </p><p> Данный </p><p><big></big></p><p> <big>$ \ left \ {\ begin {matrix} a_1x + b_1y + c_1z &amp; = {\ color {red} d_1} \\ a_2x + b_2y + c_2z &amp; = {\ color {red} d_2} \\ a_3x + b_3y + c_3z &amp; = {\ цвет {красный} D_3} \ конец {матрица} \ правом. $</big> </p><p> который в матричном формате </p><p><big></big></p><p> <big>$ \ begin {bmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {bmatrix} \ begin {bmatrix} x \\ y \\ z \ end {bmatrix} = \ begin {bmatrix} {\ color {red} d_1} \\ {\ color {red} d_2} \\ {\ color {red} d_3} \ end {bmatrix}. $</big> </p><p> Тогда значения $ x, y $ и $ z $ можно найти следующим образом: </p><p><big></big></p><p> <big>$ x = \ frac {\ begin {vmatrix} {\ color {red} d_1} &amp; b_1 &amp; c_1 \\ {\ color {red} d_2} &amp; b_2 &amp; c_2 \\ {\ color {red} d_3} &amp; b_3 &amp; c_3 \ end {vmatrix}} {\ begin {vmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {vmatrix}}, \ quad y = \ frac {\ begin {vmatrix} } a_1 &amp; {\ color {red} d_1} &amp; c_1 \\ a_2 &amp; {\ color {red} d_2} &amp; c_2 \\ a_3 &amp; {\ color {red} d_3} &amp; c_3 \ end {vmatrix}} {\ begin {vmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {vmatrix}}, \ text {и} z = \ frac {\ begin {vmatrix} a_1 &amp; b_1 &amp; {\ color {red} d_1} \\ a_2 &amp; b_2 &amp; {\ color {red} d_2} \\ a_3 &amp; b_3 &amp; {\ color {red} d_3} \ end {vmatrix}} {\ begin {vmatrix} a_1 &amp; b_1 &amp; c_1 \\ a_2 &amp; b_2 &amp; c_2 \\ a_3 &amp; b_3 &amp; c_3 \ end {vmatrix}}. $</big> </p> задача <p> Учитывая следующую систему уравнений: </p><p> <big>$ \ begin {cases} 2w-x + 5y + z = -3 \\ 3w + 2x + 2y-6z = -32 \ w + 3x + 3y-z = -47 \\ 5w-2x-3y + 3z = 49 \\ \ end {cases} $</big> </p><p> решаем для <big>$ w $, $ x $, $ y $</big> и <big>$ z $</big> , используя правило Крамера. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Given the following system of equations:
<big>
$\begin{cases}
2w-x+5y+z=-3 \\
3w+2x+2y-6z=-32 \\
w+3x+3y-z=-47 \\
5w-2x-3y+3z=49 \\
\end{cases}$
</big>
solve for <big>$w$, $x$, $y$</big> and <big>$z$</big>, using Cramer's rule.
</section>
## Tests
@@ -18,12 +30,12 @@ localeTitle: Правило Крамера
```yml
tests:
- text: <code>cramersRule</code> - это функция.
testString: 'assert(typeof cramersRule === "function", "<code>cramersRule</code> is a function.");'
- text: '<code>cramersRule([[2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3]], [-3, -32, -47, 49])</code> должны возвращать <code>[2, -12, -4, 1]</code> .'
testString: 'assert.deepEqual(cramersRule(matrices[0], freeTerms[0]), answers[0], "<code>cramersRule([[2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3]], [-3, -32, -47, 49])</code> should return <code>[2, -12, -4, 1]</code>.");'
- text: '<code>cramersRule([[3, 1, 1], [2, 2, 5], [1, -3, -4]], [3, -1, 2])</code> должны возвращать <code>[1, 1, -1]</code> .'
testString: 'assert.deepEqual(cramersRule(matrices[1], freeTerms[1]), answers[1], "<code>cramersRule([[3, 1, 1], [2, 2, 5], [1, -3, -4]], [3, -1, 2])</code> should return <code>[1, 1, -1]</code>.");'
- text: <code>cramersRule</code> is a function.
testString: assert(typeof cramersRule === 'function');
- text: <code>cramersRule([[2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3]], [-3, -32, -47, 49])</code> should return <code>[2, -12, -4, 1]</code>.
testString: assert.deepEqual(cramersRule(matrices[0], freeTerms[0]), answers[0]);
- text: <code>cramersRule([[3, 1, 1], [2, 2, 5], [1, -3, -4]], [3, -1, 2])</code> should return <code>[1, 1, -1]</code>.
testString: assert.deepEqual(cramersRule(matrices[1], freeTerms[1]), answers[1]);
```
@@ -35,7 +47,7 @@ tests:
<div id='js-seed'>
```js
function cramersRule (matrix, freeTerms) {
function cramersRule(matrix, freeTerms) {
// Good luck!
return true;
}
@@ -44,12 +56,27 @@ function cramersRule (matrix, freeTerms) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const matrices = [
[
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3]
],
[
[3, 1, 1],
[2, 2, 5],
[1, -3, -4]
]
];
const freeTerms = [[-3, -32, -47, 49], [3, -1, 2]];
const answers = [[2, -12, -4, 1], [1, 1, -1]];
```
</div>
@@ -60,6 +87,85 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
/**
* Compute Cramer's Rule
* @param {array} matrix x,y,z, etc. terms
* @param {array} freeTerms
* @return {array} solution for x,y,z, etc.
*/
function cramersRule(matrix, freeTerms) {
const det = detr(matrix);
const returnArray = [];
let i;
for (i = 0; i < matrix[0].length; i++) {
const tmpMatrix = insertInTerms(matrix, freeTerms, i);
returnArray.push(detr(tmpMatrix) / det);
}
return returnArray;
}
/**
* Inserts single dimensional array into
* @param {array} matrix multidimensional array to have ins inserted into
* @param {array} ins single dimensional array to be inserted vertically into matrix
* @param {array} at zero based offset for ins to be inserted into matrix
* @return {array} New multidimensional array with ins replacing the at column in matrix
*/
function insertInTerms(matrix, ins, at) {
const tmpMatrix = clone(matrix);
let i;
for (i = 0; i < matrix.length; i++) {
tmpMatrix[i][at] = ins[i];
}
return tmpMatrix;
}
/**
* Compute the determinate of a matrix. No protection, assumes square matrix
* function borrowed, and adapted from MIT Licensed numericjs library (www.numericjs.com)
* @param {array} m Input Matrix (multidimensional array)
* @return {number} result rounded to 2 decimal
*/
function detr(m) {
let ret = 1;
let j;
let k;
const A = clone(m);
const n = m[0].length;
let alpha;
for (j = 0; j < n - 1; j++) {
k = j;
for (let i = j + 1; i < n; i++) { if (Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } }
if (k !== j) {
const temp = A[k]; A[k] = A[j]; A[j] = temp;
ret *= -1;
}
const Aj = A[j];
for (let i = j + 1; i < n; i++) {
const Ai = A[i];
alpha = Ai[j] / Aj[j];
for (k = j + 1; k < n - 1; k += 2) {
const k1 = k + 1;
Ai[k] -= Aj[k] * alpha;
Ai[k1] -= Aj[k1] * alpha;
}
if (k !== n) { Ai[k] -= Aj[k] * alpha; }
}
if (Aj[j] === 0) { return 0; }
ret *= Aj[j];
}
return Math.round(ret * A[j][j] * 100) / 100;
}
/**
* Clone two dimensional Array using ECMAScript 5 map function and EcmaScript 3 slice
* @param {array} m Input matrix (multidimensional array) to clone
* @return {array} New matrix copy
*/
function clone(m) {
return m.map(a => a.slice());
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Date format
id: 59669d08d75b60482359409f
challengeType: 5
videoUrl: ''
forumTopicId: 302243
localeTitle: Формат даты
---
## Description
<section id="description"> Задача: <p> Возвращает массив с текущей датой в форматах: </p><p> - 2007-11-23 и </p><p> - Воскресенье, 23 ноября 2007 г. </p><p> Пример вывода: <code>[&#39;2007-11-23&#39;, &#39;Sunday, November 23, 2007&#39;]</code> </p></section>
<section id='description'>
Задача: <p> Возвращает массив с текущей датой в форматах: </p><p> - 2007-11-23 и </p><p> - Воскресенье, 23 ноября 2007 г. </p><p> Пример вывода: <code>[&#39;2007-11-23&#39;, &#39;Sunday, November 23, 2007&#39;]</code> </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Формат даты
```yml
tests:
- text: <code>getDateFormats</code> - это функция.
testString: 'assert(typeof getDateFormats === "function", "<code>getDateFormats</code> is a function.");'
- text: Должен возвращать объект.
testString: 'assert(typeof getDateFormats() === "object", "Should return an object.");'
- text: Должен возвращать массив с 2 элементами.
testString: 'assert(getDateFormats().length === 2, "Should returned an array with 2 elements.");'
- text: Должна вернуть правильную дату в правильном формате
testString: 'assert.deepEqual(getDateFormats(), dates, equalsMessage);'
- text: <code>getDateFormats</code> is a function.
testString: assert(typeof getDateFormats === 'function');
- text: Should return an object.
testString: assert(typeof getDateFormats() === 'object');
- text: Should returned an array with 2 elements.
testString: assert(getDateFormats().length === 2);
- text: Should return the correct date in the right format
testString: assert.deepEqual(getDateFormats(), dates, equalsMessage);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function getDateFormats () {
function getDateFormats() {
// Good luck!
return true;
}
@@ -46,12 +49,22 @@ function getDateFormats () {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const getDateSolution = () => {
const date = new Date();
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const fmt1 = `${date.getFullYear()}-${(1 + date.getMonth())}-${date.getDate()}`;
const fmt2 = `${weekdays[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
return [fmt1, fmt2];
};
const dates = getDateSolution();
const equalsMessage = `message: <code>getDataFormats()</code> should return <code>["${dates[0]}", "${dates[1]}"]</code>.`;
```
</div>
@@ -62,6 +75,14 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function getDateFormats() {
const date = new Date();
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const fmt1 = `${date.getFullYear()}-${(1 + date.getMonth())}-${date.getDate()}`;
const fmt2 = `${weekdays[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
return [fmt1, fmt2];
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Date manipulation
id: 5966c21cf732a95f1b67dd28
challengeType: 5
videoUrl: ''
forumTopicId: 302244
localeTitle: Обработка даты
---
## Description
<section id="description"> Задача: <p> Учитывая строку даты в EST, выведите указанную дату в виде строки с добавлением 12 часов к времени. </p><p> Часовой пояс должен быть сохранен. </p><p> Пример ввода: </p><p> <code>&quot;March 7 2009 7:30pm EST&quot;</code> </p> <p> Пример вывода: </p><p> <code>&quot;March 8 2009 7:30am EST&quot;</code> </p> </section>
<section id='description'>
Задача: <p> Учитывая строку даты в EST, выведите указанную дату в виде строки с добавлением 12 часов к времени. </p><p> Часовой пояс должен быть сохранен. </p><p> Пример ввода: </p><p> <code>&quot;March 7 2009 7:30pm EST&quot;</code> </p> <p> Пример вывода: </p><p> <code>&quot;March 8 2009 7:30am EST&quot;</code> </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Обработка даты
```yml
tests:
- text: <code>add12Hours</code> - это функция.
testString: 'assert(typeof add12Hours === "function", "<code>add12Hours</code> is a function.");'
- text: <code>add12Hours(dateString)</code> должен возвращать строку.
testString: 'assert(typeof add12Hours(tests[0]) === "string", "<code>add12Hours(dateString)</code> should return a string.");'
- text: '<code>add12Hours(&quot;&quot; + tests[0] + &quot;&quot;)</code> должны возвращать <code>&quot;&quot; + answers[0] + &quot;&quot;</code>'
testString: 'assert(add12Hours(tests[0]) === answers[0], "<code>add12Hours("" + tests[0] + "")</code> should return <code>"" + answers[0] + ""</code>");'
- text: 'Должен ли день обмена менять. <code>add12Hours(&quot;&quot; + tests[1] + &quot;&quot;)</code> должны возвращать <code>&quot;&quot; + answers[1] + &quot;&quot;</code>'
testString: 'assert(add12Hours(tests[1]) === answers[1], "Should handel day change. <code>add12Hours("" + tests[1] + "")</code> should return <code>"" + answers[1] + ""</code>");'
- text: 'Должен ли перенос месяца в високосный год. <code>add12Hours(&quot;&quot; + tests[2] + &quot;&quot;)</code> должны возвращать <code>&quot;&quot; + answers[2] + &quot;&quot;</code>'
testString: 'assert(add12Hours(tests[2]) === answers[2], "Should handel month change in a leap years. <code>add12Hours("" + tests[2] + "")</code> should return <code>"" + answers[2] + ""</code>");'
- text: 'Должен ли перенос месяца в течение общих лет. <code>add12Hours(&quot;&quot; + tests[3] + &quot;&quot;)</code> должны возвращать <code>&quot;&quot; + answers[3] + &quot;&quot;</code>'
testString: 'assert(add12Hours(tests[3]) === answers[3], "Should handel month change in a common years. <code>add12Hours("" + tests[3] + "")</code> should return <code>"" + answers[3] + ""</code>");'
- text: 'Должен измениться год выпуска. <code>add12Hours(&quot;&quot; + tests[4] + &quot;&quot;)</code> должны возвращать <code>&quot;&quot; + answers[4] + &quot;&quot;</code>'
testString: 'assert(add12Hours(tests[4]) === answers[4], "Should handel year change. <code>add12Hours("" + tests[4] + "")</code> should return <code>"" + answers[4] + ""</code>");'
- text: <code>add12Hours</code> is a function.
testString: assert(typeof add12Hours === 'function');
- text: <code>add12Hours(dateString)</code> should return a string.
testString: assert(typeof add12Hours('January 17 2017 11:43am EST') === 'string');
- text: <code>add12Hours("January 17 2017 11:43am EST")</code> should return <code>"January 17 2017 11:43pm EST"</code>
testString: assert(add12Hours('January 17 2017 11:43am EST') === 'January 17 2017 11:43pm EST');
- text: Should handel day change. <code>add12Hours("March 7 2009 7:30pm EST")</code> should return <code>"March 8 2009 7:30am EST"</code>
testString: assert(add12Hours('March 7 2009 7:30pm EST') === 'March 8 2009 7:30am EST');
- text: Should handel month change in a leap years. <code>add12Hours("February 29 2004 9:15pm EST")</code> should return <code>"March 1 2004 9:15am EST"</code>
testString: assert(add12Hours('February 29 2004 9:15pm EST') === 'March 1 2004 9:15am EST');
- text: Should handel month change in a common years. <code>add12Hours("February 28 1999 3:15pm EST")</code> should return <code>"March 1 1999 3:15am EST"</code>
testString: assert(add12Hours('February 28 1999 3:15pm EST') === 'March 1 1999 3:15am EST');
- text: Should handel year change. <code>add12Hours("December 31 2020 1:45pm EST")</code> should return <code>"January 1 2021 1:45am EST"</code>
testString: assert(add12Hours('December 31 2020 1:45pm EST') === 'January 1 2021 1:45am EST');
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function add12Hours (dateString) {
function add12Hours(dateString) {
// Good luck!
return true;
}
@@ -52,22 +55,42 @@ function add12Hours (dateString) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function add12Hours(dateString) {
const months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
// Get the parts of the string
const parts = dateString.split(' ');
const month = months.indexOf(parts[0]);
const day = parseInt(parts[1], 10);
const year = parseInt(parts[2], 10);
const time = parts[3].split(':');
let hours = parseInt(time[0], 10);
if (time[1].slice(-2) === 'pm') {
hours += 12;
}
const minutes = parseInt(time[1].slice(0, -2), 10);
// Create a date with given parts, and updated hours
const date = new Date();
date.setFullYear(year, month, day);
date.setHours(hours + 12); // Add 12 hours
date.setMinutes(minutes);
let hoursOutput = date.getHours();
let abbreviation = 'am';
if (hoursOutput > 12) {
hoursOutput -= 12;
abbreviation = 'pm';
}
return `${months[date.getMonth()]} ${date.getDate()} ${date.getFullYear()} ${hoursOutput}:${date.getMinutes()}${abbreviation} EST`;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Day of the week
id: 5966f99c45e8976909a85575
challengeType: 5
videoUrl: ''
forumTopicId: 302245
localeTitle: День недели
---
## Description
<section id="description"><p> Компания решает, что всякий раз, когда Xmas падает на воскресенье, они отдают своим работникам все дополнительные оплачиваемые отпуска, так что вместе с любыми праздничными днями работникам не придется работать на следующей неделе (с 25 декабря по 1 января). </p><p> Задача: </p><p> Напишите функцию, которая запускает год начала и конец года и возвращает массив всех лет, в которые 25 декабря будет воскресенье. </p></section>
<section id='description'>
<p> Компания решает, что всякий раз, когда Xmas падает на воскресенье, они отдают своим работникам все дополнительные оплачиваемые отпуска, так что вместе с любыми праздничными днями работникам не придется работать на следующей неделе (с 25 декабря по 1 января). </p><p> Задача: </p><p> Напишите функцию, которая запускает год начала и конец года и возвращает массив всех лет, в которые 25 декабря будет воскресенье. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes a start year and an end year and return an array of all the years where the 25th of December will be a Sunday.
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: День недели
```yml
tests:
- text: <code>findXmasSunday</code> - это функция.
testString: 'assert(typeof findXmasSunday === "function", "<code>findXmasSunday</code> is a function.");'
- text: '<code>findChristmasSunday(2000, 2100)</code> должен возвращать массив.'
testString: 'assert(typeof findXmasSunday(2000, 2100) === "object", "<code>findChristmasSunday(2000, 2100)</code> should return an array.");'
- text: '<code>findChristmasSunday(2008, 2121</code> должен вернуться [1977, 1983, 1988, 1994, 2005, 2011, 2016]'
testString: 'assert.deepEqual(findXmasSunday(1970, 2017), firstSolution, "<code>findChristmasSunday(2008, 2121</code> should return [1977, 1983, 1988, 1994, 2005, 2011, 2016]");'
- text: '<code>findChristmasSunday(2008, 2121</code> должны вернуться [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]'
testString: 'assert.deepEqual(findXmasSunday(2008, 2121), secondSolution, "<code>findChristmasSunday(2008, 2121</code> should return [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]");'
- text: <code>findXmasSunday</code> is a function.
testString: assert(typeof findXmasSunday === 'function');
- text: <code>findChristmasSunday(2000, 2100)</code> should return an array.
testString: assert(typeof findXmasSunday(2000, 2100) === 'object');
- text: <code>findChristmasSunday(2008, 2121</code> should return [1977, 1983, 1988, 1994, 2005, 2011, 2016]
testString: assert.deepEqual(findXmasSunday(1970, 2017), firstSolution);
- text: <code>findChristmasSunday(2008, 2121</code> should return [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]
testString: assert.deepEqual(findXmasSunday(2008, 2121), secondSolution);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function findXmasSunday (start, end) {
function findXmasSunday(start, end) {
// Good luck!
return true;
}
@@ -46,12 +49,13 @@ function findXmasSunday (start, end) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const firstSolution = [1977, 1983, 1988, 1994, 2005, 2011, 2016];
const secondSolution = [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118];
```
</div>
@@ -62,6 +66,16 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function findXmasSunday(start, end) {
const xmasSunday = [];
for (let year = start; year <= end; year++) {
const xmas = new Date(year, 11, 25);
if (xmas.getDay() === 0) {
xmasSunday.push(year);
}
}
return xmasSunday;
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Deal cards for FreeCell
id: 59694356a6e7011f7f1c5f4e
challengeType: 5
videoUrl: ''
forumTopicId: 302246
localeTitle: Карты сделок для FreeCell
---
## Description
<section id="description"><p> Free Cell - это карточная игра для пасьянсов, которую Пол Альфил представил системе PLATO в 1978 году. Джим Хорн в Microsoft заменил имя на FreeCell и переопределил игру для <a href="http://rosettacode.org/wiki/DOS" title="DOS">DOS</a> , а затем <a href="http://rosettacode.org/wiki/Windows" title="Windows">Windows</a> . </p><p> В этой версии реализовано 32000 номеров. ( <a href="http://www.solitairelaboratory.com/fcfaq.html" title="ссылка: http://www.solitairelaboratory.com/fcfaq.html">Часто задаваемые вопросы FreeCell</a> рассказывают об этой истории.) </p><p> Когда игра стала популярной, Джим Хорн раскрыл <a href="http://www.solitairelaboratory.com/mshuffle.txt" title="ссылка: http://www.solitairelaboratory.com/mshuffle.txt">алгоритм</a> , а другие реализации FreeCell начали воспроизводить сделки Microsoft. </p><p> Эти сделки пронумерованы от 1 до 32000. </p><p> Более новые версии от Microsoft имеют 1 миллион сделок, пронумерованных от 1 до 1000000; некоторые реализации позволяют использовать номера за пределами этого диапазона. </p><p> Алгоритм использует этот <a href="http://rosettacode.org/wiki/linear congruential generator" title="линейный конгруэнтный генератор">линейный конгруэнтный генератор</a> от Microsoft C: </p> $ state_ {n + 1} \ equiv 214013 \ times state_n + 2531011 \ pmod {2 ^ {31}} $ $ rand_n = state_n \ div 2 ^ {16} $ $ rand_n $ находится в диапазоне от 0 до 32767. <p> Алгоритм: </p> Выделите RNG с номером сделки. Создайте <a href="http://rosettacode.org/wiki/array" title="массив">массив</a> из 52 карт: туз клубов, туз бриллиантов, туз сердец, туз пик, 2 из клубов, 2 бриллиантов и т. Д. Через звания: туз, 2, 3, 4, 5, 6, 7, 8, 9, 10, Джек, Королева, Король. Индексы массива от 0 до 51, с Ace of Clubs в 0 и King of Spades - 51. Пока массив не будет пустым: выберите случайную карту с индексом ≡ следующее случайное число (длина массива мод). Поменяйте эту случайную карту последней карточкой массива. Удалите эту случайную карту из массива. (Длина массива снижается на 1.) Обработайте эту случайную карту. Сделки все 52 карты, лицевой стороной вверх, через 8 столбцов. Первые 8 карт идут в 8 столбцах, следующие 8 карт идут на первые 8 карт и так далее. Пример: <p> Заказать карты </p><p></p><pre> 1 2 3 4 5 6 7 8
<section id='description'>
<p> Free Cell - это карточная игра для пасьянсов, которую Пол Альфил представил системе PLATO в 1978 году. Джим Хорн в Microsoft заменил имя на FreeCell и переопределил игру для <a href="http://rosettacode.org/wiki/DOS" title="DOS">DOS</a> , а затем <a href="http://rosettacode.org/wiki/Windows" title="Windows">Windows</a> . </p><p> В этой версии реализовано 32000 номеров. ( <a href="http://www.solitairelaboratory.com/fcfaq.html" title="ссылка: http://www.solitairelaboratory.com/fcfaq.html">Часто задаваемые вопросы FreeCell</a> рассказывают об этой истории.) </p><p> Когда игра стала популярной, Джим Хорн раскрыл <a href="http://www.solitairelaboratory.com/mshuffle.txt" title="ссылка: http://www.solitairelaboratory.com/mshuffle.txt">алгоритм</a> , а другие реализации FreeCell начали воспроизводить сделки Microsoft. </p><p> Эти сделки пронумерованы от 1 до 32000. </p><p> Более новые версии от Microsoft имеют 1 миллион сделок, пронумерованных от 1 до 1000000; некоторые реализации позволяют использовать номера за пределами этого диапазона. </p><p> Алгоритм использует этот <a href="http://rosettacode.org/wiki/linear congruential generator" title="линейный конгруэнтный генератор">линейный конгруэнтный генератор</a> от Microsoft C: </p> $ state_ {n + 1} \ equiv 214013 \ times state_n + 2531011 \ pmod {2 ^ {31}} $ $ rand_n = state_n \ div 2 ^ {16} $ $ rand_n $ находится в диапазоне от 0 до 32767. <p> Алгоритм: </p> Выделите RNG с номером сделки. Создайте <a href="http://rosettacode.org/wiki/array" title="массив">массив</a> из 52 карт: туз клубов, туз бриллиантов, туз сердец, туз пик, 2 из клубов, 2 бриллиантов и т. Д. Через звания: туз, 2, 3, 4, 5, 6, 7, 8, 9, 10, Джек, Королева, Король. Индексы массива от 0 до 51, с Ace of Clubs в 0 и King of Spades - 51. Пока массив не будет пустым: выберите случайную карту с индексом ≡ следующее случайное число (длина массива мод). Поменяйте эту случайную карту последней карточкой массива. Удалите эту случайную карту из массива. (Длина массива снижается на 1.) Обработайте эту случайную карту. Сделки все 52 карты, лицевой стороной вверх, через 8 столбцов. Первые 8 карт идут в 8 столбцах, следующие 8 карт идут на первые 8 карт и так далее. Пример: <p> Заказать карты </p><p></p><pre> 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
@@ -29,10 +30,13 @@ localeTitle: Карты сделок для FreeCell
[4C, QS, 9C, 9H, 7C,
[&#39;4S&#39;, &#39;TS&#39;, &#39;2H&#39;, &#39;5D&#39;, &#39;JC&#39;, &#39;6C&#39;, &#39;JH&#39;, &#39;QH&#39;],
[&#39;JD&#39;, &#39;KS&#39;, &#39;KC&#39;, &#39;4H&#39;]
] </pre><p></p> Задача: <p> Напишите функцию, чтобы взять номер сделки и раздавать карты в том же порядке, что и этот алгоритм. </p><p> Функция должна возвращать двухмерный массив, представляющий плату FreeCell. </p><p> Сделки можно также проверить на <a href="http://freecellgamesolutions.com/" title="ссылка: http://freecellgamesolutions.com/">решения FreeCell для 1000000 игр</a> . </p><p> (Вызов видео решения, и он отображает первоначальную сделку.) </p></section>
] </pre><p></p> Задача: <p> Напишите функцию, чтобы взять номер сделки и раздавать карты в том же порядке, что и этот алгоритм. </p><p> Функция должна возвращать двухмерный массив, представляющий плату FreeCell. </p><p> Сделки можно также проверить на <a href="http://freecellgamesolutions.com/" title="ссылка: http://freecellgamesolutions.com/">решения FreeCell для 1000000 игр</a> . </p><p> (Вызов видео решения, и он отображает первоначальную сделку.) </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function to take a deal number and deal cards in the same order as this algorithm. The function must return a two dimensional array representing the FreeCell board.
Deals can also be checked against <a href="https://freecellgamesolutions.com/" target="_blank">FreeCell solutions to 1000000 games</a>. (Summon a video solution, and it displays the initial deal.)
</section>
## Tests
@@ -40,16 +44,16 @@ localeTitle: Карты сделок для FreeCell
```yml
tests:
- text: <code>dealFreeCell</code> - это функция.
testString: 'assert(typeof dealFreeCell === "function", "<code>dealFreeCell</code> is a function.");'
- text: <code>dealFreeCell(seed)</code> должен возвращать объект.
testString: 'assert(typeof dealFreeCell(1) === "object", "<code>dealFreeCell(seed)</code> should return an object.");'
- text: <code>dealFreeCell(seed)</code> должен возвращать массив длиной 7.
testString: 'assert(dealFreeCell(1).length === 7, "<code>dealFreeCell(seed)</code> should return an array of length 7.");'
- text: '<code>dealFreeCell(1)</code> должен возвращать массив, идентичный примеру «Игра №1»,'
testString: 'assert.deepEqual(dealFreeCell(1), game1, "<code>dealFreeCell(1)</code> should return an array identical to example "Game #1"");'
- text: '<code>dealFreeCell(617)</code> должен возвращать массив, идентичный примеру «Game # 617»,'
testString: 'assert.deepEqual(dealFreeCell(617), game617, "<code>dealFreeCell(617)</code> should return an array identical to example "Game #617"");'
- text: <code>dealFreeCell</code> is a function.
testString: assert(typeof dealFreeCell === 'function');
- text: <code>dealFreeCell(seed)</code> should return an object.
testString: assert(typeof dealFreeCell(1) === 'object');
- text: <code>dealFreeCell(seed)</code> should return an array of length 7.
testString: assert(dealFreeCell(1).length === 7);
- text: '<code>dealFreeCell(1)</code> should return an array identical to example "Game #1"'
testString: assert.deepEqual(dealFreeCell(1), game1);
- text: '<code>dealFreeCell(617)</code> should return an array identical to example "Game #617"'
testString: assert.deepEqual(dealFreeCell(617), game617);
```
@@ -61,7 +65,7 @@ tests:
<div id='js-seed'>
```js
function dealFreeCell (seed) {
function dealFreeCell(seed) {
// Good luck!
return true;
}
@@ -70,12 +74,30 @@ function dealFreeCell (seed) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const replaceThis = 3;
const game1 = [
['JD', '2D', '9H', 'JC', '5D', '7H', '7C', '5H'],
['KD', 'KC', '9S', '5S', 'AD', 'QC', 'KH', '3H'],
['2S', 'KS', '9D', 'QD', 'JS', 'AS', 'AH', '3C'],
['4C', '5C', 'TS', 'QH', '4H', 'AC', '4D', '7S'],
['3S', 'TD', '4S', 'TH', '8H', '2C', 'JH', '7D'],
['6D', '8S', '8D', 'QS', '6C', '3D', '8C', 'TC'],
['6S', '9C', '2H', '6H']
];
const game617 = [
['7D', 'AD', '5C', '3S', '5S', '8C', '2D', 'AH'],
['TD', '7S', 'QD', 'AC', '6D', '8H', 'AS', 'KH'],
['TH', 'QC', '3H', '9D', '6S', '8D', '3D', 'TC'],
['KD', '5H', '9S', '3C', '8S', '7H', '4D', 'JS'],
['4C', 'QS', '9C', '9H', '7C', '6H', '2C', '2S'],
['4S', 'TS', '2H', '5D', 'JC', '6C', 'JH', 'QH'],
['JD', 'KS', 'KC', '4H']
];
```
</div>
@@ -86,6 +108,62 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// RNG
function FreeCellRNG(seed) {
return {
lastNum: seed,
next() {
this.lastNum = ((214013 * this.lastNum) + 2531011) % (Math.pow(2, 31));
return this.lastNum >> 16;
}
};
}
// Get cards
function getDeck() {
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
const suits = ['C', 'D', 'H', 'S'];
const cards = [];
for (let i = 0; i < ranks.length; i += 1) {
for (let j = 0; j < suits.length; j += 1) {
cards.push(`${ranks[i]}${suits[j]}`);
}
}
return cards;
}
function dealFreeCell(seed) {
const rng = FreeCellRNG(seed);
const deck = getDeck();
const deltCards = [[], [], [], [], [], [], []];
let currentColumn = 0;
let currentRow = 0;
let rand;
let temp;
let card;
while (deck.length > 0) {
// Choose a random card
rand = rng.next() % deck.length;
// Swap this random card with the last card in the array
temp = deck[deck.length - 1];
deck[deck.length - 1] = deck[rand];
deck[rand] = temp;
// Remove this card from the array
card = deck.pop();
// Deal this card
deltCards[currentRow].push(card);
currentColumn += 1;
if (currentColumn === 8) {
currentColumn = 0;
currentRow += 1;
}
}
return deltCards;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Deepcopy
id: 596a8888ab7c01048de257d5
challengeType: 5
videoUrl: ''
forumTopicId: 302247
localeTitle: DeepCopy
---
## Description
<section id="description"> Задача: <p> Напишите функцию, которая возвращает глубокую копию данного объекта. </p><p> Копия не должна быть тем же самым объектом, который был дан. </p><p> Эта задача не будет проверяться: </p> Объекты со свойствами, которые являются функциями. Объекты Date или объект со свойствами, которые являются объектами Date. RegEx или объект со свойствами, которые являются объектами RegEx. Прототипирование копий </section>
<section id='description'>
Задача: <p> Напишите функцию, которая возвращает глубокую копию данного объекта. </p><p> Копия не должна быть тем же самым объектом, который был дан. </p><p> Эта задача не будет проверяться: </p> Объекты со свойствами, которые являются функциями. Объекты Date или объект со свойствами, которые являются объектами Date. RegEx или объект со свойствами, которые являются объектами RegEx. Прототипирование копий
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: DeepCopy
```yml
tests:
- text: <code>deepcopy</code> должна быть функцией.
testString: 'assert(typeof deepcopy === "function", "<code>deepcopy</code> should be a function.");'
- text: '<code>deepcopy({test: &quot;test&quot;})</code> должен возвращать объект.'
testString: 'assert(typeof deepcopy(obj1) === "object", "<code>deepcopy({test: "test"})</code> should return an object.");'
- text: 'Не следует возвращать тот же объект, который был предоставлен.'
testString: 'assert(deepcopy(obj2) != obj2, "Should not return the same object that was provided.");'
- text: 'Когда передан объект, содержащий массив, должен возвращать глубокую копию объекта.'
testString: 'assert.deepEqual(deepcopy(obj2), obj2, "When passed an object containing an array, should return a deep copy of the object.");'
- text: 'При передаче объекта, содержащего другой объект, следует вернуть глубокую копию объекта.'
testString: 'assert.deepEqual(deepcopy(obj3), obj3, "When passed an object containing another object, should return a deep copy of the object.");'
- text: <code>deepcopy</code> should be a function.
testString: assert(typeof deepcopy === 'function');
- text: '<code>deepcopy({test: "test"})</code> should return an object.'
testString: assert(typeof deepcopy(obj1) === 'object');
- text: Should not return the same object that was provided.
testString: assert(deepcopy(obj2) != obj2);
- text: When passed an object containing an array, should return a deep copy of the object.
testString: assert.deepEqual(deepcopy(obj2), obj2);
- text: When passed an object containing another object, should return a deep copy of the object.
testString: assert.deepEqual(deepcopy(obj3), obj3);
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function deepcopy (obj) {
function deepcopy(obj) {
// Good luck!
return true;
}
@@ -48,12 +51,20 @@ function deepcopy (obj) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const obj1 = { test: 'test' };
const obj2 = {
t: 'test',
a: ['an', 'array']
};
const obj3 = {
t: 'try',
o: obj2
};
```
</div>
@@ -64,6 +75,9 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function deepcopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Define a primitive data type
id: 597089c87eec450c68aa1643
challengeType: 5
videoUrl: ''
forumTopicId: 302248
localeTitle: Определить примитивный тип данных
---
## Description
<section id="description"> Задача: <p> Определите тип, который ведет себя как целое число, но имеет наименьшее допустимое значение 1 и самое высокое допустимое значение 10. </p> Ошибки. Если вы попытаетесь создать экземпляр <code>Num</code> со значением за пределами 1 - 10, он должен выбросить <code>TypeError</code> с сообщением об ошибке <code>&#39;Out of range&#39;</code> . Если вы попытаетесь создать экземпляр <code>Num</code> со значением, которое не является числом, оно должно <code>TypeError</code> с сообщением об ошибке <code>&#39;Not a Number&#39;</code> . </section>
<section id='description'>
Задача: <p> Определите тип, который ведет себя как целое число, но имеет наименьшее допустимое значение 1 и самое высокое допустимое значение 10. </p> Ошибки. Если вы попытаетесь создать экземпляр <code>Num</code> со значением за пределами 1 - 10, он должен выбросить <code>TypeError</code> с сообщением об ошибке <code>&#39;Out of range&#39;</code> . Если вы попытаетесь создать экземпляр <code>Num</code> со значением, которое не является числом, оно должно <code>TypeError</code> с сообщением об ошибке <code>&#39;Not a Number&#39;</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,34 +21,34 @@ localeTitle: Определить примитивный тип данных
```yml
tests:
- text: <code>Num</code> должно быть функцией.
testString: 'assert(typeof Num === "function", "<code>Num</code> should be a function.");'
- text: <code>new Num(4)</code> должен возвращать объект.
testString: 'assert(typeof (new Num(4)) === "object", "<code>new Num(4)</code> should return an object.");'
- text: '<code>new Num(\&#39;test\&#39;)</code> должен вызывать TypeError с сообщением «Не номер».'
testString: 'assert(throws(() => new Num("test"), TypeError, "Not a Number"), "<code>new Num(\"test\")</code> should throw a TypeError with message \"Not a Number\".");'
- text: <code>new Num(0)</code> должен вызывать TypeError с сообщением «Вне диапазона».
testString: 'assert(throws(() => new Num(0), TypeError, "Out of range"), "<code>new Num(0)</code> should throw a TypeError with message \"Out of range\".");'
- text: <code>new Num(-5)</code> должен вызывать TypeError с сообщением «Вне диапазона».
testString: 'assert(throws(() => new Num(-5), TypeError, "Out of range"), "<code>new Num(-5)</code> should throw a TypeError with message \"Out of range\".");'
- text: <code>new Num(10)</code> должен вызывать TypeError с сообщением «Вне диапазона».
testString: 'assert(throws(() => new Num(11), TypeError, "Out of range"), "<code>new Num(10)</code> should throw a TypeError with message \"Out of range\".");'
- text: <code>new Num(20)</code> должен вызывать TypeError с сообщением «Вне диапазона».
testString: 'assert(throws(() => new Num(20), TypeError, "Out of range"), "<code>new Num(20)</code> should throw a TypeError with message \"Out of range\".");'
- text: <code>new Num(3) + new Num(4)</code> должен равняться 7.
testString: 'assert.equal(new Num(3) + new Num(4), 7, "<code>new Num(3) + new Num(4)</code> should equal 7.");'
- text: <code>new Num(3) - new Num(4)</code> должен равняться -1.
testString: 'assert.equal(new Num(3) - new Num(4), -1, "<code>new Num(3) - new Num(4)</code> should equal -1.");'
- text: <code>new Num(3) * new Num(4)</code> должен равняться 12.
testString: 'assert.equal(new Num(3) * new Num(4), 12, "<code>new Num(3) * new Num(4)</code> should equal 12.");'
- text: '<code>new Num(3) / new Num(4)</code> должен равняться 0,75.'
testString: 'assert.equal(new Num(3) / new Num(4), 0.75, "<code>new Num(3) / new Num(4)</code> should equal 0.75.");'
- text: <code>new Num(3) &lt; new Num(4)</code> должен быть правдой.
testString: 'assert(new Num(3) < new Num(4), "<code>new Num(3) < new Num(4)</code> should be true.");'
- text: <code>new Num(3) &gt; new Num(4)</code> должен быть ложным.
testString: 'assert(!(new Num(3) > new Num(4)), "<code>new Num(3) > new Num(4)</code> should be false.");'
- text: '<code>(new Num(5)).toString()</code> должен возвращать &#39;5 \&#39;'
testString: 'assert.equal((new Num(5)).toString(), "5", "<code>(new Num(5)).toString()</code> should return \"5\"");'
- text: <code>Num</code> should be a function.
testString: assert(typeof Num === 'function');
- text: <code>new Num(4)</code> should return an object.
testString: assert(typeof (new Num(4)) === 'object');
- text: <code>new Num('test')</code> should throw a TypeError with message 'Not a Number'.
testString: assert.throws(() => new Num('test'), TypeError);
- text: <code>new Num(0)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(0), TypeError);
- text: <code>new Num(-5)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(-5), TypeError);
- text: <code>new Num(10)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(11), TypeError);
- text: <code>new Num(20)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(20), TypeError);
- text: <code>new Num(3) + new Num(4)</code> should equal 7.
testString: assert.equal(new Num(3) + new Num(4), 7);
- text: <code>new Num(3) - new Num(4)</code> should equal -1.
testString: assert.equal(new Num(3) - new Num(4), -1);
- text: <code>new Num(3) * new Num(4)</code> should equal 12.
testString: assert.equal(new Num(3) * new Num(4), 12);
- text: <code>new Num(3) / new Num(4)</code> should equal 0.75.
testString: assert.equal(new Num(3) / new Num(4), 0.75);
- text: <code>new Num(3) < new Num(4)</code> should be true.
testString: assert(new Num(3) < new Num(4));
- text: <code>new Num(3) > new Num(4)</code> should be false.
testString: assert(!(new Num(3) > new Num(4)));
- text: <code>(new Num(5)).toString()</code> should return '5'
testString: assert.equal((new Num(5)).toString(), '5');
```
@@ -57,7 +60,7 @@ tests:
<div id='js-seed'>
```js
function Num (n) {
function Num(n) {
// Good luck!
return n;
}
@@ -66,14 +69,24 @@ function Num (n) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function Num(n) {
if (isNaN(n)) {
throw new TypeError('Not a Number');
}
if (n < 1 || n > 10) {
throw new TypeError('Out of range');
}
this._value = +n;
}
Num.prototype.valueOf = function() { return this._value; };
Num.prototype.toString = function () { return this._value.toString(); };
```
</section>

View File

@@ -2,15 +2,27 @@
title: Department Numbers
id: 59f40b17e79dbf1ab720ed7a
challengeType: 5
videoUrl: ''
forumTopicId: 302249
localeTitle: Номера отделений
---
## Description
<section id="description"><p> Существует высоко организованный город, который решил присвоить номер каждому из своих отделов: </p> Отдел полиции Отдел санитарии Отдел пожарной охраны <p> Каждый отдел может иметь число от 1 до 7 (включительно). </p><p> Три номера отделов должны быть уникальными (отличными друг от друга) и должны содержать до 12. </p><p> Начальник полиции не любит странные цифры и хочет иметь четное число для своего отдела. </p> Задача: <p> Напишите программу, которая выводит все допустимые комбинации: </p><p> [2, 3, 7] </p><p> [2, 4, 6] </p><p> [2, 6, 4] </p><p> [2, 7, 3] </p><p> [4, 1, 7] </p><p> [4, 2, 6] </p><p> [4, 3, 5] </p><p> [4, 5, 3] </p><p> [4, 6, 2] </p><p> [4, 7, 1] </p><p> [6, 1, 5] </p><p> [6, 2, 4] </p><p> [6, 4, 2] </p><p> [6, 5, 1] </p></section>
<section id='description'>
<p> Существует высоко организованный город, который решил присвоить номер каждому из своих отделов: </p> Отдел полиции Отдел санитарии Отдел пожарной охраны <p> Каждый отдел может иметь число от 1 до 7 (включительно). </p><p> Три номера отделов должны быть уникальными (отличными друг от друга) и должны содержать до 12. </p><p> Начальник полиции не любит странные цифры и хочет иметь четное число для своего отдела. </p> Задача: <p> Напишите программу, которая выводит все допустимые комбинации: </p><p> [2, 3, 7] </p><p> [2, 4, 6] </p><p> [2, 6, 4] </p><p> [2, 7, 3] </p><p> [4, 1, 7] </p><p> [4, 2, 6] </p><p> [4, 3, 5] </p><p> [4, 5, 3] </p><p> [4, 6, 2] </p><p> [4, 7, 1] </p><p> [6, 1, 5] </p><p> [6, 2, 4] </p><p> [6, 4, 2] </p><p> [6, 5, 1] </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a program which outputs all valid combinations as an array.
```js
[2, 3, 7] [2, 4, 6] [2, 6, 4]
[2, 7, 3] [4, 1, 7] [4, 2, 6]
[4, 3, 5] [4, 5, 3] [4, 6, 2]
[4, 7, 1] [6, 1, 5] [6, 2, 4]
[6, 4, 2] [6, 5, 1]
```
</section>
## Tests
@@ -18,14 +30,14 @@ localeTitle: Номера отделений
```yml
tests:
- text: <code>combinations</code> должны быть функцией.
testString: 'assert(typeof combinations === "function", "<code>combinations</code> should be a function.");'
- text: '<code>combinations([1, 2, 3], 6)</code> должны возвращать массив.'
testString: 'assert(Array.isArray(combinations([1, 2, 3], 6)), "<code>combinations([1, 2, 3], 6)</code> should return an Array.");'
- text: '<code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> должны возвращать массив длиной 14.'
testString: 'assert(combinations(nums, total).length === len, "<code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return an array of length 14.");'
- text: '<code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> должны возвращать все допустимые комбинации.'
testString: 'assert.deepEqual(combinations(nums, total), result, "<code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return all valid combinations.");'
- text: <code>combinations</code> should be a function.
testString: assert(typeof combinations === 'function');
- text: <code>combinations([1, 2, 3], 6)</code> should return an Array.
testString: assert(Array.isArray(combinations([1, 2, 3], 6)));
- text: <code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return an array of length 14.
testString: assert(combinations(nums, total).length === len);
- text: <code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return all valid combinations.
testString: assert.deepEqual(combinations(nums, total), result);
```
@@ -37,7 +49,7 @@ tests:
<div id='js-seed'>
```js
function combinations (possibleNumbers, total) {
function combinations(possibleNumbers, total) {
// Good luck!
return true;
}
@@ -46,12 +58,30 @@ function combinations (possibleNumbers, total) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const nums = [1, 2, 3, 4, 5, 6, 7];
const total = 12;
const len = 14;
const result = [
[2, 3, 7],
[2, 4, 6],
[2, 6, 4],
[2, 7, 3],
[4, 1, 7],
[4, 2, 6],
[4, 3, 5],
[4, 5, 3],
[4, 6, 2],
[4, 7, 1],
[6, 1, 5],
[6, 2, 4],
[6, 4, 2],
[6, 5, 1]
];
```
</div>
@@ -62,6 +92,31 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function combinations(possibleNumbers, total) {
let firstNumber;
let secondNumber;
let thridNumber;
const allCombinations = [];
for (let i = 0; i < possibleNumbers.length; i += 1) {
firstNumber = possibleNumbers[i];
if (firstNumber % 2 === 0) {
for (let j = 0; j < possibleNumbers.length; j += 1) {
secondNumber = possibleNumbers[j];
if (j !== i && firstNumber + secondNumber <= total) {
thridNumber = total - firstNumber - secondNumber;
if (thridNumber !== firstNumber && thridNumber !== secondNumber && possibleNumbers.includes(thridNumber)) {
allCombinations.push([firstNumber, secondNumber, thridNumber]);
}
}
}
}
}
return allCombinations;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Discordian date
id: 59f4eafba0343628bb682785
challengeType: 5
videoUrl: ''
forumTopicId: 302250
localeTitle: Дискордианская дата
---
## Description
<section id="description"> Задача: <p> Преобразуйте заданную дату из <a href="https://en.wikipedia.org/wiki/Gregorian calendar" title="wp: григорианский календарь">григорианского календаря</a> в <a href="https://en.wikipedia.org/wiki/Discordian calendar" title="wp: Дискордианский календарь">Дискордианский календарь</a> . </p></section>
<section id='description'>
Задача: <p> Преобразуйте заданную дату из <a href="https://en.wikipedia.org/wiki/Gregorian calendar" title="wp: григорианский календарь">григорианского календаря</a> в <a href="https://en.wikipedia.org/wiki/Discordian calendar" title="wp: Дискордианский календарь">Дискордианский календарь</a> . </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: Дискордианская дата
```yml
tests:
- text: <code>discordianDate</code> - это функция.
testString: 'assert(typeof discordianDate === "function", "<code>discordianDate</code> is a function.");'
- text: '<code>discordianDate(new Date(2010, 6, 22))</code> должен вернуть <code>&quot;Pungenday, the 57th day of Confusion in the YOLD 3176&quot;</code> .'
testString: 'assert(discordianDate(new Date(2010, 6, 22)) === "Pungenday, the 57th day of Confusion in the YOLD 3176", "<code>discordianDate(new Date(2010, 6, 22))</code> should return <code>"Pungenday, the 57th day of Confusion in the YOLD 3176"</code>.");'
- text: '<code>discordianDate(new Date(2012, 1, 28))</code> должен вернуть <code>&quot;Prickle-Prickle, the 59th day of Chaos in the YOLD 3178&quot;</code> .'
testString: 'assert(discordianDate(new Date(2012, 1, 28)) === "Prickle-Prickle, the 59th day of Chaos in the YOLD 3178", "<code>discordianDate(new Date(2012, 1, 28))</code> should return <code>"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"</code>.");'
- text: '<code>discordianDate(new Date(2012, 1, 29))</code> должен вернуть <code>&quot;Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\&quot;s Day!&quot;</code> .'
testString: 'assert(discordianDate(new Date(2012, 1, 29)) === "Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\"s Day!", "<code>discordianDate(new Date(2012, 1, 29))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\"s Day!"</code>.");'
- text: '<code>discordianDate(new Date(2012, 2, 1))</code> должен вернуть <code>&quot;Setting Orange, the 60th day of Chaos in the YOLD 3178&quot;</code> .'
testString: 'assert(discordianDate(new Date(2012, 2, 1)) === "Setting Orange, the 60th day of Chaos in the YOLD 3178", "<code>discordianDate(new Date(2012, 2, 1))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178"</code>.");'
- text: '<code>discordianDate(new Date(2010, 0, 5))</code> должен вернуть <code>&quot;Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!&quot;</code> ,'
testString: 'assert(discordianDate(new Date(2010, 0, 5)) === "Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!", "<code>discordianDate(new Date(2010, 0, 5))</code> should return <code>"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"</code>.");'
- text: '<code>discordianDate(new Date(2011, 4, 3))</code> должен вернуть <code>&quot;Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!&quot;</code> ,'
testString: 'assert(discordianDate(new Date(2011, 4, 3)) === "Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!", "<code>discordianDate(new Date(2011, 4, 3))</code> should return <code>"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"</code>.");'
- text: '<code>discordianDate(new Date(2015, 9, 19))</code> должен вернуть <code>&quot;Boomtime, the 73rd day of Bureaucracy in the YOLD 3181&quot;</code> .'
testString: 'assert(discordianDate(new Date(2015, 9, 19)) === "Boomtime, the 73rd day of Bureaucracy in the YOLD 3181", "<code>discordianDate(new Date(2015, 9, 19))</code> should return <code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code>.");'
- text: <code>discordianDate</code> is a function.
testString: assert(typeof discordianDate === 'function');
- text: <code>discordianDate(new Date(2010, 6, 22))</code> should return <code>"Pungenday, the 57th day of Confusion in the YOLD 3176"</code>.
testString: assert(discordianDate(new Date(2010, 6, 22)) === 'Pungenday, the 57th day of Confusion in the YOLD 3176');
- text: <code>discordianDate(new Date(2012, 1, 28))</code> should return <code>"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"</code>.
testString: assert(discordianDate(new Date(2012, 1, 28)) === 'Prickle-Prickle, the 59th day of Chaos in the YOLD 3178');
- text: <code>discordianDate(new Date(2012, 1, 29))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!"</code>.
testString: assert(discordianDate(new Date(2012, 1, 29)) === 'Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!');
- text: <code>discordianDate(new Date(2012, 2, 1))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178"</code>.
testString: assert(discordianDate(new Date(2012, 2, 1)) === 'Setting Orange, the 60th day of Chaos in the YOLD 3178');
- text: <code>discordianDate(new Date(2010, 0, 5))</code> should return <code>"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"</code>.
testString: assert(discordianDate(new Date(2010, 0, 5)) === 'Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!');
- text: <code>discordianDate(new Date(2011, 4, 3))</code> should return <code>"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"</code>.
testString: assert(discordianDate(new Date(2011, 4, 3)) === 'Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!');
- text: <code>discordianDate(new Date(2015, 9, 19))</code> should return <code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code>.
testString: assert(discordianDate(new Date(2015, 9, 19)) === 'Boomtime, the 73rd day of Bureaucracy in the YOLD 3181');
```
@@ -45,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function discordianDate (date) {
function discordianDate(date) {
// Good luck!
return true;
}
@@ -54,14 +57,109 @@ function discordianDate (date) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
/**
* All Hail Discordia! - this script prints Discordian date using system date.
*
* lang: JavaScript
* author: jklu
* contributors: JamesMcGuigan
*
* source: https://rosettacode.org/wiki/Discordian_date#JavaScript
*/
const seasons = [
'Chaos', 'Discord', 'Confusion',
'Bureaucracy', 'The Aftermath'
];
const weekday = [
'Sweetmorn', 'Boomtime', 'Pungenday',
'Prickle-Prickle', 'Setting Orange'
];
const apostle = [
'Mungday', 'Mojoday', 'Syaday',
'Zaraday', 'Maladay'
];
const holiday = [
'Chaoflux', 'Discoflux', 'Confuflux',
'Bureflux', 'Afflux'
];
Date.prototype.isLeapYear = function() {
const year = this.getFullYear();
if ((year & 3) !== 0) { return false; }
return ((year % 100) !== 0 || (year % 400) === 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
const dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
const mn = this.getMonth();
const dn = this.getDate();
let dayOfYear = dayCount[mn] + dn;
if (mn > 1 && this.isLeapYear()) { dayOfYear += 1; }
return dayOfYear;
};
Date.prototype.isToday = function() {
const today = new Date();
return this.getDate() === today.getDate()
&& this.getMonth() === today.getMonth()
&& this.getFullYear() === today.getFullYear()
;
};
function discordianDate(date) {
if (!date) { date = new Date(); }
const y = date.getFullYear();
const yold = y + 1166;
let dayOfYear = date.getDOY();
let celebrateHoliday = null;
if (date.isLeapYear()) {
if (dayOfYear === 60) {
celebrateHoliday = 'St. Tib\'s Day';
}
else if (dayOfYear > 60) {
dayOfYear--;
}
}
dayOfYear--;
const divDay = Math.floor(dayOfYear / 73);
const seasonDay = (dayOfYear % 73) + 1;
if (seasonDay === 5) {
celebrateHoliday = apostle[divDay];
}
if (seasonDay === 50) {
celebrateHoliday = holiday[divDay];
}
const season = seasons[divDay];
const dayOfWeek = weekday[dayOfYear % 5];
const nth = (seasonDay % 10 === 1) ? 'st'
: (seasonDay % 10 === 2) ? 'nd'
: (seasonDay % 10 === 3) ? 'rd'
: 'th';
return ''
+ dayOfWeek
+ ', the ' + seasonDay + nth
+ ' day of ' + season
+ ' in the YOLD ' + yold
+ (celebrateHoliday ? '. Celebrate ' + celebrateHoliday + '!' : '')
;
}
```
</section>

View File

@@ -2,37 +2,41 @@
title: Element-wise operations
id: 599c333915e0ea32d04d4bec
challengeType: 5
videoUrl: ''
forumTopicId: 302252
localeTitle: Элементные операции
---
## Description
<section id="description"><p> Реализуйте основные матричные матричные и скалярно-матричные операции. </p><p> Воплощать в жизнь: </p><p> :: * дополнение </p><p> :: * вычитание </p><p> :: * умножение </p><p> :: * раздел </p><p> :: * возведение в степень </p><p> Первым параметром будет операция, которая должна быть выполнена, например: «m_add» для добавления матрицы и «s_add» для скалярного добавления. Второй и третий параметры будут представлять собой матрицы, на которых должны выполняться операции. </p></section>
<section id='description'>
<p> Реализуйте основные матричные матричные и скалярно-матричные операции. </p><p> Воплощать в жизнь: </p><p> :: * дополнение </p><p> :: * вычитание </p><p> :: * умножение </p><p> :: * раздел </p><p> :: * возведение в степень </p><p> Первым параметром будет операция, которая должна быть выполнена, например: «m_add» для добавления матрицы и «s_add» для скалярного добавления. Второй и третий параметры будут представлять собой матрицы, на которых должны выполняться операции. </p>
</section>
## Instructions
undefined
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>operation</code> - это функция.
testString: 'assert(typeof operation === "function", "<code>operation</code> is a function.");'
- text: '<code>operation(&quot;m_add&quot;,[[1,2],[3,4]],[[1,2],[3,4]])</code> должны вернуться <code>[[2,4],[6,8]]</code> .'
testString: 'assert.deepEqual(operation("m_add", [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[2, 4], [6, 8]], "<code>operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[2,4],[6,8]]</code>.");'
- text: '<code>operation(&quot;s_add&quot;,[[1,2],[3,4]],[[1,2],[3,4]])</code> должны возвращать <code>[[3,4],[5,6]]</code> .'
testString: 'assert.deepEqual(operation("s_add", [[1, 2], [3, 4]], 2), [[3, 4], [5, 6]], "<code>operation("s_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[3,4],[5,6]]</code>.");'
- text: '<code>operation(&quot;m_sub&quot;,[[1,2],[3,4]],[[1,2],[3,4]])</code> должны возвращать <code>[[0,0],[0,0]]</code> .'
testString: 'assert.deepEqual(operation("m_sub", [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[0, 0], [0, 0]], "<code>operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[0,0],[0,0]]</code>.");'
- text: '<code>operation(&quot;m_mult&quot;,[[1,2],[3,4]],[[1,2],[3,4]])</code> должны возвращать <code>[[1,4],[9,16]]</code> .'
testString: 'assert.deepEqual(operation("m_mult", [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 4], [9, 16]], "<code>operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[9,16]]</code>.");'
- text: '<code>operation(&quot;m_div&quot;,[[1,2],[3,4]],[[1,2],[3,4]])</code> должны возвращать <code>[[1,1],[1,1]]</code> .'
testString: 'assert.deepEqual(operation("m_div", [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 1], [1, 1]], "<code>operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,1],[1,1]]</code>.");'
- text: '<code>operation(&quot;m_exp&quot;,[[1,2],[3,4]],[[1,2],[3,4]])</code> должны вернуться <code>[[1,4],[27,256]]</code> .'
testString: 'assert.deepEqual(operation("m_exp", [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 4], [27, 256]], "<code>operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[27,256]]</code>.");'
- text: '<code>operation(&quot;m_add&quot;,[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])</code> должен возвращать <code>[[10,12,14,16],[18,20,22,24]]</code> .'
testString: 'assert.deepEqual(operation("m_add", [[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]), [[10, 12, 14, 16], [18, 20, 22, 24]], "<code>operation("m_add",[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])</code> should return <code>[[10,12,14,16],[18,20,22,24]]</code>.");'
- text: <code>operation</code> is a function.
testString: assert(typeof operation === 'function');
- text: <code>operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[2,4],[6,8]]</code>.
testString: assert.deepEqual(operation('m_add', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[2, 4], [6, 8]]);
- text: <code>operation("s_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[3,4],[5,6]]</code>.
testString: assert.deepEqual(operation('s_add', [[1, 2], [3, 4]], 2), [[3, 4], [5, 6]]);
- text: <code>operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[0,0],[0,0]]</code>.
testString: assert.deepEqual(operation('m_sub', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[0, 0], [0, 0]]);
- text: <code>operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[9,16]]</code>.
testString: assert.deepEqual(operation('m_mult', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 4], [9, 16]]);
- text: <code>operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,1],[1,1]]</code>.
testString: assert.deepEqual(operation('m_div', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 1], [1, 1]]);
- text: <code>operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[27,256]]</code>.
testString: assert.deepEqual(operation('m_exp', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 4], [27, 256]]);
- text: <code>operation("m_add",[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])</code> should return <code>[[10,12,14,16],[18,20,22,24]]</code>.
testString: assert.deepEqual(operation('m_add', [[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]), [[10, 12, 14, 16], [18, 20, 22, 24]]);
```
@@ -44,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function operation (op, arr1, arr2) {
function operation(op, arr1, arr2) {
// Good luck!
}
@@ -52,14 +56,29 @@ function operation (op, arr1, arr2) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function operation(op, arr1, arr2) {
const ops = {
add: ((a, b) => a + b),
sub: ((a, b) => a - b),
mult: ((a, b) => a * b),
div: ((a, b) => a / b),
exp: ((a, b) => Math.pow(a, b))
};
const ifm = op.startsWith('m');
const doOp = ops[op.substring(2)];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr1[0].length; j++) {
arr1[i][j] = doOp(arr1[i][j], (ifm) ? (arr2[i][j]) : (arr2));
}
}
return arr1;
}
```
</section>

View File

@@ -2,15 +2,25 @@
title: Emirp primes
id: 599d0ba974141b0f508b37d5
challengeType: 5
videoUrl: ''
forumTopicId: 302253
localeTitle: Бонусы Эмирпа
---
## Description
<section id="description"><p> Эмирп (первичный, записанный в обратном порядке) - это простые числа, которые при обратном (в их десятичном представлении) являются разными штрихами. </p><p> Напишите функцию, которая должна быть способна: Показывать первые числа <b>n</b> номеров. Покажите числа eprimes в диапазоне. Покажите количество eprimes в диапазоне. Покажите номер <b>n <sup>th</sup></b> eprimes. </p><p> Функция должна иметь два параметра. Первый получит <b>n</b> или диапазон в виде массива. Вторая будет получать логическое значение, которое указывает, возвращает ли функция eprimes в виде массива или одного числа (количество простых чисел в диапазоне или <b>n- <sup>го</sup></b> числа). В соответствии с параметрами функция должна возвращать массив или число. </p></section>
<section id='description'>
<p> Эмирп (первичный, записанный в обратном порядке) - это простые числа, которые при обратном (в их десятичном представлении) являются разными штрихами. </p><p> Напишите функцию, которая должна быть способна: Показывать первые числа <b>n</b> номеров. Покажите числа eprimes в диапазоне. Покажите количество eprimes в диапазоне. Покажите номер <b>n <sup>th</sup></b> eprimes. </p><p> Функция должна иметь два параметра. Первый получит <b>n</b> или диапазон в виде массива. Вторая будет получать логическое значение, которое указывает, возвращает ли функция eprimes в виде массива или одного числа (количество простых чисел в диапазоне или <b>n- <sup>го</sup></b> числа). В соответствии с параметрами функция должна возвращать массив или число. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that:
<ul>
<li>Shows the first <code>n</code> emirp numbers.</li>
<li>Shows the emirp numbers in a range.</li>
<li>Shows the number of emirps in a range.</li>
<li>Shows the <code>n<sup>th</sup></code> emirp number.</li>
</ul>
The function should accept two parameters. The first will receive <code>n</code> or the range as an array. The second will receive a boolean, that specifies if the function returns the emirps as an array or a single number (the number of primes in the range or the <code>n<sup>th</sup></code> prime). According to the parameters the function should return an array or a number.
</section>
## Tests
@@ -18,16 +28,16 @@ localeTitle: Бонусы Эмирпа
```yml
tests:
- text: <code>emirps</code> - это функция.
testString: 'assert(typeof emirps === "function", "<code>emirps</code> is a function.");'
- text: '<code>emirps(20,true)</code> должны вернуться <code>[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]</code>'
testString: 'assert.deepEqual(emirps(20, true), [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389], "<code>emirps(20,true)</code> should return <code>[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]</code>");'
- text: <code>emirps(10000)</code> должен вернуть <code>948349</code>
testString: 'assert.deepEqual(emirps(10000), 948349, "<code>emirps(10000)</code> should return <code>948349</code>");'
- text: '<code>emirps([7700,8000],true)</code> должны быть возвращены <code>[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]</code>'
testString: 'assert.deepEqual(emirps([7700, 8000], true), [7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963], "<code>emirps([7700,8000],true)</code> should return <code>[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]</code>");'
- text: '<code>emirps([7700,8000],true)</code> должен вернуть <code>11</code>'
testString: 'assert.deepEqual(emirps([7700, 8000], false), 11, "<code>emirps([7700,8000],true)</code> should return <code>11</code>");'
- text: <code>emirps</code> is a function.
testString: assert(typeof emirps === 'function');
- text: <code>emirps(20,true)</code> should return <code>[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]</code>
testString: assert.deepEqual(emirps(20, true), [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389]);
- text: <code>emirps(10000)</code> should return <code>948349</code>
testString: assert.deepEqual(emirps(10000), 948349);
- text: <code>emirps([7700,8000],true)</code> should return <code>[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]</code>
testString: assert.deepEqual(emirps([7700, 8000], true), [7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963]);
- text: <code>emirps([7700,8000],true)</code> should return <code>11</code>
testString: assert.deepEqual(emirps([7700, 8000], false), 11);
```
@@ -47,14 +57,47 @@ function emirps(n) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
// noprotect
function emirps(num, showEmirps)
{
const is_prime = function(n)
{
if (!(n % 2) || !(n % 3)) return false;
let p = 1;
while (p * p < n)
{ if (n % (p += 4) == 0 || n % (p += 2) == 0)
{ return false; } }
return true;
};
const is_emirp = function(n) {
const r = parseInt(n.toString().split('').reverse().join(''));
return r != n && is_prime(n) && is_prime(r);
};
let i,
arr = [];
if (typeof num === 'number') {
for (i = 0; arr.length < num; i++) if (is_emirp(i)) arr.push(i);
// first x emirps
if (showEmirps) return arr;
// xth emirp
return arr.pop();
}
if (Array.isArray(num)) {
for (i = num[0]; i <= num[1]; i++) if (is_emirp(i)) arr.push(i);
// emirps between x .. y
if (showEmirps) return arr;
// number of emirps between x .. y
return arr.length;
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Entropy
id: 599d15309e88c813a40baf58
challengeType: 5
videoUrl: ''
forumTopicId: 302254
localeTitle: Энтропия
---
## Description
<section id="description"> Задача: <p> Вычислите энтропию Шеннона H данной входной строки. </p><p> Учитывая выборочную случайную переменную $ X $, которая представляет собой строку из $ N $ &quot;символов&quot; (всего символов), состоящую из $ n $ различных символов (n = 2 для двоичных), энтропия Шеннона X в битах / символе: </p><p> $ H_2 (X) = - \ sum_ {i = 1} ^ n \ frac {count_i} {N} \ log_2 \ left (\ frac {count_i} {N} \ right) $ </p><p> где $ count_i $ - количество символов $ n_i $. </p></section>
<section id='description'>
Задача: <p> Вычислите энтропию Шеннона H данной входной строки. </p><p> Учитывая выборочную случайную переменную $ X $, которая представляет собой строку из $ N $ &quot;символов&quot; (всего символов), состоящую из $ n $ различных символов (n = 2 для двоичных), энтропия Шеннона X в битах / символе: </p><p> $ H_2 (X) = - \ sum_ {i = 1} ^ n \ frac {count_i} {N} \ log_2 \ left (\ frac {count_i} {N} \ right) $ </p><p> где $ count_i $ - количество символов $ n_i $. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Энтропия
```yml
tests:
- text: <code>entropy</code> - функция.
testString: 'assert(typeof entropy === "function", "<code>entropy</code> is a function.");'
- text: <code>entropy(&quot;0&quot;)</code> должна возвращать <code>0</code>
testString: 'assert.equal(entropy("0"), 0, "<code>entropy("0")</code> should return <code>0</code>");'
- text: <code>entropy(&quot;01&quot;)</code> должна вернуть <code>1</code>
testString: 'assert.equal(entropy("01"), 1, "<code>entropy("01")</code> should return <code>1</code>");'
- text: ''
testString: 'assert.equal(entropy("0123"), 2, "<code>entropy("0123")</code> should return <code>2</code>");'
- text: <code>entropy(&quot;01234567&quot;)</code> должна вернуть <code>3</code>
testString: 'assert.equal(entropy("01234567"), 3, "<code>entropy("01234567")</code> should return <code>3</code>");'
- text: <code>entropy(&quot;0123456789abcdef&quot;)</code> должна возвращать <code>4</code>
testString: 'assert.equal(entropy("0123456789abcdef"), 4, "<code>entropy("0123456789abcdef")</code> should return <code>4</code>");'
- text: <code>entropy(&quot;1223334444&quot;)</code> должна быть возвращена <code>1.8464393446710154</code>
testString: 'assert.equal(entropy("1223334444"), 1.8464393446710154, "<code>entropy("1223334444")</code> should return <code>1.8464393446710154</code>");'
- text: <code>entropy</code> is a function.
testString: assert(typeof entropy === 'function');
- text: <code>entropy("0")</code> should return <code>0</code>
testString: assert.equal(entropy('0'), 0);
- text: <code>entropy("01")</code> should return <code>1</code>
testString: assert.equal(entropy('01'), 1);
- text: <code>entropy("0123")</code> should return <code>2</code>
testString: assert.equal(entropy('0123'), 2);
- text: <code>entropy("01234567")</code> should return <code>3</code>
testString: assert.equal(entropy('01234567'), 3);
- text: <code>entropy("0123456789abcdef")</code> should return <code>4</code>
testString: assert.equal(entropy('0123456789abcdef'), 4);
- text: <code>entropy("1223334444")</code> should return <code>1.8464393446710154</code>
testString: assert.equal(entropy('1223334444'), 1.8464393446710154);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function entropy (s) {
function entropy(s) {
// Good luck!
}
@@ -51,14 +54,32 @@ function entropy (s) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function entropy(s) {
// Create a dictionary of character frequencies and iterate over it.
function process(s, evaluator) {
let h = Object.create(null),
k;
s.split('').forEach(c => {
h[c] && h[c]++ || (h[c] = 1); });
if (evaluator) for (k in h) evaluator(k, h[k]);
return h;
}
// Measure the entropy of a string in bits per symbol.
let sum = 0,
len = s.length;
process(s, (k, f) => {
const p = f / len;
sum -= p * Math.log(p) / Math.log(2);
});
return sum;
}
```
</section>

View File

@@ -2,15 +2,19 @@
title: Equilibrium index
id: 5987fd532b954e0f21b5d3f6
challengeType: 5
videoUrl: ''
forumTopicId: 302255
localeTitle: Равновесный индекс
---
## Description
<section id="description"><p> Равновесный индекс последовательности является индексом в такой последовательности, что сумма элементов при более низких индексах равна сумме элементов с более высокими индексами. </p><p> Например, в последовательности <big>$ A $</big> : </p><p> :::: <big>$ A_0 = -7 $</big> </p><p> :::: <big>$ A_1 = 1 $</big> </p><p> :::: <big>$ A_2 = 5 $</big> </p><p> :::: <big>$ A_3 = 2 $</big> </p><p> :::: <big>$ A_4 = -4 $</big> </p><p> :::: <big>$ A_5 = 3 $</big> </p><p> :::: <big>$ A_6 = 0 $</big> </p><p> 3 - показатель равновесия, поскольку: </p><p> :::: <big>$ A_0 + A_1 + A_2 = A_4 + A_5 + A_6 $</big> </p><p> 6 также является показателем равновесия, поскольку: </p><p> :::: <big>$ A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 $</big> </p><p> (сумма нулевых элементов равна нулю) </p><p> 7 не является индексом равновесия, поскольку он не является допустимым индексом последовательности <big>$ A $</big> . </p><p> Напишите функцию, которая, учитывая последовательность, возвращает свои равновесные индексы (если они есть). </p><p> Предположим, что последовательность может быть очень длинной. </p></section>
<section id='description'>
<p> Равновесный индекс последовательности является индексом в такой последовательности, что сумма элементов при более низких индексах равна сумме элементов с более высокими индексами. </p><p> Например, в последовательности <big>$ A $</big> : </p><p> :::: <big>$ A_0 = -7 $</big> </p><p> :::: <big>$ A_1 = 1 $</big> </p><p> :::: <big>$ A_2 = 5 $</big> </p><p> :::: <big>$ A_3 = 2 $</big> </p><p> :::: <big>$ A_4 = -4 $</big> </p><p> :::: <big>$ A_5 = 3 $</big> </p><p> :::: <big>$ A_6 = 0 $</big> </p><p> 3 - показатель равновесия, поскольку: </p><p> :::: <big>$ A_0 + A_1 + A_2 = A_4 + A_5 + A_6 $</big> </p><p> 6 также является показателем равновесия, поскольку: </p><p> :::: <big>$ A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 $</big> </p><p> (сумма нулевых элементов равна нулю) </p><p> 7 не является индексом равновесия, поскольку он не является допустимым индексом последовательности <big>$ A $</big> . </p><p> Напишите функцию, которая, учитывая последовательность, возвращает свои равновесные индексы (если они есть). </p><p> Предположим, что последовательность может быть очень длинной. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
</section>
## Tests
@@ -18,20 +22,20 @@ localeTitle: Равновесный индекс
```yml
tests:
- text: <code>equilibrium</code> является функцией.
testString: 'assert(typeof equilibrium === "function", "<code>equilibrium</code> is a function.");'
- text: '<code>equilibrium([-7, 1, 5, 2, -4, 3, 0])</code> должно вернуться <code>[3,6]</code> .'
testString: 'assert.deepEqual(equilibrium(tests[0]), ans[0], "<code>equilibrium([-7, 1, 5, 2, -4, 3, 0])</code> should return <code>[3,6]</code>.");'
- text: '<code>equilibrium([2, 4, 6])</code> должно возвращаться <code>[]</code> .'
testString: 'assert.deepEqual(equilibrium(tests[1]), ans[1], "<code>equilibrium([2, 4, 6])</code> should return <code>[]</code>.");'
- text: '<code>equilibrium([2, 9, 2])</code> должно возвращаться <code>[1]</code> .'
testString: 'assert.deepEqual(equilibrium(tests[2]), ans[2], "<code>equilibrium([2, 9, 2])</code> should return <code>[1]</code>.");'
- text: '<code>equilibrium([1, -1, 1, -1, 1, -1, 1])</code> должно возвращать <code>[0,1,2,3,4,5,6]</code> .'
testString: 'assert.deepEqual(equilibrium(tests[3]), ans[3], "<code>equilibrium([1, -1, 1, -1, 1, -1, 1])</code> should return <code>[0,1,2,3,4,5,6]</code>.");'
- text: '<code>equilibrium([1])</code> должно возвращаться <code>[0]</code> .'
testString: 'assert.deepEqual(equilibrium(tests[4]), ans[4], "<code>equilibrium([1])</code> should return <code>[0]</code>.");'
- text: '<code>equilibrium([])</code> должно возвращаться <code>[]</code> .'
testString: 'assert.deepEqual(equilibrium(tests[5]), ans[5], "<code>equilibrium([])</code> should return <code>[]</code>.");'
- text: <code>equilibrium</code> is a function.
testString: assert(typeof equilibrium === 'function');
- text: <code>equilibrium([-7, 1, 5, 2, -4, 3, 0])</code> should return <code>[3,6]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[0]), ans[0]);
- text: <code>equilibrium([2, 4, 6])</code> should return <code>[]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[1]), ans[1]);
- text: <code>equilibrium([2, 9, 2])</code> should return <code>[1]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[2]), ans[2]);
- text: <code>equilibrium([1, -1, 1, -1, 1, -1, 1])</code> should return <code>[0,1,2,3,4,5,6]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[3]), ans[3]);
- text: <code>equilibrium([1])</code> should return <code>[0]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[4]), ans[4]);
- text: <code>equilibrium([])</code> should return <code>[]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[5]), ans[5]);
```
@@ -43,7 +47,7 @@ tests:
<div id='js-seed'>
```js
function equilibrium (a) {
function equilibrium(a) {
// Good luck!
}
@@ -51,12 +55,20 @@ function equilibrium (a) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const equilibriumTests =
[[-7, 1, 5, 2, -4, 3, 0], // 3, 6
[2, 4, 6], // empty
[2, 9, 2], // 1
[1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6
[1], // 0
[] // empty
];
const ans = [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []];
```
</div>
@@ -67,6 +79,18 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function equilibrium(a) {
let N = a.length,
i,
l = [],
r = [],
e = [];
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i < N; i++)
{ l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1]; }
for (i = 0; i < N; i++)
{ if (l[i] === r[i]) e.push(i); }
return e;
}
```
</section>

View File

@@ -2,15 +2,24 @@
title: Ethiopian multiplication
id: 599d1566a02b571412643b84
challengeType: 5
videoUrl: ''
forumTopicId: 302257
localeTitle: Эфиопское умножение
---
## Description
<section id="description"><p> Эфиопское умножение - это метод умножения целых чисел, использующий только добавление, удвоение и уменьшение пополам. </p><p> Метод: </p> Возьмите два числа, чтобы их умножить и записать их в верхней части двух столбцов. В левом столбце повторите половину последнего номера, отбрасывая любые остатки и записывая результат ниже последнего в том же столбце, пока не напишите значение 1. В правом столбце многократно удвоите последнее число и запишите результат ниже. остановитесь, когда вы добавите результат в ту же строку, что и в столбце слева. 1. Изучите созданную таблицу и отбросьте любую строку, где значение в левом столбце четное. Суммируйте значения в правой колонке, которые останутся для получения результата умножения исходных двух чисел вместе <p> Например: 17 × 34 </p><p> 17 34 </p><p> Половина первого столбца: </p><p> 17 34 </p><p> 8 </p><p> 4 </p><p> 2 </p><p> 1 </p><p> Удвоение второй колонки: </p><p> 17 34 </p><p> 8 68 </p><p> 4 136 </p><p> 2 272 </p><p> 1 544 </p><p> Stratch-out rows, чья первая ячейка четная: </p><p> 17 34 </p><p> 8 <strike>68</strike> </p><p> 4 <strike>136</strike> </p><p> 2 <strike>272</strike> </p><p> 1 544 </p><p> Суммируйте оставшиеся числа в правом столбце: </p><p> 17 34 </p><p> 8 - </p><p> 4 --- </p><p> 2 --- </p><p> 1 544 </p><p> ==== </p><p> 578 </p><p> Так 17, умноженное на 34, по эфиопскому методу - 578. </p> Задача: <p> Задача состоит в том, чтобы определить три названные функции / методы / процедуры / подпрограммы: </p> один на половину целого числа, один для двойного целого числа, и один, чтобы указать, является ли целое четным. <p> Используйте эти функции для создания функции, которая делает эфиопское умножение. </p></section>
<section id='description'>
<p> Эфиопское умножение - это метод умножения целых чисел, использующий только добавление, удвоение и уменьшение пополам. </p><p> Метод: </p> Возьмите два числа, чтобы их умножить и записать их в верхней части двух столбцов. В левом столбце повторите половину последнего номера, отбрасывая любые остатки и записывая результат ниже последнего в том же столбце, пока не напишите значение 1. В правом столбце многократно удвоите последнее число и запишите результат ниже. остановитесь, когда вы добавите результат в ту же строку, что и в столбце слева. 1. Изучите созданную таблицу и отбросьте любую строку, где значение в левом столбце четное. Суммируйте значения в правой колонке, которые останутся для получения результата умножения исходных двух чисел вместе <p> Например: 17 × 34 </p><p> 17 34 </p><p> Половина первого столбца: </p><p> 17 34 </p><p> 8 </p><p> 4 </p><p> 2 </p><p> 1 </p><p> Удвоение второй колонки: </p><p> 17 34 </p><p> 8 68 </p><p> 4 136 </p><p> 2 272 </p><p> 1 544 </p><p> Stratch-out rows, чья первая ячейка четная: </p><p> 17 34 </p><p> 8 <strike>68</strike> </p><p> 4 <strike>136</strike> </p><p> 2 <strike>272</strike> </p><p> 1 544 </p><p> Суммируйте оставшиеся числа в правом столбце: </p><p> 17 34 </p><p> 8 - </p><p> 4 --- </p><p> 2 --- </p><p> 1 544 </p><p> ==== </p><p> 578 </p><p> Так 17, умноженное на 34, по эфиопскому методу - 578. </p> Задача: <p> Задача состоит в том, чтобы определить три названные функции / методы / процедуры / подпрограммы: </p> один на половину целого числа, один для двойного целого числа, и один, чтобы указать, является ли целое четным. <p> Используйте эти функции для создания функции, которая делает эфиопское умножение. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
The task is to define three named functions/methods/procedures/subroutines:
<ol>
<li>one to halve an integer,</li>
<li>one to double an integer, and</li>
<li>one to state if an integer is even</li>
</ol>
Use these functions to create a function that does Ethiopian multiplication.
</section>
## Tests
@@ -18,18 +27,18 @@ localeTitle: Эфиопское умножение
```yml
tests:
- text: <code>eth_mult</code> - это функция.
testString: 'assert(typeof eth_mult === "function", "<code>eth_mult</code> is a function.");'
- text: '<code>eth_mult(17,34)</code> должен вернуть <code>578</code> .'
testString: 'assert.equal(eth_mult(17, 34), 578, "<code>eth_mult(17,34)</code> should return <code>578</code>.");'
- text: '<code>eth_mult(23,46)</code> должен вернуть <code>1058</code> .'
testString: 'assert.equal(eth_mult(23, 46), 1058, "<code>eth_mult(23,46)</code> should return <code>1058</code>.");'
- text: '<code>eth_mult(12,27)</code> должен вернуть <code>324</code> .'
testString: 'assert.equal(eth_mult(12, 27), 324, "<code>eth_mult(12,27)</code> should return <code>324</code>.");'
- text: '<code>eth_mult(56,98)</code> должен вернуть <code>5488</code> .'
testString: 'assert.equal(eth_mult(56, 98), 5488, "<code>eth_mult(56,98)</code> should return <code>5488</code>.");'
- text: '<code>eth_mult(63,74)</code> должен вернуть <code>4662</code> .'
testString: 'assert.equal(eth_mult(63, 74), 4662, "<code>eth_mult(63,74)</code> should return <code>4662</code>.");'
- text: <code>eth_mult</code> is a function.
testString: assert(typeof eth_mult === 'function');
- text: <code>eth_mult(17,34)</code> should return <code>578</code>.
testString: assert.equal(eth_mult(17, 34), 578);
- text: <code>eth_mult(23,46)</code> should return <code>1058</code>.
testString: assert.equal(eth_mult(23, 46), 1058);
- text: <code>eth_mult(12,27)</code> should return <code>324</code>.
testString: assert.equal(eth_mult(12, 27), 324);
- text: <code>eth_mult(56,98)</code> should return <code>5488</code>.
testString: assert.equal(eth_mult(56, 98), 5488);
- text: <code>eth_mult(63,74)</code> should return <code>4662</code>.
testString: assert.equal(eth_mult(63, 74), 4662);
```
@@ -41,7 +50,7 @@ tests:
<div id='js-seed'>
```js
function eth_mult (a, b) {
function eth_mult(a, b) {
// Good luck!
}
@@ -49,14 +58,31 @@ function eth_mult (a, b) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function eth_mult(a, b) {
let sum = 0; a = [a]; b = [b];
let half = a => a / 2,
double = a => a * 2,
is_even = a => a % 2 == 0;
while (a[0] !== 1) {
a.unshift(Math.floor(half(a[0])));
b.unshift(double(b[0]));
}
for (let i = a.length - 1; i > 0; i -= 1) {
if (!is_even(a[i])) {
sum += b[i];
}
}
return sum + b[0];
}
```
</section>

View File

@@ -2,15 +2,31 @@
title: Euler method
id: 59880443fb36441083c6c20e
challengeType: 5
videoUrl: ''
forumTopicId: 302258
localeTitle: Метод Эйлера
---
## Description
<section id="description"><p> Метод Эйлера численно аппроксимирует решения обыкновенных дифференциальных уравнений первого порядка (ОДУ) с заданным начальным значением. Это явный метод решения начальных задач (IVP), как описано <a href="https://en.wikipedia.org/wiki/Euler method" title="wp: метод Эйлера">на странице wikipedia</a> . </p><p> ОДУ должно быть представлено в следующем виде: </p><p> :: <big>$ \ frac {dy (t)} {dt} = f (t, y (t)) $</big> </p><p> с начальным значением </p><p> :: <big>$ y (t_0) = y_0 $</big> </p><p> Чтобы получить числовое решение, мы заменим производную на LHS с помощью разностной аппроксимации: </p><p> :: <big>$ \ frac {dy (t)} {dt} \ approx \ frac {y (t + h) -y (t)} {h} $</big> </p><p> затем решить для $ y (t + h) $: </p><p> :: <big>$ y (t + h) \ approx y (t) + h \, \ frac {dy (t)} {dt} $</big> </p><p> который является таким же, как </p><p> :: <big>$ y (t + h) \ approx y (t) + h \, f (t, y (t)) $</big> </p><p> Итеративное правило решения: </p><p> :: <big>$ y_ {n + 1} = y_n + h \, f (t_n, y_n) $</big> </p><p> где <big>$ h $</big> - размер шага, наиболее важный параметр для точности решения. Чем меньше размер шага, тем выше точность, но также и стоимость вычислений, поэтому его всегда нужно выбирать вручную в зависимости от проблемы. </p><p> Пример: закон охлаждения Ньютона </p><p> Закон охлаждения Ньютона описывает, как объект начальной температуры <big>$ T (t_0) = T_0 $</big> остывает в среде с температурой <big>$ T_R $</big> : </p><p> :: <big>$ \ frac {dT (t)} {dt} = -k \, \ Delta T $</big> </p><p> или </p><p> :: <big>$ \ frac {dT (t)} {dt} = -k \, (T (t) - T_R) $</big> </p><p> В нем говорится, что скорость охлаждения <big>$ \ frac {dT (t)} {dt} $</big> объекта пропорциональна текущей разности температур <big>$ \ Delta T = (T (t) - T_R) $</big> в окружающую среду. </p><p> Аналитическое решение, которое мы будем сравнивать с численным приближением, </p><p> :: <big>$ T (t) = T_R + (T_0 - T_R) \; е ^ {-} $ кт</big> </p> Задача: <p> Внедрить рутину метода Эйлера, а затем использовать его для решения данного примера закона охлаждения Ньютона с ним для трех разных размеров шага: </p><p> :: * 2 с </p><p> :: * 5 с и </p><p> :: * 10 с </p><p> и сравнить с аналитическим решением. </p> Начальные значения: <p> :: * начальная температура <big>$ T_0 $</big> должна быть 100 ° C </p><p> :: * комнатная температура <big>$ T_R $</big> должна составлять 20 ° C </p><p> :: * постоянная охлаждения <big>$ k $</big> должна составлять 0,07 </p><p> :: * интервал времени для вычисления должен составлять от 0 с ──► 100 с </p></section>
<section id='description'>
<p> Метод Эйлера численно аппроксимирует решения обыкновенных дифференциальных уравнений первого порядка (ОДУ) с заданным начальным значением. Это явный метод решения начальных задач (IVP), как описано <a href="https://en.wikipedia.org/wiki/Euler method" title="wp: метод Эйлера">на странице wikipedia</a> . </p><p> ОДУ должно быть представлено в следующем виде: </p><p> :: <big>$ \ frac {dy (t)} {dt} = f (t, y (t)) $</big> </p><p> с начальным значением </p><p> :: <big>$ y (t_0) = y_0 $</big> </p><p> Чтобы получить числовое решение, мы заменим производную на LHS с помощью разностной аппроксимации: </p><p> :: <big>$ \ frac {dy (t)} {dt} \ approx \ frac {y (t + h) -y (t)} {h} $</big> </p><p> затем решить для $ y (t + h) $: </p><p> :: <big>$ y (t + h) \ approx y (t) + h \, \ frac {dy (t)} {dt} $</big> </p><p> который является таким же, как </p><p> :: <big>$ y (t + h) \ approx y (t) + h \, f (t, y (t)) $</big> </p><p> Итеративное правило решения: </p><p> :: <big>$ y_ {n + 1} = y_n + h \, f (t_n, y_n) $</big> </p><p> где <big>$ h $</big> - размер шага, наиболее важный параметр для точности решения. Чем меньше размер шага, тем выше точность, но также и стоимость вычислений, поэтому его всегда нужно выбирать вручную в зависимости от проблемы. </p><p> Пример: закон охлаждения Ньютона </p><p> Закон охлаждения Ньютона описывает, как объект начальной температуры <big>$ T (t_0) = T_0 $</big> остывает в среде с температурой <big>$ T_R $</big> : </p><p> :: <big>$ \ frac {dT (t)} {dt} = -k \, \ Delta T $</big> </p><p> или </p><p> :: <big>$ \ frac {dT (t)} {dt} = -k \, (T (t) - T_R) $</big> </p><p> В нем говорится, что скорость охлаждения <big>$ \ frac {dT (t)} {dt} $</big> объекта пропорциональна текущей разности температур <big>$ \ Delta T = (T (t) - T_R) $</big> в окружающую среду. </p><p> Аналитическое решение, которое мы будем сравнивать с численным приближением, </p><p> :: <big>$ T (t) = T_R + (T_0 - T_R) \; е ^ {-} $ кт</big> </p> Задача: <p> Внедрить рутину метода Эйлера, а затем использовать его для решения данного примера закона охлаждения Ньютона с ним для трех разных размеров шага: </p><p> :: * 2 с </p><p> :: * 5 с и </p><p> :: * 10 с </p><p> и сравнить с аналитическим решением. </p> Начальные значения: <p> :: * начальная температура <big>$ T_0 $</big> должна быть 100 ° C </p><p> :: * комнатная температура <big>$ T_R $</big> должна составлять 20 ° C </p><p> :: * постоянная охлаждения <big>$ k $</big> должна составлять 0,07 </p><p> :: * интервал времени для вычисления должен составлять от 0 с ──► 100 с </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
<ul>
<li><code>2 s</code></li>
<li><code>5 s</code> and</li>
<li><code>10 s</code></li>
</ul>
and to compare with the analytical solution.
<strong>Initial values:</strong>
<ul>
<li>initial temperature <big>$T_0$</big> shall be <code>100 °C</code></li>
<li>room temperature <big>$T_R$</big> shall be <code>20 °C</code></li>
<li>cooling constant <big>$k$</big> shall be <code>0.07</code></li>
<li>time interval to calculate shall be from <code>0 s</code> to <code>100 s</code></li>
</ul>
</section>
## Tests
@@ -18,16 +34,16 @@ localeTitle: Метод Эйлера
```yml
tests:
- text: <code>eulersMethod</code> - это функция.
testString: 'assert(typeof eulersMethod === "function", "<code>eulersMethod</code> is a function.");'
- text: '<code>eulersMethod(0, 100, 100, 10)</code> должен возвращать число.'
testString: 'assert(typeof eulersMethod(0, 100, 100, 10) === "number", "<code>eulersMethod(0, 100, 100, 10)</code> should return a number.");'
- text: '<code>eulersMethod(0, 100, 100, 10)</code> должен возвращать 20.0424631833732.'
testString: 'assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732, "<code>eulersMethod(0, 100, 100, 10)</code> should return 20.0424631833732.");'
- text: '<code>eulersMethod(0, 100, 100, 10)</code> должен возвращать 20.01449963666907.'
testString: 'assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907, "<code>eulersMethod(0, 100, 100, 10)</code> should return 20.01449963666907.");'
- text: '<code>eulersMethod(0, 100, 100, 10)</code> должен возвращать 20.000472392.'
testString: 'assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392, "<code>eulersMethod(0, 100, 100, 10)</code> should return 20.000472392.");'
- text: <code>eulersMethod</code> is a function.
testString: assert(typeof eulersMethod === 'function');
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return a number.
testString: assert(typeof eulersMethod(0, 100, 100, 10) === 'number');
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return 20.0424631833732.
testString: assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732);
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return 20.01449963666907.
testString: assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907);
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return 20.000472392.
testString: assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392);
```
@@ -39,7 +55,7 @@ tests:
<div id='js-seed'>
```js
function eulersMethod (x1, y1, x2, h) {
function eulersMethod(x1, y1, x2, h) {
// Good luck!
}
@@ -47,14 +63,23 @@ function eulersMethod (x1, y1, x2, h) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function eulersMethod(x1, y1, x2, h) {
let x = x1;
let y = y1;
while ((x < x2 && x1 < x2) || (x > x2 && x1 > x2)) {
y += h * (-0.07 * (y - 20));
x += h;
}
return y;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Evaluate binomial coefficients
id: 598de241872ef8353c58a7a2
challengeType: 5
videoUrl: ''
forumTopicId: 302259
localeTitle: Оценить биномиальные коэффициенты
---
## Description
<section id="description"><p> Напишите функцию для вычисления биномиального коэффициента при заданном значении n и k. </p><p> Эта формула рекомендуется: </p> $ \ binom {n} {k} = \ frac {n!} {(nk)! k!} = \ frac {n (n-1) (n-2) \ ldots (n-k + 1)} { k (k-1) (k-2) \ ldots 1} $ </section>
<section id='description'>
<p> Напишите функцию для вычисления биномиального коэффициента при заданном значении n и k. </p><p> Эта формула рекомендуется: </p> $ \ binom {n} {k} = \ frac {n!} {(nk)! k!} = \ frac {n (n-1) (n-2) \ ldots (n-k + 1)} { k (k-1) (k-2) \ ldots 1} $
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Оценить биномиальные коэффициенты
```yml
tests:
- text: <code>binom</code> - функция.
testString: 'assert(typeof binom === "function", "<code>binom</code> is a function.");'
- text: '<code>binom(5,3)</code> следует вернуть 10.'
testString: 'assert.equal(binom(5, 3), 10, "<code>binom(5,3)</code> should return 10.");'
- text: '<code>binom(7,2)</code> должен вернуть 21.'
testString: 'assert.equal(binom(7, 2), 21, "<code>binom(7,2)</code> should return 21.");'
- text: '<code>binom(10,4)</code> должен вернуть 210.'
testString: 'assert.equal(binom(10, 4), 210, "<code>binom(10,4)</code> should return 210.");'
- text: '<code>binom(6,1)</code> должен вернуть 6.'
testString: 'assert.equal(binom(6, 1), 6, "<code>binom(6,1)</code> should return 6.");'
- text: '<code>binom(12,8)</code> должен вернуть 495.'
testString: 'assert.equal(binom(12, 8), 495, "<code>binom(12,8)</code> should return 495.");'
- text: <code>binom</code> is a function.
testString: assert(typeof binom === 'function');
- text: <code>binom(5,3)</code> should return 10.
testString: assert.equal(binom(5, 3), 10);
- text: <code>binom(7,2)</code> should return 21.
testString: assert.equal(binom(7, 2), 21);
- text: <code>binom(10,4)</code> should return 210.
testString: assert.equal(binom(10, 4), 210);
- text: <code>binom(6,1)</code> should return 6.
testString: assert.equal(binom(6, 1), 6);
- text: <code>binom(12,8)</code> should return 495.
testString: assert.equal(binom(12, 8), 495);
```
@@ -41,7 +44,7 @@ tests:
<div id='js-seed'>
```js
function binom (n, k) {
function binom(n, k) {
// Good luck!
}
@@ -49,14 +52,18 @@ function binom (n, k) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function binom(n, k) {
let coeff = 1;
for (let i = n - k + 1; i <= n; i++) coeff *= i;
for (let i = 1; i <= k; i++) coeff /= i;
return coeff;
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Execute a Markov algorithm
id: 59e09e6d412c5939baa02d16
challengeType: 5
videoUrl: ''
forumTopicId: 302260
localeTitle: Выполнить алгоритм Маркова
---
## Description
<section id="description"> Задача: <p> Создайте интерпретатор для <a href="https://en.wikipedia.org/wiki/Markov algorithm" title="wp: алгоритм Маркова">алгоритма Маркова</a> . </p><p> Правила имеют синтаксис: </p><p><ruleset> знак равно <comment> | <rule> ) <newline> +) * </newline></rule></comment></ruleset></p><p><comment> знак равно <any character=""> } </any></comment></p><p><rule> знак равно <pattern><whitespace> -&gt; <whitespace> [.] <replacement></replacement></whitespace></whitespace></pattern></rule></p><p><whitespace> знак равно <tab> | <space> ) [ <whitespace> ] </whitespace></space></tab></whitespace></p><p> В каждой строке есть одно правило. </p><p> Если есть <b>.</b> (период), присутствующий до <replacement> , то это правило окончания, в этом случае интерпретатор должен остановить выполнение. </replacement></p><p> Набор правил состоит из последовательности правил с необязательными комментариями. </p><p> <big><big>Rulesets</big></big> </p><p> Используйте следующие тесты для записей: </p> Правила 1: <pre> Этот файл правил извлекается из Википедии:
<section id='description'>
Задача: <p> Создайте интерпретатор для <a href="https://en.wikipedia.org/wiki/Markov algorithm" title="wp: алгоритм Маркова">алгоритма Маркова</a> . </p><p> Правила имеют синтаксис: </p><p><ruleset> знак равно <comment> | <rule> ) <newline> +) * </newline></rule></comment></ruleset></p><p><comment> знак равно <any character=""> } </any></comment></p><p><rule> знак равно <pattern><whitespace> -&gt; <whitespace> [.] <replacement></replacement></whitespace></whitespace></pattern></rule></p><p><whitespace> знак равно <tab> | <space> ) [ <whitespace> ] </whitespace></space></tab></whitespace></p><p> В каждой строке есть одно правило. </p><p> Если есть <b>.</b> (период), присутствующий до <replacement> , то это правило окончания, в этом случае интерпретатор должен остановить выполнение. </replacement></p><p> Набор правил состоит из последовательности правил с необязательными комментариями. </p><p> <big><big>Rulesets</big></big> </p><p> Используйте следующие тесты для записей: </p> Правила 1: <pre> Этот файл правил извлекается из Википедии:
http://en.wikipedia.org/wiki/Markov_AlgorithmA -&gt; яблоко
B -&gt; сумка
S -&gt; магазин
@@ -63,10 +64,12 @@ _ + _ -&gt;
1C0 -&gt; B11
состояние C, символ 1 =&gt; запись 1, перемещение влево, halt0C1 -&gt; H01
1C1 -&gt; H11
</pre><p> Этот набор правил должен </p><p> <code>000000A000000</code> </p> <p> в </p><p> <code>00011H1111000</code> </p> </section>
</pre><p> Этот набор правил должен </p><p> <code>000000A000000</code> </p> <p> в </p><p> <code>00011H1111000</code> </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -74,18 +77,18 @@ _ + _ -&gt;
```yml
tests:
- text: <code>markov</code> - функция.
testString: 'assert(typeof markov === "function", "<code>markov</code> is a function.");'
- text: '<code>markov([&quot;A -&gt; apple&quot;,&quot;B -&gt; bag&quot;,&quot;S -&gt; shop&quot;,&quot;T -&gt; the&quot;,&quot;the shop -&gt; my brother&quot;,&quot;a never used -&gt; .terminating rule&quot;],&quot;I bought a B of As from T S.&quot;)</code> должен вернуться «Я купил мешок с яблоками от моего брата».'
testString: 'assert.deepEqual(markov(rules[0],tests[0]),outputs[0],"<code>markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from my brother.".");'
- text: '<code>markov([&quot;A -&gt; apple&quot;,&quot;B -&gt; bag&quot;,&quot;S -&gt; .shop&quot;,&quot;T -&gt; the&quot;,&quot;the shop -&gt; my brother&quot;,&quot;a never used -&gt; .terminating rule&quot;],&quot;I bought a B of As from T S.&quot;)</code> должен вернуться« Я купил мешок яблок из магазина T ».'
testString: 'assert.deepEqual(markov(rules[1],tests[1]),outputs[1],"<code>markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from T shop.".");'
- text: '<code>markov([&quot;A -&gt; apple&quot;,&quot;WWWW -&gt; with&quot;,&quot;Bgage -&gt; -&gt;.*&quot;,&quot;B -&gt; bag&quot;,&quot;-&gt;.* -&gt; money&quot;,&quot;W -&gt; WW&quot;,&quot;S -&gt; .shop&quot;,&quot;T -&gt; the&quot;,&quot;the shop -&gt; my brother&quot;,&quot;a never used -&gt; .terminating rule&quot;],&quot;I bought a B of As W my Bgage from T S.&quot;)</code> должен вернуться« Я купил мешок с яблоками с моими деньгами из магазина T ».'
testString: 'assert.deepEqual(markov(rules[2],tests[2]),outputs[2],"<code>markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")</code> should return "I bought a bag of apples with my money from T shop.".");'
- text: '<code>markov([&quot;_+1 -&gt; _1+&quot;,&quot;1+1 -&gt; 11+&quot;,&quot;1! -&gt; !1&quot;,&quot;,! -&gt; !+&quot;,&quot;_! -&gt; _&quot;,&quot;1*1 -&gt; x,@y&quot;,&quot;1x -&gt; xX&quot;,&quot;X, -&gt; 1,1&quot;,&quot;X1 -&gt; 1X&quot;,&quot;_x -&gt; _X&quot;,&quot;,x -&gt; ,X&quot;,&quot;y1 -&gt; 1y&quot;,&quot;y_ -&gt; _&quot;,&quot;1@1 -&gt; x,@y&quot;,&quot;1@_ -&gt; @_&quot;,&quot;,@_ -&gt; !_&quot;,&quot;++ -&gt; +&quot;,&quot;_1 -&gt; 1&quot;,&quot;1+_ -&gt; 1&quot;,&quot;_+_ -&gt; &quot;],&quot;_1111*11111_&quot;)</code> должен возвращать&quot; 11111111111111111111 &quot;.'
testString: 'assert.deepEqual(markov(rules[3],tests[3]),outputs[3],"<code>markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")</code> should return "11111111111111111111".");'
- text: '<code>markov([&quot;A0 -&gt; 1B&quot;,&quot;0A1 -&gt; C01&quot;,&quot;1A1 -&gt; C11&quot;,&quot;0B0 -&gt; A01&quot;,&quot;1B0 -&gt; A11&quot;,&quot;B1 -&gt; 1B&quot;,&quot;0C0 -&gt; B01&quot;,&quot;1C0 -&gt; B11&quot;,&quot;0C1 -&gt; H01&quot;,&quot;1C1 -&gt; H11&quot;],&quot;&quot;)</code> должны возвращать« 00011H1111000 ».'
testString: 'assert.deepEqual(markov(rules[4],tests[4]),outputs[4],"<code>markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")</code> should return "00011H1111000".");'
- text: <code>markov</code> is a function.
testString: assert(typeof markov === 'function');
- text: <code>markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from my brother.".
testString: assert.deepEqual(markov(rules[0],tests[0]),outputs[0]);
- text: <code>markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from T shop.".
testString: assert.deepEqual(markov(rules[1],tests[1]),outputs[1]);
- text: <code>markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")</code> should return "I bought a bag of apples with my money from T shop.".
testString: assert.deepEqual(markov(rules[2],tests[2]),outputs[2]);
- text: <code>markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")</code> should return "11111111111111111111".
testString: assert.deepEqual(markov(rules[3],tests[3]),outputs[3]);
- text: <code>markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")</code> should return "00011H1111000".
testString: assert.deepEqual(markov(rules[4],tests[4]),outputs[4]);
```
@@ -97,7 +100,7 @@ tests:
<div id='js-seed'>
```js
function markov (rules,test) {
function markov(rules,test) {
// Good luck!
}
@@ -105,14 +108,56 @@ function markov (rules,test) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function markov(rules,test) {
let pattern = new RegExp("^([^#]*?)\\s+->\\s+(\\.?)(.*)");
let origTest = test;
let captures = [];
rules.forEach(function(rule){
let m = pattern.exec(rule);
for (let j = 0; j < m.length; j++)
m[j] = m[j + 1];
captures.push(m);
});
test = origTest;
let copy = test;
for (let j = 0; j < captures.length; j++) {
let c = captures[j];
test = test.replace(c[0], c[2]);
if (c[1]==".")
break;
if (test!=copy) {
j = -1;
copy = test;
}
}
return test;
}
// tail:
let rules=[["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],
["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"]];
let tests=["I bought a B of As from T S.",
"I bought a B of As from T S.",
"I bought a B of As W my Bgage from T S.",
"_1111*11111_",
"000000A000000"];
let outputs=["I bought a bag of apples from my brother.",
"I bought a bag of apples from T shop.",
"I bought a bag of apples with my money from T shop.",
"11111111111111111111",
"00011H1111000"];
```
</section>

View File

@@ -2,15 +2,18 @@
title: Execute Brain****
id: 59e0a8df964e4540d5abe599
challengeType: 5
videoUrl: ''
forumTopicId: 302261
localeTitle: Выполнить мозг ****
---
## Description
<section id="description"><p> Напишите функцию для реализации интерпретатора Brain ****. Функция примет строку как параметр и должна вернуть строку в качестве вывода. Более подробная информация приведена ниже: </p><p> RCBF представляет собой набор компиляторов и интерпретаторов <a href="http://rosettacode.org/wiki/Brainf***" title="Brainf ***">Brainf ***,</a> написанных для Rosetta Code на разных языках. </p><p> Ниже приведены ссылки на каждую из версий RCBF. </p><p> Для реализации необходимо только правильно выполнить следующие инструкции: </p><p> {| </p><p> ! Command </p><p> !Описание </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>&gt;</code> || Переместите указатель вправо </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>&lt;</code> || Переместите указатель влево </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>+</code> || Увеличение ячейки памяти под указателем </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>-</code> || Уменьшить ячейку памяти под указателем </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>.</code> || Вывести символ, обозначенный ячейкой указателем </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>,</code> || Введите символ и сохраните его в ячейке указателя </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>[</code> || Перейти мимо соответствия <code>]</code> если ячейка под указателем равна 0 </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>]</code> || Вернитесь к совпадению <code>[</code> если ячейка под указателем отлична от нуля </p><p> |} </p><p> Любой размер ячейки разрешен, поддержка EOF ( <u>E</u> nd- <u>O-</u> <u>F</u> ile) необязательна, равно как и ограниченная или неограниченная память. </p></section>
<section id='description'>
<p> Напишите функцию для реализации интерпретатора Brain ****. Функция примет строку как параметр и должна вернуть строку в качестве вывода. Более подробная информация приведена ниже: </p><p> RCBF представляет собой набор компиляторов и интерпретаторов <a href="http://rosettacode.org/wiki/Brainf***" title="Brainf ***">Brainf ***,</a> написанных для Rosetta Code на разных языках. </p><p> Ниже приведены ссылки на каждую из версий RCBF. </p><p> Для реализации необходимо только правильно выполнить следующие инструкции: </p><p> {| </p><p> ! Command </p><p> !Описание </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>&gt;</code> || Переместите указатель вправо </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>&lt;</code> || Переместите указатель влево </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>+</code> || Увеличение ячейки памяти под указателем </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>-</code> || Уменьшить ячейку памяти под указателем </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>.</code> || Вывести символ, обозначенный ячейкой указателем </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>,</code> || Введите символ и сохраните его в ячейке указателя </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>[</code> || Перейти мимо соответствия <code>]</code> если ячейка под указателем равна 0 </p><p> | - </p><p> | стиль = «выравнивание текста: центр» | <code>]</code> || Вернитесь к совпадению <code>[</code> если ячейка под указателем отлична от нуля </p><p> |} </p><p> Любой размер ячейки разрешен, поддержка EOF ( <u>E</u> nd- <u>O-</u> <u>F</u> ile) необязательна, равно как и ограниченная или неограниченная память. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Выполнить мозг ****
```yml
tests:
- text: <code>brain(bye)</code> должен возвращать строку
testString: 'assert(typeof brain(bye) === "string", "<code>brain(bye)</code> should return a string");'
- text: '<code>brain("++++++[>++++++++++<-]>+++++.")</code should return "A"'
testString: 'assert.equal(brain("++++++[>++++++++++<-]>+++++."),"A", "<code>brain("++++++[>++++++++++<-]>+++++.")</code should return "A"");'
- text: '<code>brain(bye)</code> должен возвращать <code>Goodbye, World!\\r\\n</code>'
testString: 'assert.equal(brain(bye), "Goodbye, World!\r\n", "<code>brain(bye)</code> should return <code>Goodbye, World!\\r\\n</code>");'
- text: '<code>brain(hello)</code> должен вернуть <code>Hello World!\\n</code> &#39;'
testString: 'assert.equal(brain(hello), "Hello World!\n", "<code>brain(hello)</code> should return <code>Hello World!\\n</code>");'
- text: '<code>brain(fib)</code> должен возвращать <code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89</code>'
testString: 'assert.equal(brain(fib), "1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89", "<code>brain(fib)</code> should return <code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89</code>");'
- text: <code>brain(bye)</code> should return a string
testString: assert(typeof brain(bye) === 'string');
- text: <code>brain("++++++[>++++++++++<-]>+++++.")</code should return "A"
testString: assert.equal(brain("++++++[>++++++++++<-]>+++++."),"A");
- text: <code>brain(bye)</code> should return <code>Goodbye, World!\\r\\n</code>
testString: assert.equal(brain(bye), 'Goodbye, World!\r\n');
- text: <code>brain(hello)</code> should return <code>Hello World!\\n</code>
testString: assert.equal(brain(hello), "Hello World!\n");
- text: <code>brain(fib)</code> should return <code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89</code>
testString: assert.equal(brain(fib), "1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89");
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function brain (prog) {
function brain(prog) {
// Good luck!
}
@@ -47,7 +50,7 @@ function brain (prog) {
</div>
### Before Test
### Before Tests
<div id='js-setup'>
```js
@@ -121,13 +124,67 @@ let bye='++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++++++++++>++++++++++
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function brain(prog){
var output="";
var code; // formatted code
var ip = 0; // current instruction within code
var nest = 0; // current bracket nesting (for Out button)
var ahead = []; // locations of matching brackets
var data = [0]; // data array (mod by +, -)
var dp = 0; // index into data (mod by <, >)
var inp = 0; // current input character (fetch with ,)
var quit = 0;
var commands = {
'>':function() { if (++dp >= data.length) data[dp]=0 },
'<':function() { if (--dp < 0) quit++ },
'+':function() { ++data[dp] },
'-':function() { --data[dp] },
'[':function() { if (!data[dp]) ip = ahead[ip]; else ++nest },
']':function() { if ( data[dp]) ip = ahead[ip]; else --nest },
',':function() {
var c = document.getElementById("input").value.charCodeAt(inp++);
data[dp] = isNaN(c) ? 0 : c; // EOF: other options are -1 or no change
},
'.':function() {
output+=String.fromCharCode(data[dp]);
/*var s = document.getElementById("output").innerHTML)
+ String.fromCharCode(data[dp]);
s = s.replace(/\n/g,"<br>").replace(/ /g,"&amp;nbsp;");
document.getElementById("output").innerHTML = s;*/
},
};
let ar=prog.split('');
var st = [], back, error = -1;
for (ip=0; ip<ar.length; ip++) {
switch(ar[ip]) {
case '[':
st.push(ip);
break;
case ']':
if (st.length == 0) error = ip;
back = st.pop();
ahead[ip] = back;
ahead[back] = ip;
break;
}
}
for(ip=0;ip<ar.length;ip++){
if(commands.hasOwnProperty(ar[ip]))
commands[ar[ip]]();
}
return output;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Extensible prime generator
id: 598ee8b91b410510ae82efef
challengeType: 5
videoUrl: ''
forumTopicId: 302262
localeTitle: Расширяемый первичный генератор
---
## Description
<section id="description"><p> Напишите генератор простых чисел, чтобы он автоматически регулировался для генерации любого разумно высокого премьер. </p> Генератор должен иметь возможность: Показывать первые <b>n</b> простых чисел. Показывать простые числа в диапазоне. Показывать количество простых чисел в диапазоне. Показывать <b>n- <sup>е</sup></b> простое число. <p> Функция должна иметь два параметра. Первый получит <b>n</b> или диапазон в виде массива. Вторая будет получать логическое значение, которое указывает, возвращает ли функция числа простых чисел в виде массива или одного числа (числа простых чисел в диапазоне или <b>n- <sup>го</sup></b> числа). В соответствии с параметрами функция должна возвращать массив. </p></section>
<section id='description'>
<p> Напишите генератор простых чисел, чтобы он автоматически регулировался для генерации любого разумно высокого премьер. </p> Генератор должен иметь возможность: Показывать первые <b>n</b> простых чисел. Показывать простые числа в диапазоне. Показывать количество простых чисел в диапазоне. Показывать <b>n- <sup>е</sup></b> простое число. <p> Функция должна иметь два параметра. Первый получит <b>n</b> или диапазон в виде массива. Вторая будет получать логическое значение, которое указывает, возвращает ли функция числа простых чисел в виде массива или одного числа (числа простых чисел в диапазоне или <b>n- <sup>го</sup></b> числа). В соответствии с параметрами функция должна возвращать массив. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Расширяемый первичный генератор
```yml
tests:
- text: <code>primeGenerator</code> - функция.
testString: 'assert(typeof primeGenerator === "function", "<code>primeGenerator</code> is a function.");'
- text: <code>primeGenerator</code> - функция.
testString: 'assert.deepEqual(primeGenerator(20, true), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71], "<code>primeGenerator</code> is a function.");'
- text: <code>primeGenerator</code> - функция.
testString: 'assert.deepEqual(primeGenerator([100, 150], true), [101, 103, 107, 109, 113, 127, 131, 137, 139, 149], "<code>primeGenerator</code> is a function.");'
- text: <code>primeGenerator</code> - функция.
testString: 'assert.equal(primeGenerator([7700, 8000], false), 30, "<code>primeGenerator</code> is a function.");'
- text: <code>primeGenerator</code> - функция.
testString: 'assert.equal(primeGenerator(10000, false), 104729, "<code>primeGenerator</code> is a function.");'
- text: <code>primeGenerator</code> is a function.
testString: assert(typeof primeGenerator === 'function');
- text: <code>primeGenerator</code> is a function.
testString: assert.deepEqual(primeGenerator(20, true), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]);
- text: <code>primeGenerator</code> is a function.
testString: assert.deepEqual(primeGenerator([100, 150], true), [101, 103, 107, 109, 113, 127, 131, 137, 139, 149]);
- text: <code>primeGenerator</code> is a function.
testString: assert.equal(primeGenerator([7700, 8000], false), 30);
- text: <code>primeGenerator</code> is a function.
testString: assert.equal(primeGenerator(10000, false), 104729);
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function primeGenerator (num, showPrimes) {
function primeGenerator(num, showPrimes) {
// Good luck!
}
@@ -47,14 +50,51 @@ function primeGenerator (num, showPrimes) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
// noprotect
function primeGenerator(num, showPrimes) {
let i,
arr = [];
function isPrime(num) {
// try primes <= 16
if (num <= 16) { return (
num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13
); }
// cull multiples of 2, 3, 5 or 7
if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num % 7 == 0)
{ return false; }
// cull square numbers ending in 1, 3, 7 or 9
for (let i = 10; i * i <= num; i += 10) {
if (num % (i + 1) == 0) return false;
if (num % (i + 3) == 0) return false;
if (num % (i + 7) == 0) return false;
if (num % (i + 9) == 0) return false;
}
return true;
}
if (typeof num === 'number') {
for (i = 0; arr.length < num; i++) if (isPrime(i)) arr.push(i);
// first x primes
if (showPrimes) return arr;
// xth prime
return arr.pop();
}
if (Array.isArray(num)) {
for (i = num[0]; i <= num[1]; i++) if (isPrime(i)) arr.push(i);
// primes between x .. y
if (showPrimes) return arr;
// number of primes between x .. y
return arr.length;
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Factorial
id: 597b2b2a2702b44414742771
challengeType: 5
videoUrl: ''
forumTopicId: 302263
localeTitle: Факториал
---
## Description
<section id="description"><p> Напишите функцию для возврата факториала числа. </p><p> Факториал числа определяется: </p> п! = n * (n-1) * (n-2) * ..... * 1 <p> Например: 3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 </p><p> Примечание: 0! = 1 </p></section>
<section id='description'>
<p> Напишите функцию для возврата факториала числа. </p><p> Факториал числа определяется: </p> п! = n * (n-1) * (n-2) * ..... * 1 <p> Например: 3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 </p><p> Примечание: 0! = 1 </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Факториал
```yml
tests:
- text: <code>factorial</code> - это функция.
testString: 'assert(typeof factorial === "function", "<code>factorial</code> is a function.");'
- text: <code>factorial(2)</code> должен возвращать число.
testString: 'assert(typeof factorial(2) === "number", "<code>factorial(2)</code> should return a number.");'
- text: <code>factorial(3)</code> должен вернуть 6. &quot;)
testString: 'assert.equal(factorial(3),results[0],"<code>factorial(3)</code> should return 6.");'
- text: <code>factorial(3)</code> должен вернуть 120. »)
testString: 'assert.equal(factorial(5),results[1],"<code>factorial(3)</code> should return 120.");'
- text: '<code>factorial(3)</code> должен вернуть 3,628,800. &quot;)'
testString: 'assert.equal(factorial(10),results[2],"<code>factorial(3)</code> should return 3,628,800.");'
- text: <code>factorial</code> is a function.
testString: assert(typeof factorial === 'function');
- text: <code>factorial(2)</code> should return a number.
testString: assert(typeof factorial(2) === 'number');
- text: <code>factorial(3)</code> should return 6.
testString: assert.equal(factorial(3),results[0]);
- text: <code>factorial(3)</code> should return 120.
testString: assert.equal(factorial(5),results[1]);
- text: <code>factorial(3)</code> should return 3,628,800.
testString: assert.equal(factorial(10),results[2]);
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function factorial (n) {
function factorial(n) {
// Good luck!
}
@@ -47,12 +50,12 @@ function factorial (n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const results=[6,120,3628800];
```
</div>
@@ -63,6 +66,14 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function factorial(n) {
let sum = 1;
while (n > 1) {
sum *= n;
n--;
}
return sum;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Factors of an integer
id: 597f1e7fbc206f0e9ba95dc4
challengeType: 5
videoUrl: ''
forumTopicId: 302265
localeTitle: Факторы целого числа
---
## Description
<section id="description"><p> Напишите функцию, возвращающую множители положительного целого числа. </p><p> Этими факторами являются положительные целые числа, по которым число, подлежащее учету, можно разделить, чтобы получить положительный целочисленный результат. </p> /// </section>
<section id='description'>
<p> Напишите функцию, возвращающую множители положительного целого числа. </p><p> Этими факторами являются положительные целые числа, по которым число, подлежащее учету, можно разделить, чтобы получить положительный целочисленный результат. </p> ///
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,14 +21,14 @@ localeTitle: Факторы целого числа
```yml
tests:
- text: <code>factors</code> - это функция.
testString: 'assert(typeof factors === "function", "<code>factors</code> is a function.");'
- text: '<code>factors(45)</code> должны вернуться <code>[1,3,5,9,15,45]</code> .'
testString: 'assert.deepEqual(factors(45), ans[0], "<code>factors(45)</code> should return <code>[1,3,5,9,15,45]</code>.");'
- text: '<code>factors(53)</code> должны возвращать <code>[1,53]</code> .'
testString: 'assert.deepEqual(factors(53), ans[1], "<code>factors(53)</code> should return <code>[1,53]</code>.");'
- text: '<code>factors(64)</code> должны возвращать <code>[1,2,4,8,16,32,64]</code> .'
testString: 'assert.deepEqual(factors(64), ans[2], "<code>factors(64)</code> should return <code>[1,2,4,8,16,32,64]</code>.");'
- text: <code>factors</code> is a function.
testString: assert(typeof factors === 'function');
- text: <code>factors(45)</code> should return <code>[1,3,5,9,15,45]</code>.
testString: assert.deepEqual(factors(45), ans[0]);
- text: <code>factors(53)</code> should return <code>[1,53]</code>.
testString: assert.deepEqual(factors(53), ans[1]);
- text: <code>factors(64)</code> should return <code>[1,2,4,8,16,32,64]</code>.
testString: assert.deepEqual(factors(64), ans[2]);
```
@@ -37,7 +40,7 @@ tests:
<div id='js-seed'>
```js
function factors (num) {
function factors(num) {
// Good luck!
}
@@ -45,12 +48,12 @@ function factors (num) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const ans=[[1,3,5,9,15,45],[1,53],[1,2,4,8,16,32,64]];
```
</div>
@@ -61,6 +64,20 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function factors(num)
{
let n_factors = [], i, sqr=Math.floor(Math.sqrt(num));
for (i = 1; i <=sqr ; i += 1)
if (num % i === 0)
{
n_factors.push(i);
if (num / i !== i)
n_factors.push(num / i);
}
n_factors.sort(function(a, b){return a - b;});
return n_factors;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Farey sequence
id: 59c3ec9f15068017c96eb8a3
challengeType: 5
videoUrl: ''
forumTopicId: 302266
localeTitle: Последовательность Farey
---
## Description
<section id="description"><p> Напишите функцию, которая возвращает последовательность Farey порядка n. Функция должна иметь один параметр, который равен n. Он должен возвращать последовательность в виде массива. Подробнее читайте ниже: </p><p> Последовательность <a href="https://en.wikipedia.org/wiki/Farey sequence" title="wp: последовательность Farey">Farey</a> F <sub>n</sub> порядка n представляет собой последовательность полностью восстановленных фракций между 0 и 1, которые, если в младших членах, имеют знаменатели, меньшие или равные n, упорядоченные в порядке возрастания. </p><p> Последовательность Farey иногда некорректно называется серией Farey. </p><p> Каждая последовательность Farey: </p><p> :: * начинается со значения 0, обозначаемого дробью $ \ frac {0} {1} $ </p><p> :: * заканчивается значением 1, обозначаемым дробью $ \ frac {1} {1} $. </p><p> Последовательности Farey от 1 до 5: </p><p> $ {\ bf \ it {F}} _ 1 = \ frac {0} {1}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 2 = \ frac {0} {1}, \ frac {1} {2}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 3 = \ frac {0} {1}, \ frac {1} {3}, \ frac {1} {2}, \ frac {2} {3}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 4 = \ frac {0} {1}, \ frac {1} {4}, \ frac {1} {3}, \ frac {1} {2}, \ frac {2} {3}, \ frac {3} {4}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 5 = \ frac {0} {1}, \ frac {1} {5}, \ frac {1} {4}, \ frac {1} {3}, \ frac {2} {5}, \ frac {1} {2}, \ frac {3} {5}, \ frac {2} {3}, \ frac {3} {4}, \ frac {4} {5 }, \ frac {1} {1} $ </p></section>
<section id='description'>
<p> Напишите функцию, которая возвращает последовательность Farey порядка n. Функция должна иметь один параметр, который равен n. Он должен возвращать последовательность в виде массива. Подробнее читайте ниже: </p><p> Последовательность <a href="https://en.wikipedia.org/wiki/Farey sequence" title="wp: последовательность Farey">Farey</a> F <sub>n</sub> порядка n представляет собой последовательность полностью восстановленных фракций между 0 и 1, которые, если в младших членах, имеют знаменатели, меньшие или равные n, упорядоченные в порядке возрастания. </p><p> Последовательность Farey иногда некорректно называется серией Farey. </p><p> Каждая последовательность Farey: </p><p> :: * начинается со значения 0, обозначаемого дробью $ \ frac {0} {1} $ </p><p> :: * заканчивается значением 1, обозначаемым дробью $ \ frac {1} {1} $. </p><p> Последовательности Farey от 1 до 5: </p><p> $ {\ bf \ it {F}} _ 1 = \ frac {0} {1}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 2 = \ frac {0} {1}, \ frac {1} {2}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 3 = \ frac {0} {1}, \ frac {1} {3}, \ frac {1} {2}, \ frac {2} {3}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 4 = \ frac {0} {1}, \ frac {1} {4}, \ frac {1} {3}, \ frac {1} {2}, \ frac {2} {3}, \ frac {3} {4}, \ frac {1} {1} $ </p><p></p><p> $ {\ bf \ it {F}} _ 5 = \ frac {0} {1}, \ frac {1} {5}, \ frac {1} {4}, \ frac {1} {3}, \ frac {2} {5}, \ frac {1} {2}, \ frac {3} {5}, \ frac {2} {3}, \ frac {3} {4}, \ frac {4} {5 }, \ frac {1} {1} $ </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that returns the Farey sequence of order <code>n</code>. The function should have one parameter that is <code>n</code>. It should return the sequence as an array.
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Последовательность Farey
```yml
tests:
- text: <code>farey</code> - это функция.
testString: 'assert(typeof farey === "function", "<code>farey</code> is a function.");'
- text: <code>farey(3)</code> должен возвращать массив
testString: 'assert(Array.isArray(farey(3)), "<code>farey(3)</code> should return an array");'
- text: '<code>farey(3)</code> должен возвращать <code>[&quot;1/3&quot;,&quot;1/2&quot;,&quot;2/3&quot;]</code>'
testString: 'assert.deepEqual(farey(3), ["1/3","1/2","2/3"], "<code>farey(3)</code> should return <code>["1/3","1/2","2/3"]</code>");'
- text: '<code>farey(4)</code> должен возвращать <code>[&quot;1/4&quot;,&quot;1/3&quot;,&quot;1/2&quot;,&quot;2/4&quot;,&quot;2/3&quot;,&quot;3/4&quot;]</code>'
testString: 'assert.deepEqual(farey(4), ["1/4","1/3","1/2","2/4","2/3","3/4"], "<code>farey(4)</code> should return <code>["1/4","1/3","1/2","2/4","2/3","3/4"]</code>");'
- text: '<code>farey(5)</code> должен возвращать <code>[&quot;1/5&quot;,&quot;1/4&quot;,&quot;1/3&quot;,&quot;2/5&quot;,&quot;1/2&quot;,&quot;2/4&quot;,&quot;3/5&quot;,&quot;2/3&quot;,&quot;3/4&quot;,&quot;4/5&quot;]</code>'
testString: 'assert.deepEqual(farey(5), ["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"], "<code>farey(5)</code> should return <code>["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]</code>");'
- text: <code>farey</code> is a function.
testString: assert(typeof farey === 'function');
- text: <code>farey(3)</code> should return an array
testString: assert(Array.isArray(farey(3)));
- text: <code>farey(3)</code> should return <code>["1/3","1/2","2/3"]</code>
testString: assert.deepEqual(farey(3), ["1/3","1/2","2/3"]);
- text: <code>farey(4)</code> should return <code>["1/4","1/3","1/2","2/4","2/3","3/4"]</code>
testString: assert.deepEqual(farey(4), ["1/4","1/3","1/2","2/4","2/3","3/4"]);
- text: <code>farey(5)</code> should return <code>["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]</code>
testString: assert.deepEqual(farey(5), ["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]);
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function farey (n) {
function farey(n) {
// Good luck!
}
@@ -47,14 +50,29 @@ function farey (n) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function farey(n){
let farSeq=[];
for(let den = 1; den <= n; den++){
for(let num = 1; num < den; num++){
farSeq.push({
str:num+"/"+den,
val:num/den});
}
}
farSeq.sort(function(a,b){
return a.val-b.val;
});
farSeq=farSeq.map(function(a){
return a.str;
});
return farSeq;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Fibonacci n-step number sequences
id: 598eef80ba501f1268170e1e
challengeType: 5
videoUrl: ''
forumTopicId: 302267
localeTitle: Число n-ступенчатых чисел Фибоначчи
---
## Description
<section id="description"><p> Напишите функцию для генерации последовательности n-шаговых последовательностей Фибоначчи и последовательностей Лукаса. Первым параметром будет n. Второй параметр будет состоять из числа возвращаемых элементов. Третий параметр будет определять, следует ли выводить последовательность Фибоначчи или последовательность Лукаса. Если параметр «f», то верните последовательность Фибоначчи, и если это «l», верните последовательность Лукаса. Последовательности должны быть возвращены как массив. Более подробная информация приведена ниже: </p><p> Эти ряды чисел являются расширением обычной <a href="http://rosettacode.org/wiki/Fibonacci sequence" title="Последовательность Фибоначчи">последовательности Фибоначчи,</a> где: </p> При $ n = 2 $ мы имеем последовательность Фибоначчи; с начальными значениями $ [1, 1] $ и $ F_k ^ 2 = F_ {k-1} ^ 2 + F_ {k-2} ^ 2 $ При $ n = 3 $ мы имеем трибоначчивую последовательность; с начальными значениями $ [1, 1, 2] $ и $ F_k ^ 3 = F_ {k-1} ^ 3 + F_ {k-2} ^ 3 + F_ {k-3} ^ 3 $ При $ n = 4 $, мы имеем последовательность tetranacci; с начальными значениями $ [1, 1, 2, 4] $ и $ F_k ^ 4 = F_ {k-1} ^ 4 + F_ {k-2} ^ 4 + F_ {k-3} ^ 4 + F_ {k -4} ^ 4 $ ... Для общего $ n&gt; 2 $ мы имеем последовательность $ n $ -последовательности Фибоначчи - $ F_k ^ n $; с начальными значениями первых $ n $ значений $ (n-1) $ &#39;th Fibonacci $ n $ -ступенчатой ​​последовательности $ F_k ^ {n-1} $; и $ k $ -ное значение этой $ n $ -ой последовательности является $ F_k ^ n = \ sum_ {i = 1} ^ {(n)} {F_ {ki} ^ {(n)}} $ <p> При малых значениях $ n $ <a href="https://en.wikipedia.org/wiki/Number prefix#Greek_series" title="wp: Префикс номера # Greek_series">греческие числовые префиксы</a> иногда используются для индивидуального обозначения каждой серии. </p><p> {| style = &quot;text-align: left;&quot; border = &quot;4&quot; cellpadding = &quot;2&quot; cellspacing = &quot;2&quot; </p><p> | + Последовательности Фибоначчи $ n $ -ступят </p><p> | - style = &quot;background-color: rgb (255, 204, 255);&quot; </p><p> ! $ n $ !! Название серии !! Значения </p><p> | - </p><p> | 2 || Фибоначчи || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... </p><p> | - </p><p> | 3 || Трибоначчи || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... </p><p> | - </p><p> | 4 || тетранацци || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... </p><p> | - </p><p> | 5 || пентаначчи || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... </p><p> | - </p><p> | 6 || гексаначчи || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... </p><p> | - </p><p> | 7 || Гептаначи || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... </p><p> | - </p><p> | 8 || октоначчи || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... </p><p> | - </p><p> | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... </p><p> | - </p><p> | 10 || деканаци || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... </p><p> |} </p><p> Последовательности союзников могут быть сгенерированы при изменении начальных значений: </p><p> Серия <a href="https://en.wikipedia.org/wiki/Lucas number" title="wp: номер Лукаса">Lucas</a> суммирует два предыдущих значения, такие как ряд фибоначчи для $ n = 2 $, но использует начальные значения $ [2, 1] $. </p><p><!-- Lucas numbers, Lucas number, Lucas series [added to make searches easier.] --></p></section>
<section id='description'>
<p> Напишите функцию для генерации последовательности n-шаговых последовательностей Фибоначчи и последовательностей Лукаса. Первым параметром будет n. Второй параметр будет состоять из числа возвращаемых элементов. Третий параметр будет определять, следует ли выводить последовательность Фибоначчи или последовательность Лукаса. Если параметр «f», то верните последовательность Фибоначчи, и если это «l», верните последовательность Лукаса. Последовательности должны быть возвращены как массив. Более подробная информация приведена ниже: </p><p> Эти ряды чисел являются расширением обычной <a href="http://rosettacode.org/wiki/Fibonacci sequence" title="Последовательность Фибоначчи">последовательности Фибоначчи,</a> где: </p> При $ n = 2 $ мы имеем последовательность Фибоначчи; с начальными значениями $ [1, 1] $ и $ F_k ^ 2 = F_ {k-1} ^ 2 + F_ {k-2} ^ 2 $ При $ n = 3 $ мы имеем трибоначчивую последовательность; с начальными значениями $ [1, 1, 2] $ и $ F_k ^ 3 = F_ {k-1} ^ 3 + F_ {k-2} ^ 3 + F_ {k-3} ^ 3 $ При $ n = 4 $, мы имеем последовательность tetranacci; с начальными значениями $ [1, 1, 2, 4] $ и $ F_k ^ 4 = F_ {k-1} ^ 4 + F_ {k-2} ^ 4 + F_ {k-3} ^ 4 + F_ {k -4} ^ 4 $ ... Для общего $ n&gt; 2 $ мы имеем последовательность $ n $ -последовательности Фибоначчи - $ F_k ^ n $; с начальными значениями первых $ n $ значений $ (n-1) $ &#39;th Fibonacci $ n $ -ступенчатой ​​последовательности $ F_k ^ {n-1} $; и $ k $ -ное значение этой $ n $ -ой последовательности является $ F_k ^ n = \ sum_ {i = 1} ^ {(n)} {F_ {ki} ^ {(n)}} $ <p> При малых значениях $ n $ <a href="https://en.wikipedia.org/wiki/Number prefix#Greek_series" title="wp: Префикс номера # Greek_series">греческие числовые префиксы</a> иногда используются для индивидуального обозначения каждой серии. </p><p> {| style = &quot;text-align: left;&quot; border = &quot;4&quot; cellpadding = &quot;2&quot; cellspacing = &quot;2&quot; </p><p> | + Последовательности Фибоначчи $ n $ -ступят </p><p> | - style = &quot;background-color: rgb (255, 204, 255);&quot; </p><p> ! $ n $ !! Название серии !! Значения </p><p> | - </p><p> | 2 || Фибоначчи || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... </p><p> | - </p><p> | 3 || Трибоначчи || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... </p><p> | - </p><p> | 4 || тетранацци || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... </p><p> | - </p><p> | 5 || пентаначчи || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... </p><p> | - </p><p> | 6 || гексаначчи || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... </p><p> | - </p><p> | 7 || Гептаначи || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... </p><p> | - </p><p> | 8 || октоначчи || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... </p><p> | - </p><p> | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... </p><p> | - </p><p> | 10 || деканаци || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... </p><p> |} </p><p> Последовательности союзников могут быть сгенерированы при изменении начальных значений: </p><p> Серия <a href="https://en.wikipedia.org/wiki/Lucas number" title="wp: номер Лукаса">Lucas</a> суммирует два предыдущих значения, такие как ряд фибоначчи для $ n = 2 $, но использует начальные значения $ [2, 1] $. </p><p><!-- Lucas numbers, Lucas number, Lucas series [added to make searches easier.] --></p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function to generate Fibonacci $n$-step number sequences and Lucas sequences. The first parameter will be $n$. The second parameter will be the number of elements to be returned. The third parameter will specify whether to output the Fibonacci sequence or the Lucas sequence. If the parameter is <code>"f"</code> then return the Fibonacci sequence and if it is <code>"l"</code>, then return the Lucas sequence. The sequences must be returned as an array.
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: Число n-ступенчатых чисел Фибоначчи
```yml
tests:
- text: <code>fib_luc</code> является функцией.
testString: 'assert(typeof fib_luc === "function", "<code>fib_luc</code> is a function.");'
- text: '<code>fib_luc(2,10,&quot;f&quot;)</code> должен вернуть <code>[1,1,2,3,5,8,13,21,34,55]</code> .'
testString: 'assert.deepEqual(fib_luc(2,10,"f"),ans[0],"<code>fib_luc(2,10,"f")</code> should return <code>[1,1,2,3,5,8,13,21,34,55]</code>.");'
- text: '<code>fib_luc(3,15,&quot;f&quot;)</code> должен вернуться <code>[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]</code> .'
testString: 'assert.deepEqual(fib_luc(3,15,"f"),ans[1],"<code>fib_luc(3,15,"f")</code> should return <code>[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]</code>.");'
- text: '<code>fib_luc(4,15,&quot;f&quot;)</code> должен вернуться <code>[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]</code> .'
testString: 'assert.deepEqual(fib_luc(4,15,"f"),ans[2],"<code>fib_luc(4,15,"f")</code> should return <code>[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]</code>.");'
- text: '<code>fib_luc(2,10,&quot;l&quot;)</code> должен возвращать <code>[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]</code> .'
testString: 'assert.deepEqual(fib_luc(2,10,"l"),ans[3],"<code>fib_luc(2,10,"l")</code> should return <code>[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]</code>.");'
- text: '<code>fib_luc(3,15,&quot;l&quot;)</code> должны возвращать <code>[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]</code> .'
testString: 'assert.deepEqual(fib_luc(3,15,"l"),ans[4],"<code>fib_luc(3,15,"l")</code> should return <code>[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]</code>.");'
- text: '<code>fib_luc(4,15,&quot;l&quot;)</code> должен возвращать <code>[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]</code> .'
testString: 'assert.deepEqual(fib_luc(4,15,"l"),ans[5],"<code>fib_luc(4,15,"l")</code> should return <code>[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]</code>.");'
- text: '<code>fib_luc(5,15,&quot;l&quot;)</code> должен возвращать <code>[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]</code> .'
testString: 'assert.deepEqual(fib_luc(5,15,"l"),ans[6],"<code>fib_luc(5,15,"l")</code> should return <code>[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]</code>.");'
- text: <code>fib_luc</code> is a function.
testString: assert(typeof fib_luc === 'function');
- text: <code>fib_luc(2,10,"f")</code> should return <code>[1,1,2,3,5,8,13,21,34,55]</code>.
testString: assert.deepEqual(fib_luc(2,10,"f"),ans[0]);
- text: <code>fib_luc(3,15,"f")</code> should return <code>[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]</code>.
testString: assert.deepEqual(fib_luc(3,15,"f"),ans[1]);
- text: <code>fib_luc(4,15,"f")</code> should return <code>[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]</code>.
testString: assert.deepEqual(fib_luc(4,15,"f"),ans[2]);
- text: <code>fib_luc(2,10,"l")</code> should return <code>[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]</code>.
testString: assert.deepEqual(fib_luc(2,10,"l"),ans[3]);
- text: <code>fib_luc(3,15,"l")</code> should return <code>[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]</code>.
testString: assert.deepEqual(fib_luc(3,15,"l"),ans[4]);
- text: <code>fib_luc(4,15,"l")</code> should return <code>[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]</code>.
testString: assert.deepEqual(fib_luc(4,15,"l"),ans[5]);
- text: <code>fib_luc(5,15,"l")</code> should return <code>[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]</code>.
testString: assert.deepEqual(fib_luc(5,15,"l"),ans[6]);
```
@@ -45,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function fib_luc (n, len, w) {
function fib_luc(n, len, w) {
// Good luck!
}
@@ -53,12 +56,18 @@ function fib_luc (n, len, w) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const ans = [[1,1,2,3,5,8,13,21,34,55],
[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136],
[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536],
[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76],
[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ],
[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ],
[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]];
```
</div>
@@ -69,6 +78,22 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function fib_luc(n, len, w) {
function nacci(a, n, len) {
while (a.length < len) {
let sum = 0;
for (let i = Math.max(0, a.length - n); i < a.length; i++)
sum += a[i];
a.push(sum);
}
return a;
}
if(w=="f"){
return nacci(nacci([1,1], n, n), n, len);
}else{
return nacci(nacci([2,1], n, n), n, len);
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Fibonacci sequence
id: 597f24c1dda4e70f53c79c81
challengeType: 5
videoUrl: ''
forumTopicId: 302268
localeTitle: Последовательность Фибоначчи
---
## Description
<section id="description"><p> Напишите функцию для генерации <big>n- <sup>го</sup></big> числа Фибоначчи. </p> /// <p> <big>N- <sup>е</sup></big> число Фибоначчи дается: /// </p><p> F <sub>n</sub> = F <sub>n-1</sub> + F <sub>n-2</sub> </p> /// <p> Первые два члена серии - 0, 1. </p> /// <p> Следовательно, ряд равен: 0, 1, 1, 2, 3, 5, 8, 13 ... </p> /// </section>
<section id='description'>
<p> Напишите функцию для генерации <big>n- <sup>го</sup></big> числа Фибоначчи. </p> /// <p> <big>N- <sup>е</sup></big> число Фибоначчи дается: /// </p><p> F <sub>n</sub> = F <sub>n-1</sub> + F <sub>n-2</sub> </p> /// <p> Первые два члена серии - 0, 1. </p> /// <p> Следовательно, ряд равен: 0, 1, 1, 2, 3, 5, 8, 13 ... </p> ///
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Последовательность Фибоначчи
```yml
tests:
- text: <code>fibonacci</code> - это функция.
testString: 'assert(typeof fibonacci === "function", "<code>fibonacci</code> is a function.");'
- text: <code>fibonacci(2)</code> должны возвращать число.
testString: 'assert(typeof fibonacci(2) == "number", "<code>fibonacci(2)</code> should return a number.");'
- text: <code>fibonacci(3)</code> должны вернуть 1. &quot;)
testString: 'assert.equal(fibonacci(3),1,"<code>fibonacci(3)</code> should return 1.");'
- text: <code>fibonacci(5)</code> должны возвращать 3. &quot;)
testString: 'assert.equal(fibonacci(5),3,"<code>fibonacci(5)</code> should return 3.");'
- text: <code>fibonacci(10)</code> должны вернуть 34. »)
testString: 'assert.equal(fibonacci(10),34,"<code>fibonacci(10)</code> should return 34.");'
- text: <code>fibonacci</code> is a function.
testString: assert(typeof fibonacci === 'function');
- text: <code>fibonacci(2)</code> should return a number.
testString: assert(typeof fibonacci(2) == 'number');
- text: <code>fibonacci(3)</code> should return 1.
testString: assert.equal(fibonacci(3),1);
- text: <code>fibonacci(5)</code> should return 3.
testString: assert.equal(fibonacci(5),3);
- text: <code>fibonacci(10)</code> should return 34.
testString: assert.equal(fibonacci(10),34);
```
@@ -47,14 +50,21 @@ function fibonacci(n) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function fibonacci(n) {
let a = 0, b = 1, t;
while (--n > 0) {
t = a;
a = b;
b += t;
}
return a;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Fibonacci word
id: 5992e222d397f00d21122931
challengeType: 5
videoUrl: ''
forumTopicId: 302269
localeTitle: Слово Фибоначчи
---
## Description
<section id="description"><p> Напишите функцию для возврата слов Фибоначчи до N. N будет предоставлена ​​в качестве параметра функции. Функция должна возвращать массив объектов. Объекты должны иметь вид: {N: 1, Length: 1, Entropy: 0, Word: &#39;1&#39;}. Более подробная информация приведена ниже: </p><p> Слово Фибоначчи может быть создано способом, аналогичным последовательности Фибоначчи, <a href="http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf" title="ссылка: http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf">как описано здесь</a> : </p><p> Определите F_Word <sub>1</sub> как 1 </p><p> Определить F_Word <sub>2</sub> как 0 </p><p> Форма F_Word <sub>3</sub> как F_Word <sub>2,</sub> объединенная с F_Word <sub>1,</sub> то есть: 01 </p><p> Форма F_Word <sub>n</sub> как F_Word <sub>n-1,</sub> связанная с F_word <sub>n-2</sub> </p></section>
<section id='description'>
<p> Напишите функцию для возврата слов Фибоначчи до N. N будет предоставлена ​​в качестве параметра функции. Функция должна возвращать массив объектов. Объекты должны иметь вид: {N: 1, Length: 1, Entropy: 0, Word: &#39;1&#39;}. Более подробная информация приведена ниже: </p><p> Слово Фибоначчи может быть создано способом, аналогичным последовательности Фибоначчи, <a href="http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf" title="ссылка: http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf">как описано здесь</a> : </p><p> Определите F_Word <sub>1</sub> как 1 </p><p> Определить F_Word <sub>2</sub> как 0 </p><p> Форма F_Word <sub>3</sub> как F_Word <sub>2,</sub> объединенная с F_Word <sub>1,</sub> то есть: 01 </p><p> Форма F_Word <sub>n</sub> как F_Word <sub>n-1,</sub> связанная с F_word <sub>n-2</sub> </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function to return the Fibonacci Words up to <code>n</code>. <code>n</code> will be provided as a parameter to the function. The function should return an array of objects. The objects should be of the form: <code>{ N: 1, Length: 1, Entropy: 0, Word: '1' }</code>.
</section>
## Tests
@@ -18,12 +21,12 @@ localeTitle: Слово Фибоначчи
```yml
tests:
- text: <code>fibWord</code> - это функция.
testString: 'assert(typeof fibWord === "function", "<code>fibWord</code> is a function.");'
- text: <code>fibWord(5)</code> должен возвращать массив.
testString: 'assert(Array.isArray(fibWord(5)),"<code>fibWord(5)</code> should return an array.");'
- text: '<code>fibWord(5)</code> должен возвращать <code>&#39;+JSON.stringify(ans)+&#39;</code> .'
testString: 'assert.deepEqual(fibWord(5),ans,"<code>fibWord(5)</code> should return <code>"+JSON.stringify(ans)+"</code>.");'
- text: <code>fibWord</code> is a function.
testString: assert(typeof fibWord === 'function');
- text: <code>fibWord(5)</code> should return an array.
testString: assert(Array.isArray(fibWord(5)));
- text: <code>fibWord(5)</code> should return <code>[{ N:1, Length:1, Entropy:0, Word:"1" },{ N:2, Length:1, Entropy:0, Word:"0" },{ N:3, Length:2, Entropy:1, Word:"01" },{ N:4, Length:3, Entropy:0.9182958340544896, Word:"010" },{ N:5, Length:5, Entropy:0.9709505944546688, Word:"01001" }]</code>.
testString: assert.deepEqual(fibWord(5),ans);
```
@@ -35,7 +38,7 @@ tests:
<div id='js-seed'>
```js
function fibWord (n) {
function fibWord(n) {
// Good luck!
}
@@ -43,12 +46,20 @@ function fibWord (n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
let ans=[ { N: 1, Length: 1, Entropy: 0, Word: '1' },
{ N: 2, Length: 1, Entropy: 0, Word: '0' },
{ N: 3, Length: 2, Entropy: 1, Word: '01' },
{ N: 4, Length: 3, Entropy: 0.9182958340544896, Word: '010' },
{ N: 5, Length: 5, Entropy: 0.9709505944546688, Word: '01001' }];
```
</div>
@@ -59,6 +70,57 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function fibWord(n) {
function entropy(s) {
//create an object containing each individual char
//and the amount of iterations per char
function prob(s) {
var h = Object.create(null);
s.split('').forEach(function(c) {
h[c] && h[c]++ || (h[c] = 1);
});
return h;
}
s = s.toString(); //just in case
var e = 0, l = s.length, h = prob(s);
for (var i in h ) {
var p = h[i]/l;
e -= p * Math.log(p) / Math.log(2);
}
return e;
}
var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = [];
for (var i = 0; i < n; i++) {
if (i === 0 || i === 1) {
w = wNth[i];
} else {
w = wNth[i - 1] + wNth[i - 2];
wNth.push(w);
}
var l = w.length;
var e = entropy(w);
if (l <= 21) {
o.push({
N: i + 1,
Length: l,
Entropy: e,
Word: w
});
} else {
o.push({
N: i + 1,
Length: l,
Entropy: e,
Word: "..."
});
}
}
return o;
}
```
</section>

View File

@@ -1,16 +1,19 @@
---
title: Fractran
id: 5a7dad05be01840e1778a0d1
challengeType: 3
videoUrl: ''
challengeType: 5
forumTopicId: 302270
localeTitle: Fractran
---
## Description
<section id="description"><div class="rosetta"><p class="rosetta__paragraph"> <span class="rosetta__text--bold"><a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/FRACTRAN" title="wp: FRACTRAN">FRACTRAN</a></span> - полный эзотерический язык программирования Тьюринга, изобретенный математиком <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/John Horton Conway" title="wp: Джон Хортон Конвей">Джоном Хортоном Конвеем</a> . </p><br><p class="rosetta__paragraph"> Программа FRACTRAN представляет собой упорядоченный список положительных дробей $ P = (f_1, f_2, \ ldots, f_m) $ вместе с начальным положительным целым числом $ n $. </p><br><p class="rosetta__paragraph"> Программа запускается путем обновления целого числа $ n $ следующим образом: </p><br><ul class="rosetta__unordered-list"><li class="rosetta__list-item--unordered"> для первой фракции $ f_i $ в списке, для которого $ nf_i $ является целым числом, замените $ n $ на $ nf_i $; </li><li class="rosetta__list-item--unordered"> повторите это правило, пока никакая фракция в списке не выдает целое число при умножении на $ n $, а затем остановится. </li></ul><br><p class="rosetta__paragraph"> Конвей дал программу для простых чисел в FRACTRAN: </p><br><p class="rosetta__paragraph"> <span class="rosetta__text--indented">17 долл. США, долл. США, долл. США, долл. США / $ 13/11 $, $ 15/14 $, $ 15/2 $, $ 55/1 $</span> </p><br><p class="rosetta__paragraph"> Начиная с $ n = 2 $, эта программа FRACTRAN изменит $ n $ на $ 15 = 2 \ times (15/2) $, затем $ 825 = 15 \ times (55/1) $, генерируя следующую последовательность целых чисел: </p><br><p class="rosetta__paragraph"> <span class="rosetta__text--indented">$ 2 $, $ 15 $, $ 825 $, $ 725 $, $ 1925 $, $ 2275 $, $ 425 $, $ 390 $, $ 330 $, $ 290 $, $ 770 $, $ \ ldots $</span> </p><br><p class="rosetta__paragraph"> После 2 эта последовательность содержит следующие степени 2: </p><br><p class="rosetta__paragraph"> <span class="rosetta__text--indented">$ 2 ^ 2 = 4 $, $ 2 ^ 3 = 8 $, $ 2 ^ 5 = 32 $, $ 2 ^ 7 = 128 $, $ 2 ^ {11} = 2048 $, $ 2 ^ {13} = 8192 $, $ 2 ^ {17 } = 131072 $, $ 2 ^ {19} = 524288 $, $ \ ldots $</span> </p><br><p class="rosetta__paragraph"> которые являются главными полномочиями 2. </p><br><dl class="rosetta__description-list"><dt class="rosetta__description-title"> Задача: </dt></dl><p class="rosetta__paragraph"> Напишите функцию, которая принимает программу fractran как строковый параметр и возвращает первые 10 номеров программы в виде массива. Если результат не содержит 10 чисел, тогда возвращаем числа как есть. </p></div></section>
<section id='description'>
<div class="rosetta"><p class="rosetta__paragraph"> <span class="rosetta__text--bold"><a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/FRACTRAN" title="wp: FRACTRAN">FRACTRAN</a></span> - полный эзотерический язык программирования Тьюринга, изобретенный математиком <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/John Horton Conway" title="wp: Джон Хортон Конвей">Джоном Хортоном Конвеем</a> . </p><br><p class="rosetta__paragraph"> Программа FRACTRAN представляет собой упорядоченный список положительных дробей $ P = (f_1, f_2, \ ldots, f_m) $ вместе с начальным положительным целым числом $ n $. </p><br><p class="rosetta__paragraph"> Программа запускается путем обновления целого числа $ n $ следующим образом: </p><br><ul class="rosetta__unordered-list"><li class="rosetta__list-item--unordered"> для первой фракции $ f_i $ в списке, для которого $ nf_i $ является целым числом, замените $ n $ на $ nf_i $; </li><li class="rosetta__list-item--unordered"> повторите это правило, пока никакая фракция в списке не выдает целое число при умножении на $ n $, а затем остановится. </li></ul><br><p class="rosetta__paragraph"> Конвей дал программу для простых чисел в FRACTRAN: </p><br><p class="rosetta__paragraph"> <span class="rosetta__text--indented">17 долл. США, долл. США, долл. США, долл. США / $ 13/11 $, $ 15/14 $, $ 15/2 $, $ 55/1 $</span> </p><br><p class="rosetta__paragraph"> Начиная с $ n = 2 $, эта программа FRACTRAN изменит $ n $ на $ 15 = 2 \ times (15/2) $, затем $ 825 = 15 \ times (55/1) $, генерируя следующую последовательность целых чисел: </p><br><p class="rosetta__paragraph"> <span class="rosetta__text--indented">$ 2 $, $ 15 $, $ 825 $, $ 725 $, $ 1925 $, $ 2275 $, $ 425 $, $ 390 $, $ 330 $, $ 290 $, $ 770 $, $ \ ldots $</span> </p><br><p class="rosetta__paragraph"> После 2 эта последовательность содержит следующие степени 2: </p><br><p class="rosetta__paragraph"> <span class="rosetta__text--indented">$ 2 ^ 2 = 4 $, $ 2 ^ 3 = 8 $, $ 2 ^ 5 = 32 $, $ 2 ^ 7 = 128 $, $ 2 ^ {11} = 2048 $, $ 2 ^ {13} = 8192 $, $ 2 ^ {17 } = 131072 $, $ 2 ^ {19} = 524288 $, $ \ ldots $</span> </p><br><p class="rosetta__paragraph"> которые являются главными полномочиями 2. </p><br><dl class="rosetta__description-list"><dt class="rosetta__description-title"> Задача: </dt></dl><p class="rosetta__paragraph"> Напишите функцию, которая принимает программу fractran как строковый параметр и возвращает первые 10 номеров программы в виде массива. Если результат не содержит 10 чисел, тогда возвращаем числа как есть. </p></div>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes a fractran program as a string parameter and returns the first 10 numbers of the program as an array. If the result does not have 10 numbers then return the numbers as is.
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Fractran
```yml
tests:
- text: <code>fractran</code> должна быть функцией.
testString: 'assert(typeof fractran=="function","<code>fractran</code> should be a function.");'
- text: '<code>fractran(&quot;&quot;+tests[0]+&quot;&quot;)</code> должен возвращать массив.'
testString: 'assert(Array.isArray(fractran(tests[0])),"<code>fractran(""+tests[0]+"")</code> should return an array.");'
- text: '<code>fractran(&quot;&quot;+tests[0]+&quot;&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[0])+&quot;</code> .'
testString: 'assert.deepEqual(fractran(tests[0]),results[0],"<code>fractran(""+tests[0]+"")</code> should return <code>"+JSON.stringify(results[0])+"</code>.");'
- text: '<code>fractran(&quot;&quot;+tests[1]+&quot;&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[1])+&quot;</code> .'
testString: 'assert.deepEqual(fractran(tests[1]),results[1],"<code>fractran(""+tests[1]+"")</code> should return <code>"+JSON.stringify(results[1])+"</code>.");'
- text: '<code>fractran(&quot;&quot;+tests[2]+&quot;&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[2])+&quot;</code> .'
testString: 'assert.deepEqual(fractran(tests[2]),results[2],"<code>fractran(""+tests[2]+"")</code> should return <code>"+JSON.stringify(results[2])+"</code>.");'
- text: '<code>fractran(&quot;&quot;+tests[3]+&quot;&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[3])+&quot;</code> .'
testString: 'assert.deepEqual(fractran(tests[3]),results[3],"<code>fractran(""+tests[3]+"")</code> should return <code>"+JSON.stringify(results[3])+"</code>.");'
- text: '<code>fractran(&quot;&quot;+tests[4]+&quot;&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[4])+&quot;</code> .'
testString: 'assert.deepEqual(fractran(tests[4]),results[4],"<code>fractran(""+tests[4]+"")</code> should return <code>"+JSON.stringify(results[4])+"</code>.");'
- text: <code>fractran</code> should be a function.
testString: assert(typeof fractran=='function');
- text: <code>fractran("3/2, 1/3")</code> should return an array.
testString: assert(Array.isArray(fractran('3/2, 1/3')));
- text: <code>fractran("3/2, 1/3")</code> should return <code>[ 2, 3, 1 ]</code>.
testString: assert.deepEqual(fractran('3/2, 1/3'), [ 2, 3, 1 ]);
- text: <code>fractran("3/2, 5/3, 1/5")</code> should return <code>[ 2, 3, 5, 1 ]</code>.
testString: assert.deepEqual(fractran('3/2, 5/3, 1/5'), [ 2, 3, 5, 1 ]);
- text: <code>fractran("3/2, 6/3")</code> should return <code>[ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]</code>.
testString: assert.deepEqual(fractran('3/2, 6/3'), [ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]);
- text: <code>fractran("2/7, 7/2")</code> should return <code>[ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]</code>.
testString: assert.deepEqual(fractran('2/7, 7/2'), [ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]);
- text: <code>fractran("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1")</code> should return <code>[ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]</code>.
testString: assert.deepEqual(fractran('17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1'), [ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function fractran (progStr) {
function fractran(progStr) {
// Good luck!
}
@@ -51,22 +54,49 @@ function fractran (progStr) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function fractran(progStr){
var num = new Array();
var den = new Array();
var val ;
var out="";
function compile(prog){
var regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
while(regex.test(prog)){
num.push(regex.exec(prog)[1]);
den.push(regex.exec(prog)[2]);
prog = regex.exec(prog)[3];
}
}
function step(val){
var i=0;
while(i<den.length && val%den[i] != 0) i++;
return num[i]*val/den[i];
}
var seq=[]
function exec(val){
var i = 0;
while(val && i<limit){
seq.push(val)
val = step(val);
i ++;
}
}
// Main
compile(progStr);
var limit = 10;
exec(2);
return seq;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Gamma function
id: 5a23c84252665b21eecc7e76
challengeType: 5
videoUrl: ''
forumTopicId: 302271
localeTitle: Гамма-функция
---
## Description
<section id="description"> Внедрите один алгоритм (или более) для вычисления функции <a href="https://en.wikipedia.org/wiki/Gamma function">Gamma</a> ($ \ Gamma $) (только в реальном поле). Гамма-функция может быть определена как: <div style="padding-left: 4em;"> <big><big>$ \ Gamma (x) = \ displaystyle \ int_0 ^ \ infty t ^ {x-1} e ^ {- t} dt $</big></big> </div></section>
<section id='description'>
Внедрите один алгоритм (или более) для вычисления функции <a href="https://en.wikipedia.org/wiki/Gamma function">Gamma</a> ($ \ Gamma $) (только в реальном поле). Гамма-функция может быть определена как: <div style="padding-left: 4em;"> <big><big>$ \ Gamma (x) = \ displaystyle \ int_0 ^ \ infty t ^ {x-1} e ^ {- t} dt $</big></big> </div>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Гамма-функция
```yml
tests:
- text: <code>gamma</code> должна быть функцией.
testString: 'assert(typeof gamma=="function","<code>gamma</code> should be a function.")'
- text: '<code>gamma(&quot;+tests[0]+&quot;)</code> должно возвращать число.'
testString: 'assert(typeof gamma(tests[0])=="number","<code>gamma("+tests[0]+")</code> should return a number.")'
- text: '<code>gamma(&quot;+tests[0]+&quot;)</code> должен возвращать <code>&quot;+results[0]+&quot;</code> .'
testString: 'assert.equal(gamma(tests[0]),results[0],"<code>gamma("+tests[0]+")</code> should return <code>"+results[0]+"</code>.")'
- text: '<code>gamma(&quot;+tests[1]+&quot;)</code> должны возвращать <code>&quot;+results[1]+&quot;</code> .'
testString: 'assert.equal(gamma(tests[1]),results[1],"<code>gamma("+tests[1]+")</code> should return <code>"+results[1]+"</code>.")'
- text: '<code>gamma(&quot;+tests[2]+&quot;)</code> должен возвращать <code>&quot;+results[2]+&quot;</code> .'
testString: 'assert.equal(gamma(tests[2]),results[2],"<code>gamma("+tests[2]+")</code> should return <code>"+results[2]+"</code>.")'
- text: '<code>gamma(&quot;+tests[3]+&quot;)</code> должны возвращать <code>&quot;+results[3]+&quot;</code> .'
testString: 'assert.equal(gamma(tests[3]),results[3],"<code>gamma("+tests[3]+")</code> should return <code>"+results[3]+"</code>.")'
- text: '<code>gamma(&quot;+tests[4]+&quot;)</code> должны возвращать <code>&quot;+results[4]+&quot;</code> .'
testString: 'assert.equal(gamma(tests[4]),results[4],"<code>gamma("+tests[4]+")</code> should return <code>"+results[4]+"</code>.")'
- text: <code>gamma</code> should be a function.
testString: assert(typeof gamma=='function')
- text: <code>gamma(.1)</code> should return a number.
testString: assert(typeof gamma(.1)=='number')
- text: <code>gamma(.1)</code> should return <code>9.513507698668736</code>.
testString: assert.equal(round(gamma(.1)), round(9.513507698668736))
- text: <code>gamma(.2)</code> should return <code>4.590843711998803</code>.
testString: assert.equal(round(gamma(.2)), round(4.590843711998803))
- text: <code>gamma(.3)</code> should return <code>2.9915689876875904</code>.
testString: assert.equal(round(gamma(.3)), round(2.9915689876875904))
- text: <code>gamma(.4)</code> should return <code>2.218159543757687</code>.
testString: assert.equal(round(gamma(.4)), round(2.218159543757687))
- text: <code>gamma(.5)</code> should return <code>1.7724538509055159</code>.
testString: assert.equal(round(gamma(.5)), round(1.7724538509055159))
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function gamma (x) {
function gamma(x) {
// Good luck!
}
@@ -51,12 +54,14 @@ function gamma (x) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
function round(x) {
return Number(x).toPrecision(13);
}
```
</div>
@@ -67,6 +72,28 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function gamma(x) {
var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7
];
var g = 7;
if (x < 0.5) {
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
}
x -= 1;
var a = p[0];
var t = x + g + 0.5;
for (var i = 1; i < p.length; i++) {
a += p[i] / (x + i);
}
var result=Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
return result;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Gaussian elimination
id: 5a23c84252665b21eecc7e77
challengeType: 5
videoUrl: ''
forumTopicId: 302272
localeTitle: Гауссово исключение
---
## Description
<section id="description"> Напишите функцию для решения \ (Ax = b \), используя гауссово исключение, затем обратную замену. \ (A \) является матрицей \ (n \ times n \). Кроме того, \ (x \) и \ (b \) являются \ (n \) на 1 векторы. Чтобы повысить точность, используйте частичный поворот и масштабирование. </section>
<section id='description'>
Напишите функцию для решения \ (Ax = b \), используя гауссово исключение, затем обратную замену. \ (A \) является матрицей \ (n \ times n \). Кроме того, \ (x \) и \ (b \) являются \ (n \) на 1 векторы. Чтобы повысить точность, используйте частичный поворот и масштабирование.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Гауссово исключение
```yml
tests:
- text: <code>gaussianElimination</code> должно быть функцией.
testString: 'assert(typeof gaussianElimination=="function","<code>gaussianElimination</code> should be a function.");'
- text: '<code>gaussianElimination(&quot;+JSON.stringify(tests[0][0])+&quot;,&quot;+JSON.stringify(tests[0][1])+&quot;)</code> должны возвращать массив.'
testString: 'assert(Array.isArray(gaussianElimination(tests[0][0],tests[0][1])),"<code>gaussianElimination("+JSON.stringify(tests[0][0])+","+JSON.stringify(tests[0][1])+")</code> should return an array.");'
- text: '<code>gaussianElimination(&quot;+JSON.stringify(tests[0][0])+&quot;,&quot;+JSON.stringify(tests[0][1])+&quot;)</code> должны возвращать <code>&quot;+JSON.stringify(results[0])+&quot;</code> .'
testString: 'assert.deepEqual(gaussianElimination(tests[0][0],tests[0][1]),results[0],"<code>gaussianElimination("+JSON.stringify(tests[0][0])+","+JSON.stringify(tests[0][1])+")</code> should return <code>"+JSON.stringify(results[0])+"</code>.");'
- text: '<code>gaussianElimination(&quot;+JSON.stringify(tests[1][0])+&quot;,&quot;+JSON.stringify(tests[1][1])+&quot;)</code> должны возвращать <code>&quot;+JSON.stringify(results[1])+&quot;</code> .'
testString: 'assert.deepEqual(gaussianElimination(tests[1][0],tests[1][1]),results[1],"<code>gaussianElimination("+JSON.stringify(tests[1][0])+","+JSON.stringify(tests[1][1])+")</code> should return <code>"+JSON.stringify(results[1])+"</code>.");'
- text: '<code>gaussianElimination(&quot;+JSON.stringify(tests[2][0])+&quot;,&quot;+JSON.stringify(tests[2][1])+&quot;)</code> должны возвращать <code>&quot;+JSON.stringify(results[2])+&quot;</code> .'
testString: 'assert.deepEqual(gaussianElimination(tests[2][0],tests[2][1]),results[2],"<code>gaussianElimination("+JSON.stringify(tests[2][0])+","+JSON.stringify(tests[2][1])+")</code> should return <code>"+JSON.stringify(results[2])+"</code>.");'
- text: '<code>gaussianElimination(&quot;+JSON.stringify(tests[3][0])+&quot;,&quot;+JSON.stringify(tests[3][1])+&quot;)</code> должны возвращать <code>&quot;+JSON.stringify(results[3])+&quot;</code> .'
testString: 'assert.deepEqual(gaussianElimination(tests[3][0],tests[3][1]),results[3],"<code>gaussianElimination("+JSON.stringify(tests[3][0])+","+JSON.stringify(tests[3][1])+")</code> should return <code>"+JSON.stringify(results[3])+"</code>.");'
- text: '<code>gaussianElimination(&quot;+JSON.stringify(tests[4][0])+&quot;,&quot;+JSON.stringify(tests[4][1])+&quot;)</code> должны возвращать <code>&quot;+JSON.stringify(results[4])+&quot;</code> .'
testString: 'assert.deepEqual(gaussianElimination(tests[4][0],tests[4][1]),results[4],"<code>gaussianElimination("+JSON.stringify(tests[4][0])+","+JSON.stringify(tests[4][1])+")</code> should return <code>"+JSON.stringify(results[4])+"</code>.");'
- text: <code>gaussianElimination</code> should be a function.
testString: assert(typeof gaussianElimination=='function');
- text: <code>gaussianElimination([[1,1],[1,-1]], [5,1])</code> should return an array.
testString: assert(Array.isArray(gaussianElimination([[1,1],[1,-1]], [5,1])));
- text: <code>gaussianElimination([[1,1],[1,-1]], [5,1])</code> should return <code>[ 3, 2 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,1],[1,-1]], [5,1]), [ 3, 2 ]);
- text: <code>gaussianElimination([[2,3],[2,1]] , [8,4])</code> should return <code>[ 1, 2 ]</code>.
testString: assert.deepEqual(gaussianElimination([[2,3],[2,1]] , [8,4]), [ 1, 2 ]);
- text: <code>gaussianElimination([[1,3],[5,-2]], [14,19])</code> should return <code>[ 5, 3 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,3],[5,-2]], [14,19]), [ 5, 3 ]);
- text: <code>gaussianElimination([[1,1],[5,-1]] , [10,14])</code> should return <code>[ 4, 6 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,1],[5,-1]] , [10,14]), [ 4, 6 ]);
- text: <code>gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23])</code> should return <code>[ 1, 1, 1 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23]), [ 1, 1, 1 ]);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function gaussianElimination (A,b) {
function gaussianElimination(A,b) {
// Good luck!
}
@@ -51,22 +54,112 @@ function gaussianElimination (A,b) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function gaussianElimination(A, b) {
// Lower Upper Decomposition
function ludcmp(A) {
// A is a matrix that we want to decompose into Lower and Upper matrices.
var d = true
var n = A.length
var idx = new Array(n) // Output vector with row permutations from partial pivoting
var vv = new Array(n) // Scaling information
for (var i=0; i<n; i++) {
var max = 0
for (var j=0; j<n; j++) {
var temp = Math.abs(A[i][j])
if (temp > max) max = temp
}
if (max == 0) return // Singular Matrix!
vv[i] = 1 / max // Scaling
}
var Acpy = new Array(n)
for (var i=0; i<n; i++) {
var Ai = A[i]
let Acpyi = new Array(Ai.length)
for (j=0; j<Ai.length; j+=1) Acpyi[j] = Ai[j]
Acpy[i] = Acpyi
}
A = Acpy
var tiny = 1e-20 // in case pivot element is zero
for (var i=0; ; i++) {
for (var j=0; j<i; j++) {
var sum = A[j][i]
for (var k=0; k<j; k++) sum -= A[j][k] * A[k][i];
A[j][i] = sum
}
var jmax = 0
var max = 0;
for (var j=i; j<n; j++) {
var sum = A[j][i]
for (var k=0; k<i; k++) sum -= A[j][k] * A[k][i];
A[j][i] = sum
var temp = vv[j] * Math.abs(sum)
if (temp >= max) {
max = temp
jmax = j
}
}
if (i <= jmax) {
for (var j=0; j<n; j++) {
var temp = A[jmax][j]
A[jmax][j] = A[i][j]
A[i][j] = temp
}
d = !d;
vv[jmax] = vv[i]
}
idx[i] = jmax;
if (i == n-1) break;
var temp = A[i][i]
if (temp == 0) A[i][i] = temp = tiny
temp = 1 / temp
for (var j=i+1; j<n; j++) A[j][i] *= temp
}
return {A:A, idx:idx, d:d}
}
// Lower Upper Back Substitution
function lubksb(lu, b) {
// solves the set of n linear equations A*x = b.
// lu is the object containing A, idx and d as determined by the routine ludcmp.
var A = lu.A
var idx = lu.idx
var n = idx.length
var bcpy = new Array(n)
for (var i=0; i<b.length; i+=1) bcpy[i] = b[i]
b = bcpy
for (var ii=-1, i=0; i<n; i++) {
var ix = idx[i]
var sum = b[ix]
b[ix] = b[i]
if (ii > -1)
for (var j=ii; j<i; j++) sum -= A[i][j] * b[j]
else if (sum)
ii = i
b[i] = sum
}
for (var i=n-1; i>=0; i--) {
var sum = b[i]
for (var j=i+1; j<n; j++) sum -= A[i][j] * b[j]
b[i] = sum / A[i][i]
}
return b // solution vector x
}
var lu = ludcmp(A)
if (lu === undefined) return // Singular Matrix!
return lubksb(lu, b)
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: General FizzBuzz
id: 5a23c84252665b21eecc7e78
challengeType: 5
videoUrl: ''
forumTopicId: 302273
localeTitle: Общие вопросы FizzBuzz
---
## Description
<section id="description"> Напишите обобщенную версию <a href="http://rosettacode.org/wiki/FizzBuzz">FizzBuzz,</a> которая работает для любого списка факторов вместе со своими словами. Это в основном реализация «fizzbuzz», где правила игры предоставляются пользователю. Создайте функцию для ее реализации. Функция должна принимать два параметра. Первым будет массив с правилами FizzBuzz. Например: <code>[ [3,&quot;Fizz&quot;] , [5,&quot;Buzz&quot;] ]</code> . Это указывает на то, что <code>Fizz</code> следует печатать, если число кратно 3 и <code>Buzz</code> если оно кратно 5. Если оно кратно, то строки должны быть объединены в порядке, указанном в массиве. В этом случае <code>FizzBuzz</code> если число кратно 3 и 5. Второй параметр - это номер, для которого функция должна возвращать строку, как указано выше. </section>
<section id='description'>
Напишите обобщенную версию <a href="http://rosettacode.org/wiki/FizzBuzz">FizzBuzz,</a> которая работает для любого списка факторов вместе со своими словами. Это в основном реализация «fizzbuzz», где правила игры предоставляются пользователю. Создайте функцию для ее реализации. Функция должна принимать два параметра. Первым будет массив с правилами FizzBuzz. Например: <code>[ [3,&quot;Fizz&quot;] , [5,&quot;Buzz&quot;] ]</code> . Это указывает на то, что <code>Fizz</code> следует печатать, если число кратно 3 и <code>Buzz</code> если оно кратно 5. Если оно кратно, то строки должны быть объединены в порядке, указанном в массиве. В этом случае <code>FizzBuzz</code> если число кратно 3 и 5. Второй параметр - это номер, для которого функция должна возвращать строку, как указано выше.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,24 +21,24 @@ localeTitle: Общие вопросы FizzBuzz
```yml
tests:
- text: <code>genFizzBuzz</code> должен быть функцией.
testString: 'assert(typeof genFizzBuzz=="function","<code>genFizzBuzz</code> should be a function.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[0][0])+&quot;,&quot;+tests[0][1]+&quot;)</code> должны возвращать тип.'
testString: 'assert(typeof genFizzBuzz(tests[0][0],tests[0][1])=="string","<code>genFizzBuzz("+JSON.stringify(tests[0][0])+","+tests[0][1]+")</code> should return a type.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[0][0])+&quot;,&quot;+tests[0][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[0]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[0][0],tests[0][1]),results[0],"<code>genFizzBuzz("+JSON.stringify(tests[0][0])+","+tests[0][1]+")</code> should return <code>""+results[0]+""</code>.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[1][0])+&quot;,&quot;+tests[1][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[1]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[1][0],tests[1][1]),results[1],"<code>genFizzBuzz("+JSON.stringify(tests[1][0])+","+tests[1][1]+")</code> should return <code>""+results[1]+""</code>.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[2][0])+&quot;,&quot;+tests[2][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[2]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[2][0],tests[2][1]),results[2],"<code>genFizzBuzz("+JSON.stringify(tests[2][0])+","+tests[2][1]+")</code> should return <code>""+results[2]+""</code>.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[3][0])+&quot;,&quot;+tests[3][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[3]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[3][0],tests[3][1]),results[3],"<code>genFizzBuzz("+JSON.stringify(tests[3][0])+","+tests[3][1]+")</code> should return <code>""+results[3]+""</code>.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[4][0])+&quot;,&quot;+tests[4][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[4]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[4][0],tests[4][1]),results[4],"<code>genFizzBuzz("+JSON.stringify(tests[4][0])+","+tests[4][1]+")</code> should return <code>""+results[4]+""</code>.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[5][0])+&quot;,&quot;+tests[5][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[5]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[5][0],tests[5][1]),results[5],"<code>genFizzBuzz("+JSON.stringify(tests[5][0])+","+tests[5][1]+")</code> should return <code>""+results[5]+""</code>.");'
- text: '<code>genFizzBuzz(&quot;+JSON.stringify(tests[6][0])+&quot;,&quot;+tests[6][1]+&quot;)</code> должны возвращать <code>&quot;&quot;+results[6]+&quot;&quot;</code> .'
testString: 'assert.equal(genFizzBuzz(tests[6][0],tests[6][1]),results[6],"<code>genFizzBuzz("+JSON.stringify(tests[6][0])+","+tests[6][1]+")</code> should return <code>""+results[6]+""</code>.");'
- text: <code>genFizzBuzz</code> should be a function.
testString: assert(typeof genFizzBuzz=='function');
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)</code> should return a string.
testString: assert(typeof genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)=='string');
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)</code> should return <code>"Fizz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6), "Fizz");
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10)</code> should return <code>"Buzz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10), "Buzz");
- text: <code>genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12)</code> should return <code>"Buzz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12), "Buzz");
- text: <code>genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13)</code> should return <code>"13"</code>.
testString: assert.equal(genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13), '13');
- text: <code>genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15)</code> should return <code>"BuzzFizz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15), "BuzzFizz");
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15)</code> should return <code>"FizzBuzz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15), "FizzBuzz");
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105)</code> should return <code>"FizzBuzzBaxx"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105), "FizzBuzzBaxx");
```
@@ -47,7 +50,7 @@ tests:
<div id='js-seed'>
```js
function genFizzBuzz (rules, num) {
function genFizzBuzz(rules, num) {
// Good luck!
}
@@ -55,22 +58,25 @@ function genFizzBuzz (rules, num) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function genFizzBuzz(rules, num) {
let res='';
rules.forEach(function (e) {
if(num % e[0] == 0)
res+=e[1];
})
if(res==''){
res=num.toString();
}
return res;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Generate lower case ASCII alphabet
id: 5a23c84252665b21eecc7e7a
challengeType: 5
videoUrl: ''
forumTopicId: 302274
localeTitle: Создание алфавита ASCII в нижнем регистре
---
## Description
<section id="description"> Напишите функцию для генерации массива символов ASCII нижнего регистра для заданного диапазона. Например: для диапазона от 1 до 4 функция должна возвращать <code>[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]</code> . </section>
<section id='description'>
Напишите функцию для генерации массива символов ASCII нижнего регистра для заданного диапазона. Например: для диапазона от 1 до 4 функция должна возвращать <code>[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]</code> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Создание алфавита ASCII в нижнем регис
```yml
tests:
- text: <code>lascii</code> должен быть функцией.
testString: 'assert(typeof lascii=="function","<code>lascii</code> should be a function.");'
- text: '<code>lascii(&quot;a&quot;,&quot;d&quot;)</code> должен возвращать массив.'
testString: 'assert(Array.isArray(lascii("a","d")),"<code>lascii("a","d")</code> should return an array.");'
- text: <code>lascii(&quot;a&quot;,&quot;d&quot;)</code> должен возвращать <code>[ &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot; ]</code> ».'
testString: 'assert.deepEqual(lascii("a","d"),results[0],"<code>lascii("a","d")</code> should return <code>[ "a", "b", "c", "d" ]</code>.");'
- text: <code>lascii(&quot;c&quot;,&quot;i&quot;)</code> должен возвращать <code>[ &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot; ]</code> ».'
testString: 'assert.deepEqual(lascii("c","i"),results[1],"<code>lascii("c","i")</code> should return <code>[ "c", "d", "e", "f", "g", "h", "i" ]</code>.");'
- text: <code>lascii(&quot;m&quot;,&quot;q&quot;)</code> должен возвращать <code>[ &quot;m&quot;, &quot;n&quot;, &quot;o&quot;, &quot;p&quot;, &quot;q&quot; ]</code> ».'
testString: 'assert.deepEqual(lascii("m","q"),results[2],"<code>lascii("m","q")</code> should return <code>[ "m", "n", "o", "p", "q" ]</code>.");'
- text: <code>lascii(&quot;k&quot;,&quot;n&quot;)</code> должен возвращать <code>[ &quot;k&quot;, &quot;l&quot;, &quot;m&quot;, &quot;n&quot; ]</code> .»)'
testString: 'assert.deepEqual(lascii("k","n"),results[3],"<code>lascii("k","n")</code> should return <code>[ "k", "l", "m", "n" ]</code>.");'
- text: <code>lascii(&quot;t&quot;,&quot;z&quot;)</code> должен возвращать <code>[ &quot;t&quot;, &quot;u&quot;, &quot;v&quot;, &quot;w&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot; ]</code> .&quot;'
testString: 'assert.deepEqual(lascii("t","z"),results[4],"<code>lascii("t","z")</code> should return <code>[ "t", "u", "v", "w", "x", "y", "z" ]</code>.");'
- text: <code>lascii</code> should be a function.
testString: assert(typeof lascii=='function');
- text: <code>lascii("a","d")</code> should return an array.
testString: assert(Array.isArray(lascii('a','d')));
- text: <code>lascii('a','d')</code> should return <code>[ 'a', 'b', 'c', 'd' ]</code>.
testString: assert.deepEqual(lascii("a","d"),results[0]);
- text: <code>lascii('c','i')</code> should return <code>[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]</code>.
testString: assert.deepEqual(lascii("c","i"),results[1]);
- text: <code>lascii('m','q')</code> should return <code>[ 'm', 'n', 'o', 'p', 'q' ]</code>.
testString: assert.deepEqual(lascii("m","q"),results[2]);
- text: <code>lascii('k','n')</code> should return <code>[ 'k', 'l', 'm', 'n' ]</code>.
testString: assert.deepEqual(lascii("k","n"),results[3]);
- text: <code>lascii('t','z')</code> should return <code>[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]</code>.
testString: assert.deepEqual(lascii("t","z"),results[4]);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function lascii (cFrom, cTo) {
function lascii(cFrom, cTo) {
// Good luck!
}
@@ -51,12 +54,18 @@ function lascii (cFrom, cTo) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
let results=[
[ 'a', 'b', 'c', 'd' ],
[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ],
[ 'm', 'n', 'o', 'p', 'q' ],
[ 'k', 'l', 'm', 'n' ],
[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]
]
```
</div>
@@ -67,6 +76,23 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function lascii(cFrom, cTo) {
function cRange(cFrom, cTo) {
var iStart = cFrom.charCodeAt(0);
return Array.apply(
null, Array(cTo.charCodeAt(0) - iStart + 1)
).map(function (_, i) {
return String.fromCharCode(iStart + i);
});
}
return cRange(cFrom, cTo);
}
```
</section>

View File

@@ -7,10 +7,13 @@ localeTitle: GeneratorExponential
---
## Description
<section id="description"> Генератор - это исполняемый объект (например, функция или процедура), который содержит код, который дает последовательность значений по одному, так что каждый раз, когда вы вызываете генератор, предоставляется следующее значение в последовательности. Генераторы часто строятся поверх сопрограмм или объектов, так что внутреннее состояние объекта обрабатывается «естественно». Генераторы часто используются в ситуациях, когда последовательность потенциально бесконечна и где можно построить следующее значение последовательности с минимальным состоянием. Напишите функцию, которая использует генераторы для генерации квадратов и кубов. Создайте новый генератор, который фильтрует все кубы из генератора квадратов. Функция должна возвращать значение \ (n ^ {th} \) отфильтрованного генератора. Например, для \ (n = 7 \) функция должна возвращать 81, так как последовательность будет 4,9,16,25,36,49,81. Здесь 64 отфильтровывается, так как это куб. </section>
<section id='description'>
Генератор - это исполняемый объект (например, функция или процедура), который содержит код, который дает последовательность значений по одному, так что каждый раз, когда вы вызываете генератор, предоставляется следующее значение в последовательности. Генераторы часто строятся поверх сопрограмм или объектов, так что внутреннее состояние объекта обрабатывается «естественно». Генераторы часто используются в ситуациях, когда последовательность потенциально бесконечна и где можно построить следующее значение последовательности с минимальным состоянием. Напишите функцию, которая использует генераторы для генерации квадратов и кубов. Создайте новый генератор, который фильтрует все кубы из генератора квадратов. Функция должна возвращать значение \ (n ^ {th} \) отфильтрованного генератора. Например, для \ (n = 7 \) функция должна возвращать 81, так как последовательность будет 4,9,16,25,36,49,81. Здесь 64 отфильтровывается, так как это куб.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -32,7 +35,6 @@ tests:
testString: 'assert.equal(exponentialGenerator(20),484,"<code>exponentialGenerator(20)</code> should return <code>484</code>.");'
- text: <code>exponentialGenerator(25)</code> должен возвращать <code>784</code> .
testString: 'assert.equal(exponentialGenerator(25),784,"<code>exponentialGenerator(25)</code> should return <code>784</code>.");'
```
</section>
@@ -51,8 +53,6 @@ function exponentialGenerator (n) {
</div>
</section>
## Solution
@@ -61,4 +61,5 @@ function exponentialGenerator (n) {
```js
// solution required
```
</section>

View File

@@ -2,15 +2,38 @@
title: Gray code
id: 5a23c84252665b21eecc7e80
challengeType: 5
videoUrl: ''
forumTopicId: 302276
localeTitle: Серый код
---
## Description
<section id="description"> <a href="https://en.wikipedia.org/wiki/Gray code">Серый код</a> - это форма двоичного кодирования, где переходы между последовательными числами отличаются только одним битом. Это полезное кодирование для снижения опасности аппаратных данных со значениями, которые быстро изменяются и / или подключаются к более медленному оборудованию в качестве входных данных. Он также полезен для генерации входных данных для <a href="https://en.wikipedia.org/wiki/Karnaugh map">карт Карно</a> в порядке слева направо или сверху вниз. Создайте функцию для кодирования числа и декодирования числа из кода Grey. Функция должна иметь 2 параметра. Первый будет логическим. Функция должна кодироваться для истины и декодирования для false. Второй параметр будет номером, который должен быть закодирован / декодирован. Отображение нормальных двоичных представлений, представлений серого кода и декодированных значений кода Grey для всех 5-битных двоичных чисел (0-31 включительно, что приводит к 0 не нужно). Существует много возможных кодов Грея. Следующее кодирует так называемый «двоичный отраженный серый код». <br> Кодирование (MSB - бит 0, b - двоичный, g - код Grey): <code><br> if b[i-1] = 1 <br> <span style="padding-left:1em">g[i] = not b[i]</span> <br> else <br> <span style="padding-left:1em">g[i] = b[i]</span> <br></code> Или: <br> <code>g = b xor (b logically right shifted 1 time)</code> <br> Декодирование (MSB - бит 0, b - двоичный, g - код Grey): <br> <code>b[0] = g[0] <br> for other bits: <br> b[i] = g[i] xor b[i-1] <br></code> </section>
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Gray code">Серый код</a> - это форма двоичного кодирования, где переходы между последовательными числами отличаются только одним битом. Это полезное кодирование для снижения опасности аппаратных данных со значениями, которые быстро изменяются и / или подключаются к более медленному оборудованию в качестве входных данных. Он также полезен для генерации входных данных для <a href="https://en.wikipedia.org/wiki/Karnaugh map">карт Карно</a> в порядке слева направо или сверху вниз. Создайте функцию для кодирования числа и декодирования числа из кода Grey. Функция должна иметь 2 параметра. Первый будет логическим. Функция должна кодироваться для истины и декодирования для false. Второй параметр будет номером, который должен быть закодирован / декодирован. Отображение нормальных двоичных представлений, представлений серого кода и декодированных значений кода Grey для всех 5-битных двоичных чисел (0-31 включительно, что приводит к 0 не нужно). Существует много возможных кодов Грея. Следующее кодирует так называемый «двоичный отраженный серый код». <br> Кодирование (MSB - бит 0, b - двоичный, g - код Grey): <code><br> if b[i-1] = 1 <br> <span style="padding-left:1em">g[i] = not b[i]</span> <br> else <br> <span style="padding-left:1em">g[i] = b[i]</span> <br></code> Или: <br> <code>g = b xor (b logically right shifted 1 time)</code> <br> Декодирование (MSB - бит 0, b - двоичный, g - код Grey): <br> <code>b[0] = g[0] <br> for other bits: <br> b[i] = g[i] xor b[i-1] <br></code>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Create a function to encode a number to and decode a number from Gray code. The function should will have 2 parameters.
The first would be a boolean. The function should encode for true and decode for false. The second parameter would be the number to be encoded/decoded.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
<pre>
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
</pre>
Or:
<pre>
g = b xor (b logically right shifted 1 time)
</pre>
Decoding (MSB is bit 0, b is binary, g is Gray code):
<pre>
b[0] = g[0]<br>
for other bits:
b[i] = g[i] xor b[i-1]
</pre>
</section>
## Tests
@@ -18,22 +41,22 @@ localeTitle: Серый код
```yml
tests:
- text: <code>gray</code> должен быть функцией.
testString: 'assert(typeof gray=="function","<code>gray</code> should be a function.");'
- text: '<code>gray(true,177)</code> должен возвращать число.'
testString: 'assert(typeof gray(true,177)=="number","<code>gray(true,177)</code> should return a number.");'
- text: '<code>gray(true,177)</code> должен возвращать <code>233</code> .'
testString: 'assert.equal(gray(true,177),233,"<code>gray(true,177)</code> should return <code>233</code>.");'
- text: '<code>gray(true,425)</code> должен возвращать <code>381</code> .'
testString: 'assert.equal(gray(true,425),381,"<code>gray(true,425)</code> should return <code>381</code>.");'
- text: '<code>gray(true,870)</code> должен возвращать <code>725</code> .'
testString: 'assert.equal(gray(true,870),725,"<code>gray(true,870)</code> should return <code>725</code>.");'
- text: '<code>gray(false,233)</code> должен вернуть <code>177</code> .'
testString: 'assert.equal(gray(false,233),177,"<code>gray(false,233)</code> should return <code>177</code>.");'
- text: '<code>gray(false,381)</code> должен возвращать <code>425</code> .'
testString: 'assert.equal(gray(false,381),425,"<code>gray(false,381)</code> should return <code>425</code>.");'
- text: '<code>gray(false,725)</code> должен возвращать <code>870</code> .'
testString: 'assert.equal(gray(false,725),870,"<code>gray(false,725)</code> should return <code>870</code>.");'
- text: <code>gray</code> should be a function.
testString: assert(typeof gray=='function');
- text: <code>gray(true,177)</code> should return a number.
testString: assert(typeof gray(true,177)=='number');
- text: <code>gray(true,177)</code> should return <code>233</code>.
testString: assert.equal(gray(true,177),233);
- text: <code>gray(true,425)</code> should return <code>381</code>.
testString: assert.equal(gray(true,425),381);
- text: <code>gray(true,870)</code> should return <code>725</code>.
testString: assert.equal(gray(true,870),725);
- text: <code>gray(false,233)</code> should return <code>177</code>.
testString: assert.equal(gray(false,233),177);
- text: <code>gray(false,381)</code> should return <code>425</code>.
testString: assert.equal(gray(false,381),425);
- text: <code>gray(false,725)</code> should return <code>870</code>.
testString: assert.equal(gray(false,725),870);
```
@@ -53,14 +76,24 @@ function gray(enc, number) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function gray(enc, number){
if(enc){
return number ^ (number >> 1);
}else{
let n = number;
while (number >>= 1) {
n ^= number;
}
return n;
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Greatest common divisor
id: 5a23c84252665b21eecc7e82
challengeType: 5
videoUrl: ''
forumTopicId: 302277
localeTitle: Наибольший общий делитель
---
## Description
<section id="description"> Напишите функцию, которая возвращает наибольший общий делитель двух целых чисел. </section>
<section id='description'>
Напишите функцию, которая возвращает наибольший общий делитель двух целых чисел.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: Наибольший общий делитель
```yml
tests:
- text: <code>gcd</code> должна быть функцией.
testString: 'assert(typeof gcd=="function","<code>gcd</code> should be a function.");'
- text: '<code>gcd(24,36)</code> должен вернуть число.'
testString: 'assert(typeof gcd(24,36)=="number","<code>gcd(24,36)</code> should return a number.");'
- text: '<code>gcd(24,36)</code> должен вернуть <code>12</code> .'
testString: 'assert.equal(gcd(24,36),12,"<code>gcd(24,36)</code> should return <code>12</code>.");'
- text: '<code>gcd(30,48)</code> должен вернуть <code>6</code> .'
testString: 'assert.equal(gcd(30,48),6,"<code>gcd(30,48)</code> should return <code>6</code>.");'
- text: '<code>gcd(10,15)</code> должен вернуть <code>5</code> .'
testString: 'assert.equal(gcd(10,15),5,"<code>gcd(10,15)</code> should return <code>5</code>.");'
- text: '<code>gcd(100,25)</code> должен вернуть <code>25</code> .'
testString: 'assert.equal(gcd(100,25),25,"<code>gcd(100,25)</code> should return <code>25</code>.");'
- text: '<code>gcd(13,250)</code> должен вернуть <code>1</code> .'
testString: 'assert.equal(gcd(13,250),1,"<code>gcd(13,250)</code> should return <code>1</code>.");'
- text: '<code>gcd(1300,250)</code> должен вернуть <code>50</code> .'
testString: 'assert.equal(gcd(1300,250),50,"<code>gcd(1300,250)</code> should return <code>50</code>.");'
- text: <code>gcd</code> should be a function.
testString: assert(typeof gcd=='function');
- text: <code>gcd(24,36)</code> should return a number.
testString: assert(typeof gcd(24,36)=='number');
- text: <code>gcd(24,36)</code> should return <code>12</code>.
testString: assert.equal(gcd(24,36),12);
- text: <code>gcd(30,48)</code> should return <code>6</code>.
testString: assert.equal(gcd(30,48),6);
- text: <code>gcd(10,15)</code> should return <code>5</code>.
testString: assert.equal(gcd(10,15),5);
- text: <code>gcd(100,25)</code> should return <code>25</code>.
testString: assert.equal(gcd(100,25),25);
- text: <code>gcd(13,250)</code> should return <code>1</code>.
testString: assert.equal(gcd(13,250),1);
- text: <code>gcd(1300,250)</code> should return <code>50</code>.
testString: assert.equal(gcd(1300,250),50);
```
@@ -53,14 +56,15 @@ function gcd(a, b) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function gcd(a, b) {
return b==0 ? Math.abs(a):gcd(b, a % b);
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Greatest subsequential sum
id: 5a23c84252665b21eecc7e84
challengeType: 5
videoUrl: ''
forumTopicId: 302278
localeTitle: Наибольшая подпоследовательная сумма
---
## Description
<section id="description"> Если задана последовательность целых чисел, найдите непрерывную подпоследовательность, которая максимизирует сумму ее элементов, т. Е. Элементы ни одной отдельной подпоследовательности не прибавляют к значению, большему, чем это. Считается, что пустая подпоследовательность имеет сумму \ (0 \); таким образом, если все элементы отрицательны, результат должен быть пустой. </section>
<section id='description'>
Если задана последовательность целых чисел, найдите непрерывную подпоследовательность, которая максимизирует сумму ее элементов, т. Е. Элементы ни одной отдельной подпоследовательности не прибавляют к значению, большему, чем это. Считается, что пустая подпоследовательность имеет сумму \ (0 \); таким образом, если все элементы отрицательны, результат должен быть пустой.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: Наибольшая подпоследовательная сум
```yml
tests:
- text: <code>maximumSubsequence</code> должна быть функцией.
testString: 'assert(typeof maximumSubsequence=="function","<code>maximumSubsequence</code> should be a function.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[0])+&quot;)</code> должен возвращать массив.'
testString: 'assert(Array.isArray(maximumSubsequence(tests[0])),"<code>maximumSubsequence("+JSON.stringify(tests[0])+")</code> should return an array.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[0])+&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[0])+&quot;</code> .'
testString: 'assert.deepEqual(maximumSubsequence(tests[0]),results[0],"<code>maximumSubsequence("+JSON.stringify(tests[0])+")</code> should return <code>"+JSON.stringify(results[0])+"</code>.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[1])+&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[1])+&quot;</code> .'
testString: 'assert.deepEqual(maximumSubsequence(tests[1]),results[1],"<code>maximumSubsequence("+JSON.stringify(tests[1])+")</code> should return <code>"+JSON.stringify(results[1])+"</code>.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[2])+&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[2])+&quot;</code> .'
testString: 'assert.deepEqual(maximumSubsequence(tests[2]),results[2],"<code>maximumSubsequence("+JSON.stringify(tests[2])+")</code> should return <code>"+JSON.stringify(results[2])+"</code>.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[3])+&quot;)</code> должны возвращать <code>&quot;+JSON.stringify(results[3])+&quot;</code> .'
testString: 'assert.deepEqual(maximumSubsequence(tests[3]),results[3],"<code>maximumSubsequence("+JSON.stringify(tests[3])+")</code> should return <code>"+JSON.stringify(results[3])+"</code>.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[4])+&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[4])+&quot;</code> .'
testString: 'assert.deepEqual(maximumSubsequence(tests[4]),results[4],"<code>maximumSubsequence("+JSON.stringify(tests[4])+")</code> should return <code>"+JSON.stringify(results[4])+"</code>.");'
- text: '<code>maximumSubsequence(&quot;+JSON.stringify(tests[5])+&quot;)</code> должен возвращать <code>&quot;+JSON.stringify(results[5])+&quot;</code> .'
testString: 'assert.deepEqual(maximumSubsequence(tests[5]),results[5],"<code>maximumSubsequence("+JSON.stringify(tests[5])+")</code> should return <code>"+JSON.stringify(results[5])+"</code>.");'
- text: <code>maximumSubsequence</code> should be a function.
testString: assert(typeof maximumSubsequence=='function');
- text: <code>maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])</code> should return an array.
testString: assert(Array.isArray(maximumSubsequence([ 1, 2,-1, 3, 10, -10 ])));
- text: <code>maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])</code> should return <code>[ 1, 2, -1, 3, 10 ]</code>.
testString: assert.deepEqual(maximumSubsequence([1,2,-1,3,10,-10]), [ 1, 2, -1, 3, 10 ]);
- text: <code>maximumSubsequence([ 0, 8, 10, -2, -4, -1, -5, -3 ])</code> should return <code>[ 0, 8, 10 ]</code>.
testString: assert.deepEqual(maximumSubsequence([0, 8, 10, -2, -4, -1, -5, -3]), [ 0, 8, 10 ]);
- text: <code>maximumSubsequence([ 9, 9, -10, 1 ])</code> should return <code>[ 9, 9 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ 9, 9, -10, 1 ]), [ 9, 9 ]);
- text: <code>maximumSubsequence([ 7, 1, -5, -3, -8, 1 ]</code> should return <code>[ 7, 1 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ 7, 1, -5, -3, -8, 1 ]), [ 7, 1 ]);
- text: <code>maximumSubsequence([ -3, 6, -1, 4, -4, -6 ])</code> should return <code>[ 6, -1, 4 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ -3, 6, -1, 4, -4, -6 ]), [ 6, -1, 4 ]);
- text: <code>maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ])</code> should return <code>[ 3, 5, 6, -2, -1, 4 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ]), [ 3, 5, 6, -2, -1, 4 ]);
```
@@ -45,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function maximumSubsequence (population) {
function maximumSubsequence(population) {
// Good luck!
}
@@ -53,22 +56,37 @@ function maximumSubsequence (population) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function maximumSubsequence(population) {
function sumValues(arr) {
var result = 0;
for (var i = 0, len = arr.length; i < len; i++) {
result += arr[i];
}
return result;
}
var greatest;
var maxValue = 0;
var subsequence = [];
for (var i = 0, len = population.length; i < len; i++) {
for (var j = i; j <= len; j++) {
var subsequence = population.slice(i, j);
var value = sumValues(subsequence);
if (value > maxValue) {
maxValue = value;
greatest = subsequence;
};
}
}
return greatest;
}
```
</section>

View File

@@ -2,15 +2,26 @@
title: Hailstone sequence
id: 595608ff8bcd7a50bd490181
challengeType: 5
videoUrl: ''
forumTopicId: 302279
localeTitle: Последовательность градиента
---
## Description
<section id="description"><p> Последовательность чисел Hailstone может быть сгенерирована из начального положительного целого числа, n: </p> Если n равно 1, последовательность заканчивается. Если n четно, то следующее n последовательности <code>= n/2</code> Если n нечетно, то следующее n последовательности <code>= (3 * n) + 1</code> <p> (Неподтвержденная) <a href="https://en.wikipedia.org/wiki/Collatz conjecture" title="wp: гипотеза Collatz">гипотеза Collatz</a> заключается в том, что последовательность градиентов для любого начального числа всегда заканчивается. </p><p> Последовательность градиента также известна как номера градиента (поскольку значения обычно подвержены нескольким спуску и восхождениям, таким как град в облаке) или как последовательность Collatz. </p> Задача: создать процедуру для генерации последовательности градиента для числа. Используйте процедуру, чтобы показать, что последовательность градиента для числа 27 содержит 112 элементов, начиная с <code>27, 82, 41, 124</code> и заканчивая <code>8, 4, 2, 1</code> Покажите число менее 100 000, которое имеет самую длинную последовательность градиента вместе с этим длина последовательности. (Но не показывайте действительную последовательность!) См. Также: <a href="http://xkcd.com/710" title="ссылка: http://xkcd.com/710">xkcd</a> (humourous). </section>
<section id='description'>
<p> Последовательность чисел Hailstone может быть сгенерирована из начального положительного целого числа, n: </p> Если n равно 1, последовательность заканчивается. Если n четно, то следующее n последовательности <code>= n/2</code> Если n нечетно, то следующее n последовательности <code>= (3 * n) + 1</code> <p> (Неподтвержденная) <a href="https://en.wikipedia.org/wiki/Collatz conjecture" title="wp: гипотеза Collatz">гипотеза Collatz</a> заключается в том, что последовательность градиентов для любого начального числа всегда заканчивается. </p><p> Последовательность градиента также известна как номера градиента (поскольку значения обычно подвержены нескольким спуску и восхождениям, таким как град в облаке) или как последовательность Collatz. </p> Задача: создать процедуру для генерации последовательности градиента для числа. Используйте процедуру, чтобы показать, что последовательность градиента для числа 27 содержит 112 элементов, начиная с <code>27, 82, 41, 124</code> и заканчивая <code>8, 4, 2, 1</code> Покажите число менее 100 000, которое имеет самую длинную последовательность градиента вместе с этим длина последовательности. (Но не показывайте действительную последовательность!) См. Также: <a href="http://xkcd.com/710" title="ссылка: http://xkcd.com/710">xkcd</a> (humourous).
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
<ol>
<li>Create a routine to generate the hailstone sequence for a number</li>
<li>Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with <code>27, 82, 41, 124</code> and ending with <code>8, 4, 2, 1</code></li>
<li>Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)</li>
</ol>
<strong>See also:</strong>
<ul>
<li><a href="https://xkcd.com/710" target="_blank">xkcd</a> (humourous).</li>
</ul>
</section>
## Tests
@@ -18,10 +29,10 @@ localeTitle: Последовательность градиента
```yml
tests:
- text: <code>hailstoneSequence</code> - это функция.
testString: 'assert(typeof hailstoneSequence === "function", "<code>hailstoneSequence</code> is a function.");'
- text: '<code>hailstoneSequence()</code> должен возвращать <code>[[27,82,41,124,8,4,2,1], [351, 77031]]</code>'
testString: 'assert.deepEqual(hailstoneSequence(), res, "<code>hailstoneSequence()</code> should return <code>[[27,82,41,124,8,4,2,1], [351, 77031]]</code>");'
- text: <code>hailstoneSequence</code> is a function.
testString: assert(typeof hailstoneSequence === 'function');
- text: <code>hailstoneSequence()</code> should return <code>[[27,82,41,124,8,4,2,1], [351, 77031]]</code>
testString: assert.deepEqual(hailstoneSequence(), res);
```
@@ -34,7 +45,7 @@ tests:
```js
// noprotect
function hailstoneSequence () {
function hailstoneSequence() {
const res = [];
// Good luck!
@@ -45,12 +56,12 @@ function hailstoneSequence () {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const res = [[27, 82, 41, 124, 8, 4, 2, 1], [351, 77031]];
```
</div>
@@ -61,6 +72,38 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// noprotect
function hailstoneSequence () {
const res = [];
function hailstone(n) {
const seq = [n];
while (n > 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
seq.push(n);
}
return seq;
}
const h = hailstone(27);
const hLen = h.length;
res.push([...h.slice(0, 4), ...h.slice(hLen - 4, hLen)]);
let n = 0;
let max = 0;
for (let i = 100000; --i;) {
const seq = hailstone(i);
const sLen = seq.length;
if (sLen > max) {
n = i;
max = sLen;
}
}
res.push([max, n]);
return res;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Happy numbers
id: 594810f028c0303b75339ad1
challengeType: 5
videoUrl: ''
forumTopicId: 302280
localeTitle: Счастливые номера
---
## Description
<section id="description"><p> Счастливое число определяется следующим процессом: </p><p> Начиная с любого положительного целого числа, замените число на сумму квадратов его цифр и повторите процесс до тех пор, пока число не будет равно 1 (где оно останется), или оно бесконечно завершается в цикле, который не включает в себя 1. Эти цифры для которых этот процесс заканчивается на 1, являются счастливыми номерами, а те, которые не заканчиваются на 1, - это несчастливые цифры. </p><p> Реализуйте функцию, которая возвращает true, если число счастливое, или false, если нет. </p></section>
<section id='description'>
<p> Счастливое число определяется следующим процессом: </p><p> Начиная с любого положительного целого числа, замените число на сумму квадратов его цифр и повторите процесс до тех пор, пока число не будет равно 1 (где оно останется), или оно бесконечно завершается в цикле, который не включает в себя 1. Эти цифры для которых этот процесс заканчивается на 1, являются счастливыми номерами, а те, которые не заканчиваются на 1, - это несчастливые цифры. </p><p> Реализуйте функцию, которая возвращает true, если число счастливое, или false, если нет. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function that returns true if the number is happy, or false if not.
</section>
## Tests
@@ -18,32 +21,32 @@ localeTitle: Счастливые номера
```yml
tests:
- text: <code>happy</code> функция.
testString: 'assert(typeof happy === "function", "<code>happy</code> is a function.");'
- text: <code>happy(1)</code> должен возвращать логическое значение.
testString: 'assert(typeof happy(1) === "boolean", "<code>happy(1)</code> should return a boolean.");'
- text: <code>happy(1)</code> должен возвращать истину.
testString: 'assert(happy(1), "<code>happy(1)</code> should return true.");'
- text: <code>happy(2)</code> должен возвращать false.
testString: 'assert(!happy(2), "<code>happy(2)</code> should return false.");'
- text: <code>happy(7)</code> должен вернуться к истине.
testString: 'assert(happy(7), "<code>happy(7)</code> should return true.");'
- text: <code>happy(10)</code> должен вернуться к истине.
testString: 'assert(happy(10), "<code>happy(10)</code> should return true.");'
- text: <code>happy(13)</code> должен вернуться к истине.
testString: 'assert(happy(13), "<code>happy(13)</code> should return true.");'
- text: <code>happy(19)</code> должен вернуться к истине.
testString: 'assert(happy(19), "<code>happy(19)</code> should return true.");'
- text: <code>happy(23)</code> должен вернуться к истине.
testString: 'assert(happy(23), "<code>happy(23)</code> should return true.");'
- text: <code>happy(28)</code> должен вернуться к истине.
testString: 'assert(happy(28), "<code>happy(28)</code> should return true.");'
- text: <code>happy(31)</code> должен вернуться к истине.
testString: 'assert(happy(31), "<code>happy(31)</code> should return true.");'
- text: '<code>happy(32)</code> должен возвращать true :.'
testString: 'assert(happy(32), "<code>happy(32)</code> should return true:.");'
- text: <code>happy(33)</code> должен вернуть ложь.
testString: 'assert(!happy(33), "<code>happy(33)</code> should return false.");'
- text: <code>happy</code> is a function.
testString: assert(typeof happy === 'function');
- text: <code>happy(1)</code> should return a boolean.
testString: assert(typeof happy(1) === 'boolean');
- text: <code>happy(1)</code> should return true.
testString: assert(happy(1));
- text: <code>happy(2)</code> should return false.
testString: assert(!happy(2));
- text: <code>happy(7)</code> should return true.
testString: assert(happy(7));
- text: <code>happy(10)</code> should return true.
testString: assert(happy(10));
- text: <code>happy(13)</code> should return true.
testString: assert(happy(13));
- text: <code>happy(19)</code> should return true.
testString: assert(happy(19));
- text: <code>happy(23)</code> should return true.
testString: assert(happy(23));
- text: <code>happy(28)</code> should return true.
testString: assert(happy(28));
- text: <code>happy(31)</code> should return true.
testString: assert(happy(31));
- text: <code>happy(32)</code> should return true:.
testString: assert(happy(32));
- text: <code>happy(33)</code> should return false.
testString: assert(!happy(33));
```
@@ -55,7 +58,7 @@ tests:
<div id='js-seed'>
```js
function happy (number) {
function happy(number) {
// Good luck!
}
@@ -63,14 +66,29 @@ function happy (number) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function happy (number) {
let m;
let digit;
const cycle = [];
while (number !== 1 && cycle[number] !== true) {
cycle[number] = true;
m = 0;
while (number > 0) {
digit = number % 10;
m += Math.pow(digit, 2);
number = (number - digit) / 10;
}
number = m;
}
return (number === 1);
}
```
</section>

View File

@@ -2,15 +2,19 @@
title: Harshad or Niven series
id: 595668ca4cfe1af2fb9818d4
challengeType: 5
videoUrl: ''
forumTopicId: 302281
localeTitle: Серия Harshad или Niven
---
## Description
<section id="description"><p> Номера <a href="http://mathworld.wolfram.com/HarshadNumber.html" title="ссылка: http://mathworld.wolfram.com/HarshadNumber.html">Harshad</a> или Niven представляют собой целые положительные числа ≥ 1, которые делятся на сумму их цифр. </p><p> Например, 42 является <a href="http://rosettacode.org/wiki/oeis:A005349" title="OEIS: A005349">числом Харшада,</a> поскольку 42 делится на (4 + 2) без остатка. </p> Предположим, что ряд определяется как числа в порядке возрастания. Задача: <p> Реализуйте функцию для генерации последовательных членов последовательности Harshad. </p><p> Используйте его, чтобы перечислить первые двадцать членов последовательности и перечислите первое число Harshad, превышающее 1000. </p></section>
<section id='description'>
<p> Номера <a href="http://mathworld.wolfram.com/HarshadNumber.html" title="ссылка: http://mathworld.wolfram.com/HarshadNumber.html">Harshad</a> или Niven представляют собой целые положительные числа ≥ 1, которые делятся на сумму их цифр. </p><p> Например, 42 является <a href="http://rosettacode.org/wiki/oeis:A005349" title="OEIS: A005349">числом Харшада,</a> поскольку 42 делится на (4 + 2) без остатка. </p> Предположим, что ряд определяется как числа в порядке возрастания. Задача: <p> Реализуйте функцию для генерации последовательных членов последовательности Harshad. </p><p> Используйте его, чтобы перечислить первые двадцать членов последовательности и перечислите первое число Harshad, превышающее 1000. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function to generate successive members of the Harshad sequence.
Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000.
</section>
## Tests
@@ -18,10 +22,10 @@ localeTitle: Серия Harshad или Niven
```yml
tests:
- text: <code>isHarshadOrNiven</code> - это функция.
testString: 'assert(typeof isHarshadOrNiven === "function", "<code>isHarshadOrNiven</code> is a function.");'
- text: '<code>isHarshadOrNiven()</code> должен возвращать <code>{&quot;firstTwenty&quot;: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],&quot;firstOver1000&quot;: 1002}</code>'
testString: 'assert.deepEqual(isHarshadOrNiven(), res, "<code>isHarshadOrNiven()</code> should return <code>{"firstTwenty": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],"firstOver1000": 1002}</code>");'
- text: <code>isHarshadOrNiven</code> is a function.
testString: assert(typeof isHarshadOrNiven === 'function');
- text: '<code>isHarshadOrNiven()</code> should return <code>{"firstTwenty": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],"firstOver1000": 1002}</code>'
testString: assert.deepEqual(isHarshadOrNiven(), res);
```
@@ -33,7 +37,7 @@ tests:
<div id='js-seed'>
```js
function isHarshadOrNiven () {
function isHarshadOrNiven() {
const res = {
firstTwenty: [],
firstOver1000: undefined
@@ -47,12 +51,15 @@ function isHarshadOrNiven () {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const res = {
firstTwenty: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],
firstOver1000: 1002
};
```
</div>
@@ -63,6 +70,39 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function isHarshadOrNiven() {
const res = {
firstTwenty: [],
firstOver1000: undefined
};
function isHarshad(n) {
let s = 0;
const nStr = n.toString();
for (let i = 0; i < nStr.length; ++i) {
s += parseInt(nStr.charAt(i), 10);
}
return n % s === 0;
}
let count = 0;
const harshads = [];
for (let n = 1; count < 20; ++n) {
if (isHarshad(n)) {
count++;
harshads.push(n);
}
}
res.firstTwenty = harshads;
let h = 1000;
while (!isHarshad(++h));
res.firstOver1000 = h;
return res;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Hash from two arrays
id: 595671d4d2cdc305f0d5b36f
challengeType: 5
videoUrl: ''
forumTopicId: 302283
localeTitle: Хэш из двух массивов
---
## Description
<section id="description"> Задача: <p> Используя два массива равной длины, создайте объект Hash, в котором элементы из одного массива (ключи) связаны с элементами другого (значения) </p> Связанная задача: <a href="http://rosettacode.org/wiki/Associative arrays/Creation" title="Ассоциативные массивы / Создание">Ассоциативные массивы / Создание</a> </section>
<section id='description'>
Задача: <p> Используя два массива равной длины, создайте объект Hash, в котором элементы из одного массива (ключи) связаны с элементами другого (значения) </p> Связанная задача: <a href="http://rosettacode.org/wiki/Associative arrays/Creation" title="Ассоциативные массивы / Создание">Ассоциативные массивы / Создание</a>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Хэш из двух массивов
```yml
tests:
- text: <code>arrToObj</code> - функция.
testString: 'assert(typeof arrToObj === "function", "<code>arrToObj</code> is a function.");'
- text: '<code>arrToObj([1, 2, 3, 4, 5], [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;])</code> должны возвращать <code>{ 1: &quot;a&quot;, 2: &quot;b&quot;, 3: &quot;c&quot;, 4: &quot;d&quot;, 5: &quot;e&quot; }</code>'
testString: 'assert.deepEqual(arrToObj(...testCases[0]), res[0], "<code>arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }</code>");'
- text: '<code>arrToObj([1, 2, 3, 4, 5], [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;])</code> должны возвращать <code>{ 1: &quot;a&quot;, 2: &quot;b&quot;, 3: &quot;c&quot;, 4: &quot;d&quot;, 5: undefined }</code>'
testString: 'assert.deepEqual(arrToObj(...testCases[1]), res[1], "<code>arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"])</code> should return <code>{ 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }</code>");'
- text: '<code>arrToObj([1, 2, 3], [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;])</code> должны возвращать <code>{ 1: &quot;a&quot;, 2: &quot;b&quot;, 3: &quot;c&quot; }</code>'
testString: 'assert.deepEqual(arrToObj(...testCases[2]), res[2], "<code>arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c" }</code>");'
- text: '<code>arrToObj([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;], [1, 2, 3, 4, 5])</code> должны возвращать <code>{ &quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3 , &quot;d&quot;: 4, &quot;e&quot;: 5 }</code>'
testString: 'assert.deepEqual(arrToObj(...testCases[3]), res[3], "<code>arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }</code>");'
- text: '<code>arrToObj([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;], [1, 2, 3, 4])</code> должны возвращать <code>{ &quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3 , &quot;d&quot;: 4, &quot;e&quot;: undefined }</code>'
testString: 'assert.deepEqual(arrToObj(...testCases[4]), res[4], "<code>arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4])</code> should return <code>{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }</code>");'
- text: '<code>arrToObj([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], [1, 2, 3, 4, 5])</code> должны возвращать <code>{ &quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3 }</code>'
testString: 'assert.deepEqual(arrToObj(...testCases[5]), res[5], "<code>arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 }</code>");'
- text: <code>arrToObj</code> is a function.
testString: assert(typeof arrToObj === 'function');
- text: '<code>arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }</code>'
testString: assert.deepEqual(arrToObj(...testCases[0]), res[0]);
- text: '<code>arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"])</code> should return <code>{ 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }</code>'
testString: assert.deepEqual(arrToObj(...testCases[1]), res[1]);
- text: '<code>arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c" }</code>'
testString: assert.deepEqual(arrToObj(...testCases[2]), res[2]);
- text: '<code>arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }</code>'
testString: assert.deepEqual(arrToObj(...testCases[3]), res[3]);
- text: '<code>arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4])</code> should return <code>{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }</code>'
testString: assert.deepEqual(arrToObj(...testCases[4]), res[4]);
- text: '<code>arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 }</code>'
testString: assert.deepEqual(arrToObj(...testCases[5]), res[5]);
```
@@ -52,12 +55,28 @@ function arrToObj (keys, vals) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [
[[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd', 'e']],
[[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd']],
[[1, 2, 3], ['a', 'b', 'c', 'd', 'e']],
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]],
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4]],
[['a', 'b', 'c'], [1, 2, 3, 4, 5]]
];
const res = [
{ 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e' },
{ 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: undefined },
{ 1: 'a', 2: 'b', 3: 'c' },
{ a: 1, b: 2, c: 3, d: 4, e: 5 },
{ a: 1, b: 2, c: 3, d: 4, e: undefined },
{ a: 1, b: 2, c: 3 }
];
```
</div>
@@ -68,6 +87,12 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function arrToObj (keys, vals) {
return keys.reduce((map, key, index) => {
map[key] = vals[index];
return map;
}, {});
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Hash join
id: 5956795bc9e2c415eb244de1
challengeType: 5
videoUrl: ''
forumTopicId: 302284
localeTitle: Присоединиться
---
## Description
<section id="description"><p> <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join" title="wp: Join_ (SQL) #Inner_join">Внутреннее соединение</a> - это операция, которая объединяет две таблицы данных в одну таблицу на основе совпадающих значений столбцов. Простейшим способом реализации этой операции является алгоритм <a href="https://en.wikipedia.org/wiki/Nested loop join" title="wp: Соединение вложенного цикла">объединения вложенных циклов</a> , но более масштабируемой альтернативой является алгоритм <a href="https://en.wikipedia.org/wiki/hash join" title="wp: hash join">хеш-соединения</a> . </p><p> Внедрите алгоритм «хеш-соединения» и продемонстрируйте, что он проходит тестовый сценарий, указанный ниже. </p><p> Вы должны представлять таблицы как структуры данных, которые кажутся естественными на вашем языке программирования. </p><p> Алгоритм «хеш-соединения» состоит из двух шагов: </p> Хэш-фаза. Создайте <a href="https://en.wikipedia.org/wiki/Multimap" title="wp: Multimap">мультимап</a> из одной из двух таблиц, сопоставляя их со всеми значениями столбца объединения со всеми строками, которые его содержат. Мультимап должен поддерживать хэш-ориентированный поиск, который масштабируется лучше, чем простой линейный поиск, потому что в этом весь смысл этого алгоритма. В идеале мы должны создать мультимап для меньшей таблицы, таким образом минимизируя время его создания и размер памяти. Фаза присоединения. Сканируйте другую таблицу и найдите соответствующие строки, просмотрев созданный ранее мультимап. <p> В псевдокоде алгоритм может быть выражен следующим образом: </p><pre> пусть A = первая входная таблица (или, в идеале, большая)
<section id='description'>
<p> <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join" title="wp: Join_ (SQL) #Inner_join">Внутреннее соединение</a> - это операция, которая объединяет две таблицы данных в одну таблицу на основе совпадающих значений столбцов. Простейшим способом реализации этой операции является алгоритм <a href="https://en.wikipedia.org/wiki/Nested loop join" title="wp: Соединение вложенного цикла">объединения вложенных циклов</a> , но более масштабируемой альтернативой является алгоритм <a href="https://en.wikipedia.org/wiki/hash join" title="wp: hash join">хеш-соединения</a> . </p><p> Внедрите алгоритм «хеш-соединения» и продемонстрируйте, что он проходит тестовый сценарий, указанный ниже. </p><p> Вы должны представлять таблицы как структуры данных, которые кажутся естественными на вашем языке программирования. </p><p> Алгоритм «хеш-соединения» состоит из двух шагов: </p> Хэш-фаза. Создайте <a href="https://en.wikipedia.org/wiki/Multimap" title="wp: Multimap">мультимап</a> из одной из двух таблиц, сопоставляя их со всеми значениями столбца объединения со всеми строками, которые его содержат. Мультимап должен поддерживать хэш-ориентированный поиск, который масштабируется лучше, чем простой линейный поиск, потому что в этом весь смысл этого алгоритма. В идеале мы должны создать мультимап для меньшей таблицы, таким образом минимизируя время его создания и размер памяти. Фаза присоединения. Сканируйте другую таблицу и найдите соответствующие строки, просмотрев созданный ранее мультимап. <p> В псевдокоде алгоритм может быть выражен следующим образом: </p><pre> пусть A = первая входная таблица (или, в идеале, большая)
пусть B = вторая входная таблица (или, в идеале, меньшая)
пусть j <sub>A</sub> = идентификатор столбца соединения таблицы A
пусть j <sub>B</sub> = идентификатор столбца соединения таблицы B
@@ -19,10 +20,141 @@ localeTitle: Присоединиться
для каждой строки b в мультимадре M <sub>B</sub> под ключом a (j <sub>A</sub> ):
пусть c = конкатенация строки a и строки b
поместите строку c в таблицу C <p></p>
</pre> Прецедент <p> вход </p><table><tbody><tr><td style="padding: 4px; margin: 5px;"><table style="border:none; border-collapse:collapse;"><tbody><tr><td style="border:none"> <i>A =</i> </td><td style="border:none"><table><tbody><tr><th style="padding: 4px; margin: 5px;"> Возраст </th><th style="padding: 4px; margin: 5px;"> имя </th></tr><tr><td style="padding: 4px; margin: 5px;"> 27 </td><td style="padding: 4px; margin: 5px;"> Иона </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Алан </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> слава </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Popeye </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> Алан </td></tr></tbody></table></td><td style="border:none; padding-left:1.5em;" rowspan="2"></td><td style="border:none"> <i>B =</i> </td><td style="border:none"><table><tbody><tr><th style="padding: 4px; margin: 5px;"> символ </th><th style="padding: 4px; margin: 5px;"> Немезида </th></tr><tr><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Киты </td></tr><tr><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Пауки </td></tr><tr><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> привидения </td></tr><tr><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Zombies </td></tr><tr><td style="padding: 4px; margin: 5px;"> слава </td><td style="padding: 4px; margin: 5px;"> Buffy </td></tr></tbody></table></td></tr><tr><td style="border:none"> <i>j <sub>A</sub> =</i> </td><td style="border:none"> <i><code>Name</code> (т.е. столбец 1)</i> </td><td style="border:none"> <i>j <sub>B</sub> =</i> </td><td style="border:none"> <i><code>Character</code> (т.е. столбец 0)</i> </td></tr></tbody></table></td><td style="padding: 4px; margin: 5px;"></td></tr></tbody></table><p> Вывод </p><table><tbody><tr><th style="padding: 4px; margin: 5px;"> A.Age </th><th style="padding: 4px; margin: 5px;"> Имя </th><th style="padding: 4px; margin: 5px;"> B.Character </th><th style="padding: 4px; margin: 5px;"> B.Nemesis </th></tr><tr><td style="padding: 4px; margin: 5px;"> 27 </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Киты </td></tr><tr><td style="padding: 4px; margin: 5px;"> 27 </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Пауки </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> привидения </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Zombies </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> слава </td><td style="padding: 4px; margin: 5px;"> слава </td><td style="padding: 4px; margin: 5px;"> Buffy </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> привидения </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Zombies </td></tr></tbody></table><p></p><p></p><p> Порядок строк в выходной таблице не имеет значения. </p><p> Если вы используете численные индексированные массивы для представления строк таблицы (вместо обращения к столбцам по имени), вы можете представить выходные строки в форме <code style="white-space:nowrap">[[27, &quot;Jonah&quot;], [&quot;Jonah&quot;, &quot;Whales&quot;]]</code> , </p><hr></section>
</pre> Прецедент <p> вход </p><table><tbody><tr><td style="padding: 4px; margin: 5px;"><table style="border:none; border-collapse:collapse;"><tbody><tr><td style="border:none"> <i>A =</i> </td><td style="border:none"><table><tbody><tr><th style="padding: 4px; margin: 5px;"> Возраст </th><th style="padding: 4px; margin: 5px;"> имя </th></tr><tr><td style="padding: 4px; margin: 5px;"> 27 </td><td style="padding: 4px; margin: 5px;"> Иона </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Алан </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> слава </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Popeye </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> Алан </td></tr></tbody></table></td><td style="border:none; padding-left:1.5em;" rowspan="2"></td><td style="border:none"> <i>B =</i> </td><td style="border:none"><table><tbody><tr><th style="padding: 4px; margin: 5px;"> символ </th><th style="padding: 4px; margin: 5px;"> Немезида </th></tr><tr><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Киты </td></tr><tr><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Пауки </td></tr><tr><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> привидения </td></tr><tr><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Zombies </td></tr><tr><td style="padding: 4px; margin: 5px;"> слава </td><td style="padding: 4px; margin: 5px;"> Buffy </td></tr></tbody></table></td></tr><tr><td style="border:none"> <i>j <sub>A</sub> =</i> </td><td style="border:none"> <i><code>Name</code> (т.е. столбец 1)</i> </td><td style="border:none"> <i>j <sub>B</sub> =</i> </td><td style="border:none"> <i><code>Character</code> (т.е. столбец 0)</i> </td></tr></tbody></table></td><td style="padding: 4px; margin: 5px;"></td></tr></tbody></table><p> Вывод </p><table><tbody><tr><th style="padding: 4px; margin: 5px;"> A.Age </th><th style="padding: 4px; margin: 5px;"> Имя </th><th style="padding: 4px; margin: 5px;"> B.Character </th><th style="padding: 4px; margin: 5px;"> B.Nemesis </th></tr><tr><td style="padding: 4px; margin: 5px;"> 27 </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Киты </td></tr><tr><td style="padding: 4px; margin: 5px;"> 27 </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Иона </td><td style="padding: 4px; margin: 5px;"> Пауки </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> привидения </td></tr><tr><td style="padding: 4px; margin: 5px;"> 18 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Zombies </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> слава </td><td style="padding: 4px; margin: 5px;"> слава </td><td style="padding: 4px; margin: 5px;"> Buffy </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> привидения </td></tr><tr><td style="padding: 4px; margin: 5px;"> 28 </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Алан </td><td style="padding: 4px; margin: 5px;"> Zombies </td></tr></tbody></table><p></p><p></p><p> Порядок строк в выходной таблице не имеет значения. </p><p> Если вы используете численные индексированные массивы для представления строк таблицы (вместо обращения к столбцам по имени), вы можете представить выходные строки в форме <code style="white-space:nowrap">[[27, &quot;Jonah&quot;], [&quot;Jonah&quot;, &quot;Whales&quot;]]</code> , </p><hr>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement the "hash join" algorithm as a function and demonstrate that it passes the test-case listed below. The function should accept two arrays of objects and return an array of combined objects.
<h4><strong>Input</strong></h4>
<table>
<tr>
<td style="padding: 4px; margin: 5px;">
<table style="border:none; border-collapse:collapse;">
<tr>
<td style="border:none"> <i>A =</i>
</td>
<td style="border:none">
<table>
<tr>
<th style="padding: 4px; margin: 5px;"> Age </th>
<th style="padding: 4px; margin: 5px;"> Name
</th></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 27 </td>
<td style="padding: 4px; margin: 5px;"> Jonah
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 18 </td>
<td style="padding: 4px; margin: 5px;"> Alan
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 28 </td>
<td style="padding: 4px; margin: 5px;"> Glory
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 18 </td>
<td style="padding: 4px; margin: 5px;"> Popeye
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 28 </td>
<td style="padding: 4px; margin: 5px;"> Alan
</td></tr></table>
</td>
<td style="border:none; padding-left:1.5em;" rowspan="2">
</td>
<td style="border:none"> <i>B =</i>
</td>
<td style="border:none">
<table>
<tr>
<th style="padding: 4px; margin: 5px;"> Character </th>
<th style="padding: 4px; margin: 5px;"> Nemesis
</th></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> Jonah </td>
<td style="padding: 4px; margin: 5px;"> Whales
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> Jonah </td>
<td style="padding: 4px; margin: 5px;"> Spiders
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Ghosts
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Zombies
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> Glory </td>
<td style="padding: 4px; margin: 5px;"> Buffy
</td></tr></table>
</td></tr>
<tr>
<td style="border:none"> <i>j<sub>A</sub> =</i>
</td>
<td style="border:none"> <i><code>Name</code> (i.e. column 1)</i>
</td>
<td style="border:none"> <i>j<sub>B</sub> =</i>
</td>
<td style="border:none"> <i><code>Character</code> (i.e. column 0)</i>
</td></tr></table>
</td>
<td style="padding: 4px; margin: 5px;">
</td></tr></table>
<h4><strong>Output</strong></h4>
<table>
<tr>
<th style="padding: 4px; margin: 5px;"> A_age </th>
<th style="padding: 4px; margin: 5px;"> A_name </th>
<th style="padding: 4px; margin: 5px;"> B_character </th>
<th style="padding: 4px; margin: 5px;"> B_nemesis
</th></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 27 </td>
<td style="padding: 4px; margin: 5px;"> Jonah </td>
<td style="padding: 4px; margin: 5px;"> Jonah </td>
<td style="padding: 4px; margin: 5px;"> Whales
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 27 </td>
<td style="padding: 4px; margin: 5px;"> Jonah </td>
<td style="padding: 4px; margin: 5px;"> Jonah </td>
<td style="padding: 4px; margin: 5px;"> Spiders
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 18 </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Ghosts
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 18 </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Zombies
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 28 </td>
<td style="padding: 4px; margin: 5px;"> Glory </td>
<td style="padding: 4px; margin: 5px;"> Glory </td>
<td style="padding: 4px; margin: 5px;"> Buffy
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 28 </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Ghosts
</td></tr>
<tr>
<td style="padding: 4px; margin: 5px;"> 28 </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Alan </td>
<td style="padding: 4px; margin: 5px;"> Zombies
</td></tr></table>
The order of the rows in the output table is not significant.
</section>
## Tests
@@ -30,10 +162,10 @@ localeTitle: Присоединиться
```yml
tests:
- text: <code>hashJoin</code> - это функция.
testString: 'assert(typeof hashJoin === "function", "<code>hashJoin</code> is a function.");'
- text: '<code>hashJoin([{ age: 27, name: &quot;Jonah&quot; }, { age: 18, name: &quot;Alan&quot; }, { age: 28, name: &quot;Glory&quot; }, { age: 18, name: &quot;Popeye&quot; }, { age: 28, name: &quot;Alan&quot; }], [{ character: &quot;Jonah&quot;, nemesis: &quot;Whales&quot; }, { character: &quot;Jonah&quot;, nemesis: &quot;Spiders&quot; }, { character: &quot;Alan&quot;, nemesis: &quot;Ghosts&quot; }, { character:&quot;Alan&quot;, nemesis: &quot;Zombies&quot; }, { character: &quot;Glory&quot;, nemesis: &quot;Buffy&quot; }, { character: &quot;Bob&quot;, nemesis: &quot;foo&quot; }])</code> должен возвращать <code>[{&quot;A_age&quot;: 27,&quot;A_name&quot;: &quot;Jonah&quot;, &quot;B_character&quot;: &quot;Jonah&quot;, &quot;B_nemesis&quot;: &quot;Whales&quot;}, {&quot;A_age&quot;: 27,&quot;A_name&quot;: &quot;Jonah&quot;, &quot;B_character&quot;: &quot;Jonah&quot;, &quot;B_nemesis&quot;: &quot;Spiders&quot;}, {&quot;A_age&quot;: 18,&quot;A_name&quot;: &quot;Alan&quot;, &quot;B_character&quot;: &quot;Alan&quot;, &quot;B_nemesis&quot;: &quot;Ghosts&quot;}, {&quot;A_age&quot;: 18,&quot;A_name&quot;: &quot;Alan&quot;, &quot;B_character&quot;: &quot;Alan&quot;, &quot;B_nemesis&quot;: &quot;Zombies&quot;}, {&quot;A_age&quot;: 28,&quot;A_name&quot;: &quot;Glory&quot;, &quot;B_character&quot;: &quot;Glory&quot;, &quot;B_nemesis&quot;: &quot;Buffy&quot;}, {&quot;A_age&quot;: 28,&quot;A_name&quot;: &quot;Alan&quot;, &quot;B_character&quot;: &quot;Alan&quot;, &quot;B_nemesis&quot;: &quot;Ghosts&quot;}, {&quot;A_age&quot;: 28,&quot;A_name&quot;: &quot;Alan&quot;, &quot;B_character&quot;: &quot;Alan&quot;, &quot;B_nemesis&quot;: &quot;Zombies&quot;}]</code>'
testString: 'assert.deepEqual(hashJoin(hash1, hash2), res, "<code>hashJoin([{ age: 27, name: "Jonah" }, { age: 18, name: "Alan" }, { age: 28, name: "Glory" }, { age: 18, name: "Popeye" }, { age: 28, name: "Alan" }], [{ character: "Jonah", nemesis: "Whales" }, { character: "Jonah", nemesis: "Spiders" }, { character: "Alan", nemesis: "Ghosts" }, { character:"Alan", nemesis: "Zombies" }, { character: "Glory", nemesis: "Buffy" }, { character: "Bob", nemesis: "foo" }])</code> should return <code>[{"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Whales"}, {"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Spiders"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}, {"A_age": 28,"A_name": "Glory", "B_character": "Glory", "B_nemesis": "Buffy"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}]</code>");'
- text: <code>hashJoin</code> is a function.
testString: assert(typeof hashJoin === 'function');
- text: '<code>hashJoin([{ age: 27, name: "Jonah" }, { age: 18, name: "Alan" }, { age: 28, name: "Glory" }, { age: 18, name: "Popeye" }, { age: 28, name: "Alan" }], [{ character: "Jonah", nemesis: "Whales" }, { character: "Jonah", nemesis: "Spiders" }, { character: "Alan", nemesis: "Ghosts" }, { character:"Alan", nemesis: "Zombies" }, { character: "Glory", nemesis: "Buffy" }, { character: "Bob", nemesis: "foo" }])</code> should return <code>[{"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Whales"}, {"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Spiders"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}, {"A_age": 28,"A_name": "Glory", "B_character": "Glory", "B_nemesis": "Buffy"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}]</code>'
testString: assert.deepEqual(hashJoin(hash1, hash2), res);
```
@@ -45,7 +177,7 @@ tests:
<div id='js-seed'>
```js
function hashJoin (hash1, hash2) {
function hashJoin(hash1, hash2) {
// Good luck!
return [];
}
@@ -54,12 +186,40 @@ function hashJoin (hash1, hash2) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const hash1 = [
{ age: 27, name: 'Jonah' },
{ age: 18, name: 'Alan' },
{ age: 28, name: 'Glory' },
{ age: 18, name: 'Popeye' },
{ age: 28, name: 'Alan' }
];
const hash2 = [
{ character: 'Jonah', nemesis: 'Whales' },
{ character: 'Jonah', nemesis: 'Spiders' },
{ character: 'Alan', nemesis: 'Ghosts' },
{ character: 'Alan', nemesis: 'Zombies' },
{ character: 'Glory', nemesis: 'Buffy' },
{ character: 'Bob', nemesis: 'foo' }
];
const res = [
{ A_age: 27, A_name: 'Jonah', B_character: 'Jonah', B_nemesis: 'Whales' },
{ A_age: 27, A_name: 'Jonah', B_character: 'Jonah', B_nemesis: 'Spiders' },
{ A_age: 18, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Ghosts' },
{ A_age: 18, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Zombies' },
{ A_age: 28, A_name: 'Glory', B_character: 'Glory', B_nemesis: 'Buffy' },
{ A_age: 28, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Ghosts' },
{ A_age: 28, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Zombies' }
];
const bench1 = [{ name: 'u2v7v', num: 1 }, { name: 'n53c8', num: 10 }, { name: 'oysce', num: 9 }, { name: '0mto2s', num: 1 }, { name: 'vkh5id', num: 4 }, { name: '5od0cf', num: 8 }, { name: 'uuulue', num: 10 }, { name: '3rgsbi', num: 9 }, { name: 'kccv35r', num: 4 }, { name: '80un74', num: 9 }, { name: 'h4pp3', num: 6 }, { name: '51bit', num: 7 }, { name: 'j9ndf', num: 8 }, { name: 'vf3u1', num: 10 }, { name: 'g0bw0om', num: 10 }, { name: 'j031x', num: 7 }, { name: 'ij3asc', num: 9 }, { name: 'byv83y', num: 8 }, { name: 'bjzp4k', num: 4 }, { name: 'f3kbnm', num: 10 }];
const bench2 = [{ friend: 'o8b', num: 8 }, { friend: 'ye', num: 2 }, { friend: '32i', num: 5 }, { friend: 'uz', num: 3 }, { friend: 'a5k', num: 4 }, { friend: 'uad', num: 7 }, { friend: '3w5', num: 10 }, { friend: 'vw', num: 10 }, { friend: 'ah', num: 4 }, { friend: 'qv', num: 7 }, { friend: 'ozv', num: 2 }, { friend: '9ri', num: 10 }, { friend: '7nu', num: 4 }, { friend: 'w3', num: 9 }, { friend: 'tgp', num: 8 }, { friend: 'ibs', num: 1 }, { friend: 'ss7', num: 6 }, { friend: 'g44', num: 9 }, { friend: 'tab', num: 9 }, { friend: 'zem', num: 10 }];
```
</div>
@@ -70,6 +230,37 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function hashJoin(hash1, hash2) {
const hJoin = (tblA, tblB, strJoin) => {
const [jA, jB] = strJoin.split('=');
const M = tblB.reduce((a, x) => {
const id = x[jB];
return (
a[id] ? a[id].push(x) : (a[id] = [x]),
a
);
}, {});
return tblA.reduce((a, x) => {
const match = M[x[jA]];
return match ? (
a.concat(match.map(row => dictConcat(x, row)))
) : a;
}, []);
};
const dictConcat = (dctA, dctB) => {
const ok = Object.keys;
return ok(dctB).reduce(
(a, k) => (a[`B_${k}`] = dctB[k]) && a,
ok(dctA).reduce(
(a, k) => (a[`A_${k}`] = dctA[k]) && a, {}
)
);
};
return hJoin(hash1, hash2, 'name=character');
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Heronian triangles
id: 595b98f8b5a2245e243aa831
challengeType: 5
videoUrl: ''
forumTopicId: 302285
localeTitle: Херонические треугольники
---
## Description
<section id="description"><p> <a href="https://en.wikipedia.org/wiki/Heron&#x27;s formula" title="wp: формула Герона">Формула Героя</a> для области треугольника с учетом длины трех ее сторон <big>a,</big> <big>b</big> и <big>c</big> определяется следующим образом: </p><p> <big>$$ A = \ sqrt {s (sa) (sb) (sc)}, $$</big> </p><p> где <big>s</big> - половина периметра треугольника; то есть, </p><p> <big>$$ з = \ гидроразрыва {а + B + C} {2} $$.</big> </p><p> <a href="http://www.had2know.com/academics/heronian-triangles-generator-calculator.html" title="ссылка: http://www.had2know.com/academics/heronian-triangles-generator-calculator.html">Херонические треугольники</a> - это треугольники, стороны и области которых являются целыми числами. </p><p> Примером может служить треугольник со сторонами 3, 4, 5, площадь которых равна 6 (а по периметру - 12). </p><p> Заметим, что любой треугольник, чьи стороны все целые кратные 3, 4, 5; такие как 6, 8, 10, также будут иероническим треугольником. </p><p> Определите примитивный херонийский треугольник как хернийский треугольник, где наибольший общий делитель </p><p> всех трех сторон 1 (единство). </p><p> Это исключает, например, треугольник 6, 8, 10. </p> Задача: <p> Реализуйте функцию, основанную на формуле Героя, которая возвращает первые <code>n <sub>th</sub></code> упорядоченные треугольники в массиве массивов. </p></section>
<section id='description'>
<p> <a href="https://en.wikipedia.org/wiki/Heron&#x27;s formula" title="wp: формула Герона">Формула Героя</a> для области треугольника с учетом длины трех ее сторон <big>a,</big> <big>b</big> и <big>c</big> определяется следующим образом: </p><p> <big>$$ A = \ sqrt {s (sa) (sb) (sc)}, $$</big> </p><p> где <big>s</big> - половина периметра треугольника; то есть, </p><p> <big>$$ з = \ гидроразрыва {а + B + C} {2} $$.</big> </p><p> <a href="http://www.had2know.com/academics/heronian-triangles-generator-calculator.html" title="ссылка: http://www.had2know.com/academics/heronian-triangles-generator-calculator.html">Херонические треугольники</a> - это треугольники, стороны и области которых являются целыми числами. </p><p> Примером может служить треугольник со сторонами 3, 4, 5, площадь которых равна 6 (а по периметру - 12). </p><p> Заметим, что любой треугольник, чьи стороны все целые кратные 3, 4, 5; такие как 6, 8, 10, также будут иероническим треугольником. </p><p> Определите примитивный херонийский треугольник как хернийский треугольник, где наибольший общий делитель </p><p> всех трех сторон 1 (единство). </p><p> Это исключает, например, треугольник 6, 8, 10. </p> Задача: <p> Реализуйте функцию, основанную на формуле Героя, которая возвращает первые <code>n <sub>th</sub></code> упорядоченные треугольники в массиве массивов. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement a function based on Hero's formula that returns the first <code>n<sub>th</sub></code> ordered triangles in an array of arrays.
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Херонические треугольники
```yml
tests:
- text: <code>heronianTriangle</code> - это функция.
testString: 'assert(typeof heronianTriangle === "function", "<code>heronianTriangle</code> is a function.");'
- text: '<code>heronianTriangle()</code> должен возвращать <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]</code>'
testString: 'assert.deepEqual(heronianTriangle(testCases[0]), res[0], "<code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]</code>");'
- text: '<code>heronianTriangle()</code> должен возвращать <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],</code>'
testString: 'assert.deepEqual(heronianTriangle(testCases[1]), res[1], "<code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],</code>");'
- text: '<code>heronianTriangle()</code> должен возвращать <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],</code>'
testString: 'assert.deepEqual(heronianTriangle(testCases[2]), res[2], "<code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],</code>");'
- text: '<code>heronianTriangle()</code> должен возвращать <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]</code>'
testString: 'assert.deepEqual(heronianTriangle(testCases[3]), res[3], "<code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]</code>");'
- text: <code>heronianTriangle</code> is a function.
testString: assert(typeof heronianTriangle === 'function');
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]</code>
testString: assert.deepEqual(heronianTriangle(testCases[0]), res[0]);
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],</code>
testString: assert.deepEqual(heronianTriangle(testCases[1]), res[1]);
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],</code>
testString: assert.deepEqual(heronianTriangle(testCases[2]), res[2]);
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]</code>
testString: assert.deepEqual(heronianTriangle(testCases[3]), res[3]);
```
@@ -40,7 +43,7 @@ tests:
```js
// noprotect
function heronianTriangle (n) {
function heronianTriangle(n) {
// Good luck!
return [];
@@ -50,12 +53,19 @@ function heronianTriangle (n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCases = [10, 15, 20, 25];
const res = [
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]],
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37], [16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]
];
```
</div>
@@ -66,6 +76,67 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// noprotect
function heronianTriangle(n) {
const list = [];
const result = [];
let j = 0;
for (let c = 1; c <= 200; c++) {
for (let b = 1; b <= c; b++) {
for (let a = 1; a <= b; a++) {
if (gcd(gcd(a, b), c) === 1 && isHeron(heronArea(a, b, c))) {
list[j++] = new Array(a, b, c, heronArea(a, b, c));
}
}
}
}
sort(list);
for (let i = 0; i < n; i++) {
result[i] = [list[i][0], list[i][1], list[i][2]];
}
return result;
function heronArea(a, b, c) {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
function isHeron(h) { return h % 1 === 0 && h > 0; }
function gcd(a, b) {
let leftover = 1;
let dividend = a > b ? a : b;
let divisor = a > b ? b : a;
while (leftover !== 0) {
leftover = dividend % divisor;
if (leftover > 0) {
dividend = divisor;
divisor = leftover;
}
}
return divisor;
}
function sort(arg) {
let swapped = true;
let temp = [];
while (swapped) {
swapped = false;
for (let i = 1; i < arg.length; i++) {
if (arg[i][4] < arg[i - 1][4] || arg[i][4] === arg[i - 1][4] && arg[i][3] < arg[i - 1][3]) {
temp = arg[i];
arg[i] = arg[i - 1];
arg[i - 1] = temp;
swapped = true;
}
}
}
}
}
```
</section>

View File

@@ -2,15 +2,28 @@
title: Hofstadter Figure-Figure sequences
id: 59622f89e4e137560018a40e
challengeType: 5
videoUrl: ''
forumTopicId: 302286
localeTitle: Последовательности Рисунка Hofstadter
---
## Description
<section id="description"><p> Эти две последовательности положительных целых чисел определяются как: </p><p> <big>$$ R (1) = 1 \; \ S (1) = 2 \\ R (n) = R (n-1) + S (n-1), \ quad n&gt; 1. $$</big> </p><p> Последовательность <big>$ S (n) $</big> дополнительно определяется как последовательность положительных целых чисел, не присутствующих в <big>$ R (n) $</big> . </p><p> Последовательность <big>$ R $</big> начинается: </p><p> 1, 3, 7, 12, 18, ... </p><p> Последовательность <big>$ S $</big> начинается: </p><p> 2, 4, 5, 6, 8, ... </p> Задача: создать две функции с именем ffr и ffs, которые при задании n возвращают R (n) или S (n) соответственно. (Обратите внимание, что R (1) = 1 и S (1) = 2, чтобы избежать ошибок, , Максимальное значение n не должно приниматься. Sloane <a href="http://oeis.org/A005228" title="ссылка: http://oeis.org/A005228">A005228</a> и <a href="http://oeis.org/A030124" title="ссылка: http://oeis.org/A030124">A030124</a> . <a href="http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html" title="ссылка: http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html">Wolfram MathWorld</a> Wikipedia: <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences" title="wp: Hofstadter_sequence # Hofstadter_Figure-Figure_sequences">последовательности Hofstadter Figure-Figure</a> . </section>
<section id='description'>
<p> Эти две последовательности положительных целых чисел определяются как: </p><p> <big>$$ R (1) = 1 \; \ S (1) = 2 \\ R (n) = R (n-1) + S (n-1), \ quad n&gt; 1. $$</big> </p><p> Последовательность <big>$ S (n) $</big> дополнительно определяется как последовательность положительных целых чисел, не присутствующих в <big>$ R (n) $</big> . </p><p> Последовательность <big>$ R $</big> начинается: </p><p> 1, 3, 7, 12, 18, ... </p><p> Последовательность <big>$ S $</big> начинается: </p><p> 2, 4, 5, 6, 8, ... </p> Задача: создать две функции с именем ffr и ffs, которые при задании n возвращают R (n) или S (n) соответственно. (Обратите внимание, что R (1) = 1 и S (1) = 2, чтобы избежать ошибок, , Максимальное значение n не должно приниматься. Sloane <a href="http://oeis.org/A005228" title="ссылка: http://oeis.org/A005228">A005228</a> и <a href="http://oeis.org/A030124" title="ссылка: http://oeis.org/A030124">A030124</a> . <a href="http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html" title="ссылка: http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html">Wolfram MathWorld</a> Wikipedia: <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences" title="wp: Hofstadter_sequence # Hofstadter_Figure-Figure_sequences">последовательности Hofstadter Figure-Figure</a> .
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Create two functions named <code>ffr</code> and <code>ffs</code> that when given <code>n</code> return <code>R(n)</code> or <code>S(n)</code> respectively. (Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
No maximum value for <code>n</code> should be assumed.
<strong>References</strong>
<ul>
<li>
Sloane's <a href="https://oeis.org/A005228" target="_blank">A005228</a> and <a href="https://oeis.org/A030124" target="_blank">A030124</a>.
</li>
<li>
Wikipedia: <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences" title="wp: Hofstadter_sequence#Hofstadter_Figure-Figure_sequences" target="_blank">Hofstadter Figure-Figure sequences</a>.
</li>
</ul>
</section>
## Tests
@@ -18,30 +31,30 @@ localeTitle: Последовательности Рисунка Hofstadter
```yml
tests:
- text: <code>ffr</code> - функция.
testString: 'assert(typeof ffr === "function", "<code>ffr</code> is a function.");'
- text: <code>ffs</code> - функция.
testString: 'assert(typeof ffs === "function", "<code>ffs</code> is a function.");'
- text: <code>ffr</code> должно возвращать целое число.
testString: 'assert(Number.isInteger(ffr(1)), "<code>ffr</code> should return integer.");'
- text: <code>ffs</code> должно возвращать целое число.
testString: 'assert(Number.isInteger(ffs(1)), "<code>ffs</code> should return integer.");'
- text: <code>ffr()</code> должен возвращать <code>69</code>
testString: 'assert.equal(ffr(ffrParamRes[0][0]), ffrParamRes[0][1], "<code>ffr()</code> should return <code>69</code>");'
- text: <code>ffr()</code> должен вернуть <code>1509</code>
testString: 'assert.equal(ffr(ffrParamRes[1][0]), ffrParamRes[1][1], "<code>ffr()</code> should return <code>1509</code>");'
- text: <code>ffr()</code> должен возвращать <code>5764</code>
testString: 'assert.equal(ffr(ffrParamRes[2][0]), ffrParamRes[2][1], "<code>ffr()</code> should return <code>5764</code>");'
- text: <code>ffr()</code> должен вернуть <code>526334</code>
testString: 'assert.equal(ffr(ffrParamRes[3][0]), ffrParamRes[3][1], "<code>ffr()</code> should return <code>526334</code>");'
- text: <code>ffs()</code> должен возвращать <code>14</code>
testString: 'assert.equal(ffs(ffsParamRes[0][0]), ffsParamRes[0][1], "<code>ffs()</code> should return <code>14</code>");'
- text: <code>ffs()</code> должен вернуть <code>59</code>
testString: 'assert.equal(ffs(ffsParamRes[1][0]), ffsParamRes[1][1], "<code>ffs()</code> should return <code>59</code>");'
- text: <code>ffs()</code> должен возвращать <code>112</code>
testString: 'assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1], "<code>ffs()</code> should return <code>112</code>");'
- text: <code>ffs()</code> должен возвращать <code>1041</code>
testString: 'assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1], "<code>ffs()</code> should return <code>1041</code>");'
- text: <code>ffr</code> is a function.
testString: assert(typeof ffr === 'function');
- text: <code>ffs</code> is a function.
testString: assert(typeof ffs === 'function');
- text: <code>ffr</code> should return integer.
testString: assert(Number.isInteger(ffr(1)));
- text: <code>ffs</code> should return integer.
testString: assert(Number.isInteger(ffs(1)));
- text: <code>ffr()</code> should return <code>69</code>
testString: assert.equal(ffr(ffrParamRes[0][0]), ffrParamRes[0][1]);
- text: <code>ffr()</code> should return <code>1509</code>
testString: assert.equal(ffr(ffrParamRes[1][0]), ffrParamRes[1][1]);
- text: <code>ffr()</code> should return <code>5764</code>
testString: assert.equal(ffr(ffrParamRes[2][0]), ffrParamRes[2][1]);
- text: <code>ffr()</code> should return <code>526334</code>
testString: assert.equal(ffr(ffrParamRes[3][0]), ffrParamRes[3][1]);
- text: <code>ffs()</code> should return <code>14</code>
testString: assert.equal(ffs(ffsParamRes[0][0]), ffsParamRes[0][1]);
- text: <code>ffs()</code> should return <code>59</code>
testString: assert.equal(ffs(ffsParamRes[1][0]), ffsParamRes[1][1]);
- text: <code>ffs()</code> should return <code>112</code>
testString: assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1]);
- text: <code>ffs()</code> should return <code>1041</code>
testString: assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1]);
```
@@ -66,12 +79,13 @@ function ffs(n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const ffrParamRes = [[10, 69], [50, 1509], [100, 5764], [1000, 526334]];
const ffsParamRes = [[10, 14], [50, 59], [100, 112], [1000, 1041]];
```
</div>
@@ -82,6 +96,33 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// noprotect
const R = [null, 1];
const S = [null, 2];
function extendSequences (n) {
let current = Math.max(R[R.length - 1], S[S.length - 1]);
let i;
while (R.length <= n || S.length <= n) {
i = Math.min(R.length, S.length) - 1;
current += 1;
if (current === R[i] + S[i]) {
R.push(current);
} else {
S.push(current);
}
}
}
function ffr (n) {
extendSequences(n);
return R[n];
}
function ffs (n) {
extendSequences(n);
return S[n];
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Hofstadter Q sequence
id: 59637c4d89f6786115efd814
challengeType: 5
videoUrl: ''
forumTopicId: 302287
localeTitle: Последовательность Хофстадтера Q
---
## Description
<section id="description"><p> Последовательность <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence" title="wp: Hofstadter_sequence # Hofstadter_Q_sequence">Hofstadter Q</a> определяется как: </p><p> $ Q (1) = Q (2) = 1, \\ Q (n) = Q \ big (nQ (n-1) \ big) + Q \ big (nQ (n-2)), \ quad n&gt; 2. $ </p><p> Он определен как <a href="http://rosettacode.org/wiki/Fibonacci sequence" title="Последовательность Фибоначчи">последовательность Фибоначчи</a> , но в то время как следующий член в последовательности Фибоначчи представляет собой сумму двух предыдущих членов, в последовательности Q предыдущие два члена говорят вам, как далеко вернуться в последовательность Q, чтобы найти два числа суммировать, чтобы сделать следующий член последовательности. </p> Задача: Внедрить уравнение Хоффстадтера Q Sequence в JavaScript </section>
<section id='description'>
<p> Последовательность <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence" title="wp: Hofstadter_sequence # Hofstadter_Q_sequence">Hofstadter Q</a> определяется как: </p><p> $ Q (1) = Q (2) = 1, \\ Q (n) = Q \ big (nQ (n-1) \ big) + Q \ big (nQ (n-2)), \ quad n&gt; 2. $ </p><p> Он определен как <a href="http://rosettacode.org/wiki/Fibonacci sequence" title="Последовательность Фибоначчи">последовательность Фибоначчи</a> , но в то время как следующий член в последовательности Фибоначчи представляет собой сумму двух предыдущих членов, в последовательности Q предыдущие два члена говорят вам, как далеко вернуться в последовательность Q, чтобы найти два числа суммировать, чтобы сделать следующий член последовательности. </p> Задача: Внедрить уравнение Хоффстадтера Q Sequence в JavaScript
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Implement the Hofstadter Q Sequence equation as a function. The function should accept number, <code>n</code>, and return an integer.
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Последовательность Хофстадтера Q
```yml
tests:
- text: <code>hofstadterQ</code> является функцией.
testString: 'assert(typeof hofstadterQ === "function", "<code>hofstadterQ</code> is a function.");'
- text: <code>hofstadterQ()</code> должен возвращать <code>integer</code>
testString: 'assert(Number.isInteger(hofstadterQ(1000)), "<code>hofstadterQ()</code> should return <code>integer</code>");'
- text: <code>hofstadterQ(1000)</code> должен вернуть <code>502</code>
testString: 'assert.equal(hofstadterQ(testCase[0]), res[0], "<code>hofstadterQ(1000)</code> should return <code>502</code>");'
- text: <code>hofstadterQ(1500)</code> должен вернуть <code>755</code>
testString: 'assert.equal(hofstadterQ(testCase[1]), res[1], "<code>hofstadterQ(1500)</code> should return <code>755</code>");'
- text: <code>hofstadterQ(2000)</code> должен вернуть <code>1005</code>
testString: 'assert.equal(hofstadterQ(testCase[2]), res[2], "<code>hofstadterQ(2000)</code> should return <code>1005</code>");'
- text: <code>hofstadterQ(2500)</code> должен вернуть <code>1261</code>
testString: 'assert.equal(hofstadterQ(testCase[3]), res[3], "<code>hofstadterQ(2500)</code> should return <code>1261</code>");'
- text: <code>hofstadterQ</code> is a function.
testString: assert(typeof hofstadterQ === 'function');
- text: <code>hofstadterQ()</code> should return <code>integer</code>
testString: assert(Number.isInteger(hofstadterQ(1000)));
- text: <code>hofstadterQ(1000)</code> should return <code>502</code>
testString: assert.equal(hofstadterQ(testCase[0]), res[0]);
- text: <code>hofstadterQ(1500)</code> should return <code>755</code>
testString: assert.equal(hofstadterQ(testCase[1]), res[1]);
- text: <code>hofstadterQ(2000)</code> should return <code>1005</code>
testString: assert.equal(hofstadterQ(testCase[2]), res[2]);
- text: <code>hofstadterQ(2500)</code> should return <code>1261</code>
testString: assert.equal(hofstadterQ(testCase[3]), res[3]);
```
@@ -41,7 +44,7 @@ tests:
<div id='js-seed'>
```js
function hofstadterQ (n) {
function hofstadterQ(n) {
// Good luck!
return n;
}
@@ -50,12 +53,13 @@ function hofstadterQ (n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testCase = [1000, 1500, 2000, 2500];
const res = [502, 755, 1005, 1261];
```
</div>
@@ -66,6 +70,18 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function hofstadterQ (n) {
const memo = [1, 1, 1];
const Q = function (i) {
let result = memo[i];
if (typeof result !== 'number') {
result = Q(i - Q(i - 1)) + Q(i - Q(i - 2));
memo[i] = result;
}
return result;
};
return Q(n);
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: I before E except after C
id: 5a23c84252665b21eecc7eb0
challengeType: 5
videoUrl: ''
localeTitle: 'I до E, за исключением C'
forumTopicId: 302288
localeTitle: I до E, за исключением C
---
## Description
<section id="description"> Фраза <a href="https://en.wikipedia.org/wiki/I before E except after C">«I до E, за исключением C»</a> - широко известная мнемоника, которая должна помочь при написании английских слов. Используя предоставленные слова, проверьте, являются ли два подкласса фразы правдоподобными: <ol><li style="margin-bottom: 5px;"> <i>«Я до E, когда не предшествует C».</i> </li><li> <i>«E до I, когда предшествует C».</i> </li></ol> Если обе подфразы правдоподобны, то исходную фразу можно назвать правдоподобной. Напишите функцию, которая принимает слово и проверяет, соответствует ли это слово этому правилу. Функция должна возвращать true, если она соответствует правилу, в противном случае false. </section>
<section id='description'>
Фраза <a href="https://en.wikipedia.org/wiki/I before E except after C">«I до E, за исключением C»</a> - широко известная мнемоника, которая должна помочь при написании английских слов. Используя предоставленные слова, проверьте, являются ли два подкласса фразы правдоподобными: <ol><li style="margin-bottom: 5px;"> <i>«Я до E, когда не предшествует C».</i> </li><li> <i>«E до I, когда предшествует C».</i> </li></ol> Если обе подфразы правдоподобны, то исходную фразу можно назвать правдоподобной. Напишите функцию, которая принимает слово и проверяет, соответствует ли это слово этому правилу. Функция должна возвращать true, если она соответствует правилу, в противном случае false.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that accepts a word and check if the word follows this rule. The function should return true if the word follows the rule and false if it does not.
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: 'I до E, за исключением C'
```yml
tests:
- text: <code>IBeforeExceptC</code> должен быть функцией.
testString: 'assert(typeof IBeforeExceptC=="function","<code>IBeforeExceptC</code> should be a function.");'
- text: <code>IBeforeExceptC(&quot;receive&quot;)</code> должен возвращать логическое значение.
testString: 'assert(typeof IBeforeExceptC("receive")=="boolean","<code>IBeforeExceptC("receive")</code> should return a boolean.");'
- text: <code>IBeforeExceptC(&quot;receive&quot;)</code> должен возвращать <code>true</code> .
testString: 'assert.equal(IBeforeExceptC("receive"),true,"<code>IBeforeExceptC("receive")</code> should return <code>true</code>.");'
- text: <code>IBeforeExceptC(&quot;science&quot;)</code> должен возвращать <code>false</code> .
testString: 'assert.equal(IBeforeExceptC("science"),false,"<code>IBeforeExceptC("science")</code> should return <code>false</code>.");'
- text: <code>IBeforeExceptC(&quot;imperceivable&quot;)</code> должен возвращать <code>true</code> .
testString: 'assert.equal(IBeforeExceptC("imperceivable"),true,"<code>IBeforeExceptC("imperceivable")</code> should return <code>true</code>.");'
- text: <code>IBeforeExceptC(&quot;inconceivable&quot;)</code> должен возвращать <code>true</code> .
testString: 'assert.equal(IBeforeExceptC("inconceivable"),true,"<code>IBeforeExceptC("inconceivable")</code> should return <code>true</code>.");'
- text: <code>IBeforeExceptC(&quot;insufficient&quot;)</code> должен возвращать <code>false</code> .
testString: 'assert.equal(IBeforeExceptC("insufficient"),false,"<code>IBeforeExceptC("insufficient")</code> should return <code>false</code>.");'
- text: <code>IBeforeExceptC(&quot;omniscient&quot;)</code> должен возвращать <code>false</code> .
testString: 'assert.equal(IBeforeExceptC("omniscient"),false,"<code>IBeforeExceptC("omniscient")</code> should return <code>false</code>.");'
- text: <code>IBeforeExceptC</code> should be a function.
testString: assert(typeof IBeforeExceptC=='function');
- text: <code>IBeforeExceptC("receive")</code> should return a boolean.
testString: assert(typeof IBeforeExceptC("receive")=='boolean');
- text: <code>IBeforeExceptC("receive")</code> should return <code>true</code>.
testString: assert.equal(IBeforeExceptC("receive"),true);
- text: <code>IBeforeExceptC("science")</code> should return <code>false</code>.
testString: assert.equal(IBeforeExceptC("science"),false);
- text: <code>IBeforeExceptC("imperceivable")</code> should return <code>true</code>.
testString: assert.equal(IBeforeExceptC("imperceivable"),true);
- text: <code>IBeforeExceptC("inconceivable")</code> should return <code>true</code>.
testString: assert.equal(IBeforeExceptC("inconceivable"),true);
- text: <code>IBeforeExceptC("insufficient")</code> should return <code>false</code>.
testString: assert.equal(IBeforeExceptC("insufficient"),false);
- text: <code>IBeforeExceptC("omniscient")</code> should return <code>false</code>.
testString: assert.equal(IBeforeExceptC("omniscient"),false);
```
@@ -45,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function IBeforeExceptC (word) {
function IBeforeExceptC(word) {
// Good luck!
}
@@ -53,14 +56,20 @@ function IBeforeExceptC (word) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function IBeforeExceptC(word)
{
if(word.indexOf("c")==-1 && word.indexOf("ie")!=-1)
return true;
else if(word.indexOf("cei")!=-1)
return true;
return false;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: IBAN
id: 5a23c84252665b21eecc7eaf
challengeType: 5
videoUrl: ''
forumTopicId: 302289
localeTitle: Они были
---
## Description
<section id="description"> <a href="https://en.wikipedia.org/wiki/International_Bank_Account_Number">Международный номер банковского счета (IBAN)</a> является международно согласованным средством определения банковских счетов через национальные границы с уменьшенным риском распространения <a href="https://en.wikipedia.org/wiki/Transcription_error">ошибок транскрипции</a> . IBAN состоит из 34 буквенно-цифровых символов: <ul><li> сначала двухбуквенный код страны ISO 3166-1 alpha-2 </li><li> затем две контрольные цифры и </li><li> наконец, базовый номер банковского счета для конкретной страны (BBAN). </li></ul> Контрольные цифры позволяют проверить работоспособность номера банковского счета, чтобы подтвердить его целостность даже перед отправкой транзакции. Напишите функцию, которая принимает строку IBAN в качестве параметра. Если это верно, верните true. В противном случае верните false. </section>
<section id='description'>
<a href="https://en.wikipedia.org/wiki/International_Bank_Account_Number">Международный номер банковского счета (IBAN)</a> является международно согласованным средством определения банковских счетов через национальные границы с уменьшенным риском распространения <a href="https://en.wikipedia.org/wiki/Transcription_error">ошибок транскрипции</a> . IBAN состоит из 34 буквенно-цифровых символов: <ul><li> сначала двухбуквенный код страны ISO 3166-1 alpha-2 </li><li> затем две контрольные цифры и </li><li> наконец, базовый номер банковского счета для конкретной страны (BBAN). </li></ul> Контрольные цифры позволяют проверить работоспособность номера банковского счета, чтобы подтвердить его целостность даже перед отправкой транзакции. Напишите функцию, которая принимает строку IBAN в качестве параметра. Если это верно, верните true. В противном случае верните false.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes IBAN string as parameter. If it is valid return true. Otherwise, return false.
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Они были
```yml
tests:
- text: <code>isValid</code> должна быть функцией.
testString: 'assert(typeof isValid=="function","<code>isValid</code> should be a function.");'
- text: '<code>isValid(&quot;&quot;+tests[0]+&quot;&quot;)</code> должен возвращать логическое значение.'
testString: 'assert(typeof isValid(tests[0])=="boolean","<code>isValid(""+tests[0]+"")</code> should return a boolean.");'
- text: '<code>isValid(&quot;&quot;+tests[0]+&quot;&quot;)</code> должен возвращать <code>true</code> .'
testString: 'assert.equal(isValid(tests[0]),true,"<code>isValid(""+tests[0]+"")</code> should return <code>true</code>.");'
- text: '<code>isValid(&quot;&quot;+tests[1]+&quot;&quot;)</code> должен возвращать <code>false</code> .'
testString: 'assert.equal(isValid(tests[1]),false,"<code>isValid(""+tests[1]+"")</code> should return <code>false</code>.");'
- text: '<code>isValid(&quot;&quot;+tests[2]+&quot;&quot;)</code> должен возвращать <code>false</code> .'
testString: 'assert.equal(isValid(tests[2]),false,"<code>isValid(""+tests[2]+"")</code> should return <code>false</code>.");'
- text: '<code>isValid(&quot;&quot;+tests[3]+&quot;&quot;)</code> должен возвращать <code>false</code> .'
testString: 'assert.equal(isValid(tests[3]),false,"<code>isValid(""+tests[3]+"")</code> should return <code>false</code>.");'
- text: '<code>isValid(&quot;&quot;+tests[4]+&quot;&quot;)</code> должны возвращать <code>true</code> .'
testString: 'assert.equal(isValid(tests[4]),true,"<code>isValid(""+tests[4]+"")</code> should return <code>true</code>.");'
- text: <code>isValid</code> should be a function.
testString: assert(typeof isValid=='function');
- text: <code>isValid("GB82 WEST 1234 5698 7654 32")</code> should return a boolean.
testString: assert(typeof isValid('GB82 WEST 1234 5698 7654 32')=='boolean');
- text: <code>isValid("GB82 WEST 1234 5698 7654 32")</code> should return <code>true</code>.
testString: assert.equal(isValid('GB82 WEST 1234 5698 7654 32'),true);
- text: <code>isValid("GB82 WEST 1.34 5698 7654 32")</code> should return <code>false</code>.
testString: assert.equal(isValid('GB82 WEST 1.34 5698 7654 32'),false);
- text: <code>isValid("GB82 WEST 1234 5698 7654 325")</code> should return <code>false</code>.
testString: assert.equal(isValid('GB82 WEST 1234 5698 7654 325'),false);
- text: <code>isValid("GB82 TEST 1234 5698 7654 32")</code> should return <code>false</code>.
testString: assert.equal(isValid('GB82 TEST 1234 5698 7654 32'),false);
- text: <code>isValid("SA03 8000 0000 6080 1016 7519")</code> should return <code>true</code>.
testString: assert.equal(isValid('SA03 8000 0000 6080 1016 7519'),true);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function isValid (iban) {
function isValid(iban) {
// Good luck!
}
@@ -51,22 +54,32 @@ function isValid (iban) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function isValid(iban) {
var ibanLen = {
NO:15, BE:16, DK:18, FI:18, FO:18, GL:18, NL:18, MK:19,
SI:19, AT:20, BA:20, EE:20, KZ:20, LT:20, LU:20, CR:21,
CH:21, HR:21, LI:21, LV:21, BG:22, BH:22, DE:22, GB:22,
GE:22, IE:22, ME:22, RS:22, AE:23, GI:23, IL:23, AD:24,
CZ:24, ES:24, MD:24, PK:24, RO:24, SA:24, SE:24, SK:24,
VG:24, TN:24, PT:25, IS:26, TR:26, FR:27, GR:27, IT:27,
MC:27, MR:27, SM:27, AL:28, AZ:28, CY:28, DO:28, GT:28,
HU:28, LB:28, PL:28, BR:29, PS:29, KW:30, MU:30, MT:31
}
iban = iban.replace(/\s/g, '')
if (!iban.match(/^[\dA-Z]+$/)) return false
var len = iban.length
if (len != ibanLen[iban.substr(0,2)]) return false
iban = iban.substr(4) + iban.substr(0,4)
for (var s='', i=0; i<len; i+=1) s+=parseInt(iban.charAt(i),36)
for (var m=s.substr(0,15)%97, s=s.substr(15); s; s=s.substr(13)) m=(m+s.substr(0,13))%97
return m == 1
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Identity matrix
id: 5a23c84252665b21eecc7eb1
challengeType: 5
videoUrl: ''
forumTopicId: 302290
localeTitle: Единичная матрица
---
## Description
<section id="description"> <i>Единичная матрица</i> является квадратной матрицей размера \ (n \ times n \), где диагональные элементы - все <b>1</b> s (одни), а все остальные элементы - все <b>0</b> s (нули). \ begin {bmatrix} 1 &amp; 0 &amp; 0 \ cr 0 &amp; 1 &amp; 0 \ cr 0 &amp; 0 &amp; 1 \ cr \ end {bmatrix} Напишите функцию, которая принимает число «n» в качестве параметра и возвращает единичную матрицу порядок nx n. </section>
<section id='description'>
<i>Единичная матрица</i> является квадратной матрицей размера \ (n \ times n \), где диагональные элементы - все <b>1</b> s (одни), а все остальные элементы - все <b>0</b> s (нули). \ begin {bmatrix} 1 &amp; 0 &amp; 0 \ cr 0 &amp; 1 &amp; 0 \ cr 0 &amp; 0 &amp; 1 \ cr \ end {bmatrix} Напишите функцию, которая принимает число «n» в качестве параметра и возвращает единичную матрицу порядок nx n.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes a number <code>n</code> as a parameter and returns the identity matrix of order \( n \times n \).
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Единичная матрица
```yml
tests:
- text: <code>idMatrix</code> должна быть функцией.
testString: 'assert(typeof idMatrix=="function","<code>idMatrix</code> should be a function.");'
- text: <code>idMatrix(1)</code> должен возвращать массив.
testString: 'assert(Array.isArray(idMatrix(1)),"<code>idMatrix(1)</code> should return an array.");'
- text: '<code>idMatrix(1)</code> должен возвращать <code>&quot;+JSON.stringify(results[0])+&quot;</code> .'
testString: 'assert.deepEqual(idMatrix(1),results[0],"<code>idMatrix(1)</code> should return <code>"+JSON.stringify(results[0])+"</code>.");'
- text: '<code>idMatrix(2)</code> должен возвращать <code>&quot;+JSON.stringify(results[1])+&quot;</code> .'
testString: 'assert.deepEqual(idMatrix(2),results[1],"<code>idMatrix(2)</code> should return <code>"+JSON.stringify(results[1])+"</code>.");'
- text: '<code>idMatrix(3)</code> должен возвращать <code>&quot;+JSON.stringify(results[2])+&quot;</code> .'
testString: 'assert.deepEqual(idMatrix(3),results[2],"<code>idMatrix(3)</code> should return <code>"+JSON.stringify(results[2])+"</code>.");'
- text: '<code>idMatrix(4)</code> должен возвращать <code>&quot;+JSON.stringify(results[3])+&quot;</code> .'
testString: 'assert.deepEqual(idMatrix(4),results[3],"<code>idMatrix(4)</code> should return <code>"+JSON.stringify(results[3])+"</code>.");'
- text: <code>idMatrix</code> should be a function.
testString: assert(typeof idMatrix=='function');
- text: <code>idMatrix(1)</code> should return an array.
testString: assert(Array.isArray(idMatrix(1)));
- text: <code>idMatrix(1)</code> should return <code>[ [ 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(1),results[0]);
- text: <code>idMatrix(2)</code> should return <code>[ [ 1, 0 ], [ 0, 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(2),results[1]);
- text: <code>idMatrix(3)</code> should return <code>[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(3),results[2]);
- text: <code>idMatrix(4)</code> should return <code>[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(4),results[3]);
```
@@ -41,7 +44,7 @@ tests:
<div id='js-seed'>
```js
function idMatrix (n) {
function idMatrix(n) {
// Good luck!
}
@@ -49,12 +52,15 @@ function idMatrix (n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
let results=[[ [ 1 ] ],
[ [ 1, 0 ], [ 0, 1 ] ],
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ],
[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]]
```
</div>
@@ -65,6 +71,13 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function idMatrix(n) {
return Array.apply(null, new Array(n)).map(function (x, i, xs) {
return xs.map(function (_, k) {
return i === k ? 1 : 0;
})
});
}
```
</section>

View File

@@ -2,16 +2,19 @@
title: Iterated digits squaring
id: 5a23c84252665b21eecc7ec1
challengeType: 5
videoUrl: ''
forumTopicId: 302291
localeTitle: Итерированные цифры в квадрате
---
## Description
<section id="description"> Если вы добавите квадрат цифр натурального числа (целое число больше нуля), вы всегда заканчиваете либо 1, либо 89: <pre> 15 -&gt; 26 -&gt; 40 -&gt; 16 -&gt; 37 -&gt; 58 -&gt; 89
7 -&gt; 49 -&gt; 97 -&gt; 130 -&gt; 10 -&gt; 1 </pre> Напишите функцию, которая принимает число как параметр и возвращает 1 или 89 после выполнения указанного процесса. </section>
<section id='description'>
Если вы добавите квадрат цифр натурального числа (целое число больше нуля), вы всегда заканчиваете либо 1, либо 89: <pre> 15 -&gt; 26 -&gt; 40 -&gt; 16 -&gt; 37 -&gt; 58 -&gt; 89
7 -&gt; 49 -&gt; 97 -&gt; 130 -&gt; 10 -&gt; 1 </pre> Напишите функцию, которая принимает число как параметр и возвращает 1 или 89 после выполнения указанного процесса.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes a number as a parameter and returns 1 or 89 after performing the mentioned process.
</section>
## Tests
@@ -19,22 +22,22 @@ localeTitle: Итерированные цифры в квадрате
```yml
tests:
- text: <code>iteratedSquare</code> должна быть функцией.
testString: 'assert(typeof iteratedSquare=="function","<code>iteratedSquare</code> should be a function.");'
- text: <code>iteratedSquare(4)</code> должен вернуть число.
testString: 'assert(typeof iteratedSquare(4)=="number","<code>iteratedSquare(4)</code> should return a number.");'
- text: <code>iteratedSquare(4)</code> должен вернуть <code>89</code> .
testString: 'assert.equal(iteratedSquare(4),89,"<code>iteratedSquare(4)</code> should return <code>89</code>.");'
- text: <code>iteratedSquare(7)</code> должен вернуть <code>1</code> .
testString: 'assert.equal(iteratedSquare(7),1,"<code>iteratedSquare(7)</code> should return <code>1</code>.");'
- text: <code>iteratedSquare(15)</code> должен вернуть <code>89</code> .
testString: 'assert.equal(iteratedSquare(15),89,"<code>iteratedSquare(15)</code> should return <code>89</code>.");'
- text: <code>iteratedSquare(20)</code> должен вернуть <code>89</code> .
testString: 'assert.equal(iteratedSquare(20),89,"<code>iteratedSquare(20)</code> should return <code>89</code>.");'
- text: <code>iteratedSquare(70)</code> должен вернуть <code>1</code> .
testString: 'assert.equal(iteratedSquare(70),1,"<code>iteratedSquare(70)</code> should return <code>1</code>.");'
- text: <code>iteratedSquare(100)</code> должен вернуть <code>1</code> .
testString: 'assert.equal(iteratedSquare(100),1,"<code>iteratedSquare(100)</code> should return <code>1</code>.");'
- text: <code>iteratedSquare</code> should be a function.
testString: assert(typeof iteratedSquare=='function');
- text: <code>iteratedSquare(4)</code> should return a number.
testString: assert(typeof iteratedSquare(4)=='number');
- text: <code>iteratedSquare(4)</code> should return <code>89</code>.
testString: assert.equal(iteratedSquare(4),89);
- text: <code>iteratedSquare(7)</code> should return <code>1</code>.
testString: assert.equal(iteratedSquare(7),1);
- text: <code>iteratedSquare(15)</code> should return <code>89</code>.
testString: assert.equal(iteratedSquare(15),89);
- text: <code>iteratedSquare(20)</code> should return <code>89</code>.
testString: assert.equal(iteratedSquare(20),89);
- text: <code>iteratedSquare(70)</code> should return <code>1</code>.
testString: assert.equal(iteratedSquare(70),1);
- text: <code>iteratedSquare(100)</code> should return <code>1</code>.
testString: assert.equal(iteratedSquare(100),1);
```
@@ -46,7 +49,7 @@ tests:
<div id='js-seed'>
```js
function iteratedSquare (n) {
function iteratedSquare(n) {
// Good luck!
}
@@ -54,14 +57,24 @@ function iteratedSquare (n) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function iteratedSquare(n) {
var total;
while (n != 89 && n != 1) {
total = 0;
while (n > 0) {
total += Math.pow(n % 10, 2);
n = Math.floor(n/10);
}
n = total;
}
return n;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Jaro distance
id: 5a23c84252665b21eecc7ec2
challengeType: 5
videoUrl: ''
forumTopicId: 302292
localeTitle: Расстояние Jaro
---
## Description
<section id="description"> Расстояние Jaro является мерой сходства между двумя строками. Чем выше расстояние Jaro для двух строк, тем более похожи строки. Оценка нормализуется так, что <b>0 не</b> приравнивается к подобию, а <b>1</b> - точное совпадение. Определение Расстояние Jaro \ (d_j \) двух заданных строк \ (s_1 \) и \ (s_2 \) - это \ begin {align} d_j = \ begin {cases} 0 &amp; &amp; \ text {if} m = 0 \\\ \ {\ frac {1} {3}} \ left ({\ frac {m} {| s_ {1} |}} + {\ frac {m} {| s_ {2} |}} + {\ frac { mt} {m}} \ right) &amp; &amp; \ text {other} \ end {cases} \ end {align} Где: <ul><li> \ (m \) - количество <i>совпадающих символов</i> ; </li><li> \ (t \) - половина числа <i>транспозиций</i> . </li></ul> Два символа из \ (s_1 \) и \ (s_2 \) соответственно, считаются <i>совпадающими,</i> только если они одинаковы, а не дальше \ (\ left \ lfloor \ frac {\ max (| s_1 |, | s_2 |)} {2} \ право \ rfloor-1 \). Каждый символ \ (s_1 \) сравнивается со всеми его совпадающими символами в \ (s_2 \). Количество совпадающих (но разных порядковых порядков) символов, деленное на 2, определяет количество <i>транспозиций</i> . <b>Пример.</b> С учетом строк \ (s_1 \) <i>DWAYNE</i> и \ (s_2 \) <i>DUANE</i> находим: <ul><li> \ (т = 4 \) </li><li> \ (| s_1 | = 6 \) </li><li> \ (| s_2 | = 5 \) </li><li> \ (t = 0 \) </li></ul> Мы находим оценку Джаро: \ (d_j = \ frac {1} {3} \ left (\ frac {4} {6} + \ frac {4} {5} + \ frac {4-0} {4} \ right) = 0.822 \). Напишите функцию a, которая принимает две строки в качестве параметров и возвращает связанное расстояние Jaro. </section>
<section id='description'>
Расстояние Jaro является мерой сходства между двумя строками. Чем выше расстояние Jaro для двух строк, тем более похожи строки. Оценка нормализуется так, что <b>0 не</b> приравнивается к подобию, а <b>1</b> - точное совпадение. Определение Расстояние Jaro \ (d_j \) двух заданных строк \ (s_1 \) и \ (s_2 \) - это \ begin {align} d_j = \ begin {cases} 0 &amp; &amp; \ text {if} m = 0 \\\ \ {\ frac {1} {3}} \ left ({\ frac {m} {| s_ {1} |}} + {\ frac {m} {| s_ {2} |}} + {\ frac { mt} {m}} \ right) &amp; &amp; \ text {other} \ end {cases} \ end {align} Где: <ul><li> \ (m \) - количество <i>совпадающих символов</i> ; </li><li> \ (t \) - половина числа <i>транспозиций</i> . </li></ul> Два символа из \ (s_1 \) и \ (s_2 \) соответственно, считаются <i>совпадающими,</i> только если они одинаковы, а не дальше \ (\ left \ lfloor \ frac {\ max (| s_1 |, | s_2 |)} {2} \ право \ rfloor-1 \). Каждый символ \ (s_1 \) сравнивается со всеми его совпадающими символами в \ (s_2 \). Количество совпадающих (но разных порядковых порядков) символов, деленное на 2, определяет количество <i>транспозиций</i> . <b>Пример.</b> С учетом строк \ (s_1 \) <i>DWAYNE</i> и \ (s_2 \) <i>DUANE</i> находим: <ul><li> \ (т = 4 \) </li><li> \ (| s_1 | = 6 \) </li><li> \ (| s_2 | = 5 \) </li><li> \ (t = 0 \) </li></ul> Мы находим оценку Джаро: \ (d_j = \ frac {1} {3} \ left (\ frac {4} {6} + \ frac {4} {5} + \ frac {4-0} {4} \ right) = 0.822 \). Напишите функцию a, которая принимает две строки в качестве параметров и возвращает связанное расстояние Jaro.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function a that takes two strings as parameters and returns the associated Jaro distance.
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Расстояние Jaro
```yml
tests:
- text: <code>jaro</code> должен быть функцией.
testString: 'assert(typeof jaro=="function","<code>jaro</code> should be a function.");'
- text: '<code>jaro(&quot;&quot;+tests[0][0]+&quot;&quot;,&quot;&quot;+tests[0][1]+&quot;&quot;)</code> должны возвращать число.'
testString: 'assert(typeof jaro(tests[0][0],tests[0][1])=="number","<code>jaro()</code> should return a number.");'
- text: '<code>jaro(&quot;&quot;+tests[0][0]+&quot;&quot;,&quot;&quot;+tests[0][1]+&quot;&quot;)</code> должны возвращать <code>&quot;+results[0]+&quot;</code> .'
testString: 'assert.equal(jaro(tests[0][0],tests[0][1]),results[0],"<code>jaro(""+tests[0][0]+"",""+tests[0][1]+"")</code> should return <code>"+results[0]+"</code>.");'
- text: '<code>jaro(&quot;&quot;+tests[1][0]+&quot;&quot;,&quot;&quot;+tests[1][1]+&quot;&quot;)</code> должны возвращать <code>&quot;+results[1]+&quot;</code> .'
testString: 'assert.equal(jaro(tests[1][0],tests[1][1]),results[1],"<code>jaro(""+tests[1][0]+"",""+tests[1][1]+"")</code> should return <code>"+results[1]+"</code>.");'
- text: '<code>jaro(&quot;&quot;+tests[2][0]+&quot;&quot;,&quot;&quot;+tests[2][1]+&quot;&quot;)</code> должны возвращать <code>&quot;+results[2]+&quot;</code> .'
testString: 'assert.equal(jaro(tests[2][0],tests[2][1]),results[2],"<code>jaro(""+tests[2][0]+"",""+tests[2][1]+"")</code> should return <code>"+results[2]+"</code>.");'
- text: '<code>jaro(&quot;&quot;+tests[3][0]+&quot;&quot;,&quot;&quot;+tests[3][1]+&quot;&quot;)</code> должны возвращать <code>&quot;+results[3]+&quot;</code> .'
testString: 'assert.equal(jaro(tests[3][0],tests[3][1]),results[3],"<code>jaro(""+tests[3][0]+"",""+tests[3][1]+"")</code> should return <code>"+results[3]+"</code>.");'
- text: '<code>jaro(&quot;&quot;+tests[4][0]+&quot;&quot;,&quot;&quot;+tests[4][1]+&quot;&quot;)</code> должны возвращать <code>&quot;+results[4]+&quot;</code> .'
testString: 'assert.equal(jaro(tests[4][0],tests[4][1]),results[4],"<code>jaro(""+tests[4][0]+"",""+tests[4][1]+"")</code> should return <code>"+results[4]+"</code>.");'
- text: <code>jaro</code> should be a function.
testString: assert(typeof jaro=='function');
- text: <code>jaro("MARTHA", "MARHTA")</code> should return a number.
testString: assert(typeof jaro('MARTHA', 'MARHTA')=='number');
- text: <code>jaro("MARTHA", "MARHTA")</code> should return <code>0.9444444444444445</code>.
testString: assert.equal(jaro('MARTHA', 'MARHTA'), 0.9444444444444445);
- text: <code>jaro("DIXON", "DICKSONX")</code> should return <code>0.7666666666666666</code>.
testString: assert.equal(jaro('DIXON', 'DICKSONX'), 0.7666666666666666);
- text: <code>jaro("JELLYFISH", "SMELLYFISH")</code> should return <code>0.8962962962962964</code>.
testString: assert.equal(jaro('JELLYFISH', 'SMELLYFISH'), 0.8962962962962964);
- text: <code>jaro("HELLOS", "CHELLO")</code> should return <code>0.888888888888889</code>.
testString: assert.equal(jaro('HELLOS', 'CHELLO'), 0.888888888888889);
- text: <code>jaro("ABCD", "BCDA")</code> should return <code>0.8333333333333334</code>.
testString: assert.equal(jaro('ABCD', 'BCDA'), 0.8333333333333334);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function jaro (s, t) {
function jaro(s, t) {
// Good luck!
}
@@ -51,22 +54,54 @@ function jaro (s, t) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function jaro(s, t) {
var s_len = s.length;
var t_len = t.length;
if (s_len == 0 && t_len == 0) return 1;
var match_distance = Math.max(s_len, t_len) / 2 - 1;
var s_matches = new Array(s_len);
var t_matches = new Array(t_len);
var matches = 0;
var transpositions = 0;
for (var i = 0; i < s_len; i++) {
var start = Math.max(0, i - match_distance);
var end = Math.min(i + match_distance + 1, t_len);
for (var j = start; j < end; j++) {
if (t_matches[j]) continue;
if (s.charAt(i) != t.charAt(j)) continue;
s_matches[i] = true;
t_matches[j] = true;
matches++;
break;
}
}
if (matches == 0) return 0;
var k = 0;
for (var i = 0; i < s_len; i++) {
if (!s_matches[i]) continue;
while (!t_matches[k]) k++;
if (s.charAt(i) != t.charAt(k)) transpositions++;
k++;
}
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2.0) / matches)) / 3.0;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: JortSort
id: 5a23c84252665b21eecc7ec4
challengeType: 5
videoUrl: ''
forumTopicId: 302293
localeTitle: JortSort
---
## Description
<section id="description"> jortSort - это набор инструментов сортировки, который заставляет пользователя выполнять работу и гарантирует эффективность, потому что вам больше не нужно сортировать. Первоначально он был представлен Jenn «Moneydollars» Шиффер на престижном <a href="https://www.youtube.com/watch?v=pj4U_W0OFoE">JSConf</a> . jortSort - это функция, которая принимает один массив сопоставимых объектов в качестве аргумента. Затем он сортирует массив в порядке возрастания и сравнивает отсортированный массив с первоначально предоставленным массивом. Если массивы совпадают (т. Е. Исходный массив уже был отсортирован), функция возвращает true. Если массивы не совпадают (т. Е. Исходный массив не был отсортирован), функция возвращает false. </section>
<section id='description'>
jortSort - это набор инструментов сортировки, который заставляет пользователя выполнять работу и гарантирует эффективность, потому что вам больше не нужно сортировать. Первоначально он был представлен Jenn «Moneydollars» Шиффер на престижном <a href="https://www.youtube.com/watch?v=pj4U_W0OFoE">JSConf</a> . jortSort - это функция, которая принимает один массив сопоставимых объектов в качестве аргумента. Затем он сортирует массив в порядке возрастания и сравнивает отсортированный массив с первоначально предоставленным массивом. Если массивы совпадают (т. Е. Исходный массив уже был отсортирован), функция возвращает true. Если массивы не совпадают (т. Е. Исходный массив не был отсортирован), функция возвращает false.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,22 +21,22 @@ localeTitle: JortSort
```yml
tests:
- text: <code>jortsort</code> должен быть функцией.
testString: 'assert(typeof jortsort=="function","<code>jortsort</code> should be a function.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[0])+&quot;)</code> должен возвращать логическое значение.'
testString: 'assert(typeof jortsort(tests[0].slice())=="boolean","<code>jortsort("+JSON.stringify(tests[0])+")</code> should return a boolean.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[0])+&quot;)</code> должен возвращать <code>true</code> .'
testString: 'assert.equal(jortsort(tests[0].slice()),true,"<code>jortsort("+JSON.stringify(tests[0])+")</code> should return <code>true</code>.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[1])+&quot;)</code> должен возвращать <code>false</code> .'
testString: 'assert.equal(jortsort(tests[1].slice()),false,"<code>jortsort("+JSON.stringify(tests[1])+")</code> should return <code>false</code>.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[2])+&quot;)</code> должен возвращать значение <code>false</code> .'
testString: 'assert.equal(jortsort(tests[2].slice()),false,"<code>jortsort("+JSON.stringify(tests[2])+")</code> should return <code>false</code>.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[3])+&quot;)</code> должен возвращать <code>true</code> .'
testString: 'assert.equal(jortsort(tests[3].slice()),true,"<code>jortsort("+JSON.stringify(tests[3])+")</code> should return <code>true</code>.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[4])+&quot;)</code> должен возвращать значение <code>false</code> .'
testString: 'assert.equal(jortsort(tests[4].slice()),false,"<code>jortsort("+JSON.stringify(tests[4])+")</code> should return <code>false</code>.");'
- text: '<code>jortsort(&quot;+JSON.stringify(tests[5])+&quot;)</code> должен возвращать <code>true</code> .'
testString: 'assert.equal(jortsort(tests[5].slice()),true,"<code>jortsort("+JSON.stringify(tests[5])+")</code> should return <code>true</code>.");'
- text: <code>jortsort</code> should be a function.
testString: assert(typeof jortsort=='function');
- text: <code>jortsort([1,2,3,4,5])</code> should return a boolean.
testString: assert(typeof jortsort([1,2,3,4,5])=='boolean');
- text: <code>jortsort([1,2,3,4,5])</code> should return <code>true</code>.
testString: assert.equal(jortsort([1,2,3,4,5]),true);
- text: <code>jortsort([1,2,13,4,5])</code> should return <code>false</code>.
testString: assert.equal(jortsort([1,2,13,4,5]),false);
- text: <code>jortsort([12,4,51,2,4])</code> should return <code>false</code>.
testString: assert.equal(jortsort([12,4,51,2,4]),false);
- text: <code>jortsort([1,2])</code> should return <code>true</code>.
testString: assert.equal(jortsort([1,2]),true);
- text: <code>jortsort([5,4,3,2,1])</code> should return <code>false</code>.
testString: assert.equal(jortsort([5,4,3,2,1]),false);
- text: <code>jortsort([1,1,1,1,1])</code> should return <code>true</code>.
testString: assert.equal(jortsort([1,1,1,1,1]),true);
```
@@ -45,7 +48,7 @@ tests:
<div id='js-seed'>
```js
function jortsort (array) {
function jortsort(array) {
// Good luck!
}
@@ -53,22 +56,24 @@ function jortsort (array) {
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function jortsort(array) {
// sort the array
var originalArray = array.slice(0);
array.sort( function(a,b){return a - b} );
// compare to see if it was originally sorted
for (var i = 0; i < originalArray.length; ++i) {
if (originalArray[i] !== array[i]) return false;
}
return true;
};
```
</section>

View File

@@ -2,15 +2,18 @@
title: Josephus problem
id: 5a23c84252665b21eecc7ec5
challengeType: 5
videoUrl: ''
forumTopicId: 302294
localeTitle: Проблема Иосифа
---
## Description
<section id="description"> <a href="https://en.wikipedia.org/wiki/Josephus problem">Проблема Джозефуса</a> - математическая головоломка с мрачным описанием: $ n $ заключенные стоят по кругу, последовательно пронумерованные от $ 0 $ до $ n-1 $. Палач ходит по кругу, начиная с заключенного $ 0 $, удаляя каждого $ k $ -ного заключенного и убивая его. По мере того как процесс продолжается, круг становится все меньше и меньше, пока остается только один заключенный, который затем освобождается. Например, если есть $ n = 5 $ заключенных и $ k = 2 $, то порядок, в котором заключенные будут убиты (назовем его «последовательностью убийства»), будет 1, 3, 0 и 4, а оставшийся в живых будет # 2. Учитывая любые <big>$ n, k&gt; 0 $</big> , выясните, кто из заключенных будет последним выжившим. В одном из таких инцидентов было 41 заключенный, и каждый 3- <sup>й</sup> заключенный был убит ( <big>$ k = 3 $</big> ). Среди них было умное имя Джофа, который разработал проблему, стоял в выжившем положении и продолжал рассказывать историю. Каким он был? Напишите функцию, которая берет начальное число заключенных и «k» в качестве параметра и возвращает число заключенного, который выживает. </section>
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Josephus problem">Проблема Джозефуса</a> - математическая головоломка с мрачным описанием: $ n $ заключенные стоят по кругу, последовательно пронумерованные от $ 0 $ до $ n-1 $. Палач ходит по кругу, начиная с заключенного $ 0 $, удаляя каждого $ k $ -ного заключенного и убивая его. По мере того как процесс продолжается, круг становится все меньше и меньше, пока остается только один заключенный, который затем освобождается. Например, если есть $ n = 5 $ заключенных и $ k = 2 $, то порядок, в котором заключенные будут убиты (назовем его «последовательностью убийства»), будет 1, 3, 0 и 4, а оставшийся в живых будет # 2. Учитывая любые <big>$ n, k&gt; 0 $</big> , выясните, кто из заключенных будет последним выжившим. В одном из таких инцидентов было 41 заключенный, и каждый 3- <sup>й</sup> заключенный был убит ( <big>$ k = 3 $</big> ). Среди них было умное имя Джофа, который разработал проблему, стоял в выжившем положении и продолжал рассказывать историю. Каким он был? Напишите функцию, которая берет начальное число заключенных и «k» в качестве параметра и возвращает число заключенного, который выживает.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes the initial number of prisoners and 'k' as parameter and returns the number of the prisoner that survives.
</section>
## Tests
@@ -18,20 +21,20 @@ localeTitle: Проблема Иосифа
```yml
tests:
- text: <code>josephus</code> должен быть функцией.
testString: 'assert(typeof josephus=="function","<code>josephus</code> should be a function.");'
- text: '<code>josephus(30,3)</code> должен вернуть число.'
testString: 'assert(typeof josephus(30,3)=="number","<code>josephus(30,3)</code> should return a number.");'
- text: '<code>josephus(30,3)</code> должен вернуться <code>29</code> .'
testString: 'assert.equal(josephus(30,3),29,"<code>josephus(30,3)</code> should return <code>29</code>.");'
- text: '<code>josephus(30,5)</code> должен вернуться <code>3</code> .'
testString: 'assert.equal(josephus(30,5),3,"<code>josephus(30,5)</code> should return <code>3</code>.");'
- text: '<code>josephus(20,2)</code> должен вернуться <code>9</code> .'
testString: 'assert.equal(josephus(20,2),9,"<code>josephus(20,2)</code> should return <code>9</code>.");'
- text: '<code>josephus(17,6)</code> должен вернуться <code>2</code> .'
testString: 'assert.equal(josephus(17,6),2,"<code>josephus(17,6)</code> should return <code>2</code>.");'
- text: '<code>josephus(29,4)</code> должен вернуться <code>2</code> .'
testString: 'assert.equal(josephus(29,4),2,"<code>josephus(29,4)</code> should return <code>2</code>.");'
- text: <code>josephus</code> should be a function.
testString: assert(typeof josephus=='function');
- text: <code>josephus(30,3)</code> should return a number.
testString: assert(typeof josephus(30,3)=='number');
- text: <code>josephus(30,3)</code> should return <code>29</code>.
testString: assert.equal(josephus(30,3),29);
- text: <code>josephus(30,5)</code> should return <code>3</code>.
testString: assert.equal(josephus(30,5),3);
- text: <code>josephus(20,2)</code> should return <code>9</code>.
testString: assert.equal(josephus(20,2),9);
- text: <code>josephus(17,6)</code> should return <code>2</code>.
testString: assert.equal(josephus(17,6),2);
- text: <code>josephus(29,4)</code> should return <code>2</code>.
testString: assert.equal(josephus(29,4),2);
```
@@ -43,7 +46,7 @@ tests:
<div id='js-seed'>
```js
function josephus (init, kill) {
function josephus(init, kill) {
// Good luck!
}
@@ -51,14 +54,45 @@ function josephus (init, kill) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function josephus(init, kill) {
var Josephus = {
init: function(n) {
this.head = {};
var current = this.head;
for (var i = 0; i < n - 1; i++) {
current.label = i + 1;
current.next = {
prev: current
};
current = current.next;
}
current.label = n;
current.next = this.head;
this.head.prev = current;
return this;
},
kill: function(spacing) {
var current = this.head;
while (current.next !== current) {
for (var i = 0; i < spacing - 1; i++) {
current = current.next;
}
current.prev.next = current.next;
current.next.prev = current.prev;
current = current.next;
}
return current.label;
}
}
return Josephus.init(init).kill(kill)
}
```
</section>

View File

@@ -2,17 +2,32 @@
title: S-Expressions
id: 59667989bf71cf555dd5d2ff
challengeType: 5
videoUrl: ''
forumTopicId: 302303
localeTitle: S-выражение
---
## Description
<section id="description"><p> <a href="https://en.wikipedia.org/wiki/S-Expression" title="wp: S-выражение">S-выражения</a> - один из удобных способов анализа и хранения данных. </p> Задача: <p> Напишите простой читатель / парсер для S-Expressions, который обрабатывает строки с кавычками и без кавычек, целые числа и поплавки. </p><p> Функция должна читать одно, но вложенное S-выражение из строки и возвращать его как (вложенный) массив. </p><p> Новые строки и другие пробелы могут игнорироваться, если они не содержатся в цитируемой строке. </p><p> &quot; <tt>()</tt> &quot; Внутри цитируемых строк не интерпретируются, а рассматриваются как часть строки. </p><p> Обработка скрытых кавычек внутри строки необязательна; таким образом &quot; <tt>(foo&quot; bar)</tt> &quot;может рассматриваться как строка&quot; <tt>foo &quot;bar</tt> &quot; или как ошибка. </p><p> Для этого читатель не должен распознавать « <tt>\</tt> » для экранирования, но должен, кроме того, распознавать номера, если язык имеет соответствующие типы данных. </p><p> Обратите внимание, что за исключением « <tt>(» «</tt> » (« <tt>\</tt> », если поддерживается escaping) и пробелов нет специальных символов. Все остальное разрешено без кавычек. </p><p> Читатель должен уметь читать следующий ввод </p><p></p><pre> ((данные «котируемые данные» 123 4.5)
<section id='description'>
<p> <a href="https://en.wikipedia.org/wiki/S-Expression" title="wp: S-выражение">S-выражения</a> - один из удобных способов анализа и хранения данных. </p> Задача: <p> Напишите простой читатель / парсер для S-Expressions, который обрабатывает строки с кавычками и без кавычек, целые числа и поплавки. </p><p> Функция должна читать одно, но вложенное S-выражение из строки и возвращать его как (вложенный) массив. </p><p> Новые строки и другие пробелы могут игнорироваться, если они не содержатся в цитируемой строке. </p><p> &quot; <tt>()</tt> &quot; Внутри цитируемых строк не интерпретируются, а рассматриваются как часть строки. </p><p> Обработка скрытых кавычек внутри строки необязательна; таким образом &quot; <tt>(foo&quot; bar)</tt> &quot;может рассматриваться как строка&quot; <tt>foo &quot;bar</tt> &quot; или как ошибка. </p><p> Для этого читатель не должен распознавать « <tt>\</tt> » для экранирования, но должен, кроме того, распознавать номера, если язык имеет соответствующие типы данных. </p><p> Обратите внимание, что за исключением « <tt>(» «</tt> » (« <tt>\</tt> », если поддерживается escaping) и пробелов нет специальных символов. Все остальное разрешено без кавычек. </p><p> Читатель должен уметь читать следующий ввод </p><p></p><pre> ((данные «котируемые данные» 123 4.5)
(данные (! @ # (4.5) &quot;(более&quot; &quot;данные)&quot;)))
</pre><p></p><p> и превратить его в родную структуру данных. (см. реализации <a href="http://rosettacode.org/wiki/#Pike" title="#Pike">Pike</a> , <a href="http://rosettacode.org/wiki/#Python" title="#Python">Python</a> и <a href="http://rosettacode.org/wiki/#Ruby" title="#Рубин">Ruby</a> для примеров встроенных структур данных.) </p></section>
</pre><p></p><p> и превратить его в родную структуру данных. (см. реализации <a href="http://rosettacode.org/wiki/#Pike" title="#Pike">Pike</a> , <a href="http://rosettacode.org/wiki/#Python" title="#Python">Python</a> и <a href="http://rosettacode.org/wiki/#Ruby" title="#Рубин">Ruby</a> для примеров встроенных структур данных.) </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a simple reader/parser for S-Expressions that handles quoted and unquoted strings, integers and floats.
The function should read a single but nested S-Expression from a string and return it as a (nested) array.
Newlines and other whitespace may be ignored unless contained within a quoted string.
"<tt>()</tt>" inside quoted strings are not interpreted, but treated as part of the string.
Handling escaped quotes inside a string is optional; thus "<tt>(foo"bar)</tt>" may be treated as a string "<tt>foo"bar</tt>", or as an error.
For this, the reader need not recognize "<tt>\</tt>" for escaping, but should, in addition, recognize numbers if the language has appropriate data types.
Note that with the exception of "<tt>()"</tt>" ("<tt>\</tt>" if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.
The reader should be able to read the following input
<pre>
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
</pre>
and turn it into a native data structure. (See the <a href="https://rosettacode.org/wiki/S-Expressions#Pike" title="#Pike" target="_blank">Pike</a>, <a href="https://rosettacode.org/wiki/S-Expressions#Python" title="#Python" target="_blank">Python</a> and <a href="https://rosettacode.org/wiki/S-Expressions#Ruby" title="#Ruby" target="_blank">Ruby</a> implementations for examples of native data structures.)
</section>
## Tests
@@ -20,12 +35,12 @@ localeTitle: S-выражение
```yml
tests:
- text: <code>parseSexpr</code> - это функция.
testString: 'assert(typeof parseSexpr === "function", "<code>parseSexpr</code> is a function.");'
- text: '<code>parseSexpr(&quot;(data1 data2 data3)&quot;)</code> должен возвращать [&quot;data1&quot;, &quot;data2&quot;, &quot;data3&quot;] &quot;)'
testString: 'assert.deepEqual(parseSexpr(simpleSExpr), simpleSolution, "<code>parseSexpr("(data1 data2 data3)")</code> should return ["data1", "data2", "data3"]");'
- text: '<code>parseSexpr(&#39;(data1 data2 data3)&#39;)</code> должен возвращать массив с 3 элементами &quot;)'
testString: 'assert.deepEqual(parseSexpr(basicSExpr), basicSolution, "<code>parseSexpr("(data1 data2 data3)")</code> should return an array with 3 elements");'
- text: <code>parseSexpr</code> is a function.
testString: assert(typeof parseSexpr === 'function');
- text: <code>parseSexpr('(data1 data2 data3)')</code> should return <code>['data1', 'data2', 'data3']</code>
testString: assert.deepEqual(parseSexpr(simpleSExpr), simpleSolution);
- text: <code>parseSexpr('(data1 data2 data3)')</code> should return an array with 3 elements.
testString: assert.deepEqual(parseSexpr(basicSExpr), basicSolution);
```
@@ -46,12 +61,16 @@ function parseSexpr(str) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const simpleSExpr = '(data1 data2 data3)';
const simpleSolution = ['data1', 'data2', 'data3'];
const basicSExpr = '((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))';
const basicSolution = [["data","\"quoted data\"",123,4.5],["data",["!@#",[4.5],"\"(more\"","\"data)\""]]];
```
</div>
@@ -62,6 +81,21 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function parseSexpr(str) {
const t = str.match(/\s*("[^"]*"|\(|\)|"|[^\s()"]+)/g);
for (var o, c = 0, i = t.length - 1; i >= 0; i--) {
var n,
ti = t[i].trim();
if (ti == '"') return;
else if (ti == '(') t[i] = '[', c += 1;
else if (ti == ')') t[i] = ']', c -= 1;
else if ((n = +ti) == ti) t[i] = n;
else t[i] = `'${ti.replace('\'', '\\\'')}'`;
if (i > 0 && ti != ']' && t[i - 1].trim() != '(') t.splice(i, 0, ',');
if (!c) if (!o) o = true; else return;
}
return c ? undefined : eval(t.join(''));
}
```
</section>

View File

@@ -1,16 +1,27 @@
---
title: 'Sailors, coconuts and a monkey problem'
title: Sailors, coconuts and a monkey problem
id: 59da22823d04c95919d46269
challengeType: 5
videoUrl: ''
localeTitle: 'Моряки, кокосы и проблема обезьяны'
forumTopicId: 302304
localeTitle: Моряки, кокосы и проблема обезьяны
---
## Description
<section id="description"><p> Пять матросов потерпели кораблекрушение на острове и собирают большую кучу кокосовых орехов в течение дня. </p><p> В эту ночь первый моряк просыпается и решает взять свою первую долю раньше, поэтому пытается разделить кучу кокосов одинаково на пять кучек, но обнаруживает, что остался один кокос, поэтому он бросает его обезьяне, а затем прячет «свою», одну из пяти одинаковых по размеру груды кокосов и подталкивает еще четыре свай вместе, чтобы снова сформировать одну видимую груду кокосов и ложиться спать. </p><p> Короче говоря, каждый из моряков, в свою очередь, встает один раз ночью и выполняет те же действия, что и разделение кокосовой кучи на пять, и обнаруживает, что один кокос оставлен и дает кокосовому кокосовому ореху обезьяне. </p><p> Утром (после тайного и раздельного действия каждого из пяти матросов в ночное время) оставшиеся кокосы делятся на пять равных свай для каждого из моряков, после чего обнаруживается, что куча кокосовых орехов одинаково делится среди моряков без остатка. (Ничего для обезьяны утром). </p><p> Задание: </p><pre> <code> Create a function that returns the the minimum possible size of the initial pile of coconuts collected during the day for N sailors.</code> </pre><p> Заметка: </p><pre> <code> Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.</code> </pre><p> Cf: </p><p> <a href="https://www.youtube.com/watch?v=U9qU20VmvaU" title="ссылка: https://www.youtube.com/watch?v=U9qU20VmvaU">Обезьяны и кокосы - Numberphile</a> (видео) Аналитическое решение. </p><pre> <code> &lt;a href=&quot;http://oeis.org/A002021&quot; title=&quot;link: http://oeis.org/A002021&quot;&gt;A002021 Pile of coconuts problem&lt;/a&gt; The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).</code> </pre></section>
<section id='description'>
<p> Пять матросов потерпели кораблекрушение на острове и собирают большую кучу кокосовых орехов в течение дня. </p><p> В эту ночь первый моряк просыпается и решает взять свою первую долю раньше, поэтому пытается разделить кучу кокосов одинаково на пять кучек, но обнаруживает, что остался один кокос, поэтому он бросает его обезьяне, а затем прячет «свою», одну из пяти одинаковых по размеру груды кокосов и подталкивает еще четыре свай вместе, чтобы снова сформировать одну видимую груду кокосов и ложиться спать. </p><p> Короче говоря, каждый из моряков, в свою очередь, встает один раз ночью и выполняет те же действия, что и разделение кокосовой кучи на пять, и обнаруживает, что один кокос оставлен и дает кокосовому кокосовому ореху обезьяне. </p><p> Утром (после тайного и раздельного действия каждого из пяти матросов в ночное время) оставшиеся кокосы делятся на пять равных свай для каждого из моряков, после чего обнаруживается, что куча кокосовых орехов одинаково делится среди моряков без остатка. (Ничего для обезьяны утром). </p><p> Задание: </p><pre> <code> Create a function that returns the the minimum possible size of the initial pile of coconuts collected during the day for N sailors.</code> </pre><p> Заметка: </p><pre> <code> Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.</code> </pre><p> Cf: </p><p> <a href="https://www.youtube.com/watch?v=U9qU20VmvaU" title="ссылка: https://www.youtube.com/watch?v=U9qU20VmvaU">Обезьяны и кокосы - Numberphile</a> (видео) Аналитическое решение. </p><pre> <code> &lt;a href=&quot;http://oeis.org/A002021&quot; title=&quot;link: http://oeis.org/A002021&quot;&gt;A002021 Pile of coconuts problem&lt;/a&gt; The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).</code> </pre>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Create a function that returns the minimum possible size of the initial pile of coconuts collected during the day for <code>N</code> sailors.
<strong>Note:</strong>
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc. can occur in time fitting the story line, so as not to affect the mathematics.
<strong>C.f:</strong>
<ul>
<li><a href="https://www.youtube.com/watch?v=U9qU20VmvaU" target="_blank"> Monkeys and Coconuts - Numberphile</a> (Video) Analytical solution.</li>
<li><a href="https://oeis.org/A002021" target="_blank">A002021 Pile of coconuts problem</a> The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).</li>
</ul>
</section>
## Tests
@@ -18,14 +29,14 @@ localeTitle: 'Моряки, кокосы и проблема обезьяны'
```yml
tests:
- text: <code>splitCoconuts</code> - это функция.
testString: 'assert(typeof splitCoconuts === "function", "<code>splitCoconuts</code> is a function.");'
- text: <code>splitCoconuts(5)</code> должен вернуть 3121.
testString: 'assert(splitCoconuts(5) === 3121, "<code>splitCoconuts(5)</code> should return 3121.");'
- text: <code>splitCoconuts(6)</code> должен возвращать 233275.
testString: 'assert(splitCoconuts(6) === 233275, "<code>splitCoconuts(6)</code> should return 233275.");'
- text: <code>splitCoconuts(7)</code> должен вернуть 823537.
testString: 'assert(splitCoconuts(7) === 823537, "<code>splitCoconuts(7)</code> should return 823537.");'
- text: <code>splitCoconuts</code> is a function.
testString: assert(typeof splitCoconuts === 'function');
- text: <code>splitCoconuts(5)</code> should return 3121.
testString: assert(splitCoconuts(5) === 3121);
- text: <code>splitCoconuts(6)</code> should return 233275.
testString: assert(splitCoconuts(6) === 233275);
- text: <code>splitCoconuts(7)</code> should return 823537.
testString: assert(splitCoconuts(7) === 823537);
```
@@ -47,14 +58,41 @@ function splitCoconuts(intSailors) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
// noprotect
function splitCoconuts(intSailors) {
let intNuts = intSailors;
let result = splitCoconutsHelper(intNuts, intSailors);
while (!result) {
intNuts += 1;
result = splitCoconutsHelper(intNuts, intSailors);
}
return intNuts;
}
function splitCoconutsHelper(intNuts, intSailors, intDepth) {
const nDepth = intDepth !== undefined ? intDepth : intSailors;
const portion = Math.floor(intNuts / intSailors);
const remain = intNuts % intSailors;
if (portion <= 0 || remain !== (nDepth ? 1 : 0)) {
return null;
}
if (nDepth) {
return splitCoconutsHelper(
intNuts - portion - remain, intSailors, nDepth - 1
);
}
return intNuts;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: SEDOLs
id: 59d9c6bc214c613ba73ff012
challengeType: 5
videoUrl: ''
forumTopicId: 302305
localeTitle: SEDOLs
---
## Description
<section id="description"> Задача: <p> Для каждого списка номеров 6-значных <a href="https://en.wikipedia.org/wiki/SEDOL" title="wp: SEDOL">SEDOL</a> s вычислите и добавьте цифру контрольной суммы. </p><p> То есть, учитывая входную строку слева, ваша функция должна возвращать соответствующую строку справа: </p><pre> <code>&lt;pre&gt; 710889 =&gt; 7108899 B0YBKJ =&gt; B0YBKJ7 406566 =&gt; 4065663 B0YBLH =&gt; B0YBLH2 228276 =&gt; 2282765 B0YBKL =&gt; B0YBKL9 557910 =&gt; 5579107 B0YBKR =&gt; B0YBKR5 585284 =&gt; 5852842 B0YBKT =&gt; B0YBKT7 B00030 =&gt; B000300 &lt;/pre&gt;</code> </pre><p> Проверьте также, что каждый вход правильно сформирован, особенно в отношении допустимых символов, разрешенных в строке SEDOL. Ваша функция должна возвращать значение <code>null</code> для недопустимого ввода. </p></section>
<section id='description'>
Задача: <p> Для каждого списка номеров 6-значных <a href="https://en.wikipedia.org/wiki/SEDOL" title="wp: SEDOL">SEDOL</a> s вычислите и добавьте цифру контрольной суммы. </p><p> То есть, учитывая входную строку слева, ваша функция должна возвращать соответствующую строку справа: </p><pre> <code>&lt;pre&gt; 710889 =&gt; 7108899 B0YBKJ =&gt; B0YBKJ7 406566 =&gt; 4065663 B0YBLH =&gt; B0YBLH2 228276 =&gt; 2282765 B0YBKL =&gt; B0YBKL9 557910 =&gt; 5579107 B0YBKR =&gt; B0YBKR5 585284 =&gt; 5852842 B0YBKT =&gt; B0YBKT7 B00030 =&gt; B000300 &lt;/pre&gt;</code> </pre><p> Проверьте также, что каждый вход правильно сформирован, особенно в отношении допустимых символов, разрешенных в строке SEDOL. Ваша функция должна возвращать значение <code>null</code> для недопустимого ввода. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: SEDOLs
```yml
tests:
- text: <code>sedol</code> - это функция.
testString: 'assert(typeof sedol === "function", "<code>sedol</code> is a function.");'
- text: '<code>sedol(&#39;a&#39;)</code> должен возвращать null. &quot;)'
testString: 'assert(sedol("a") === null, "<code>sedol("a")</code> should return null.");'
- text: '<code>sedol(&#39;710889&#39;)</code> должен возвращать &#39;7108899&#39;. &quot;)'
testString: 'assert(sedol("710889") === "7108899", "<code>sedol("710889")</code> should return "7108899".");'
- text: '<code>sedol(&#39;BOATER&#39;)</code> должен вернуть null. &quot;)'
testString: 'assert(sedol("BOATER") === null, "<code>sedol("BOATER")</code> should return null.");'
- text: '<code>sedol(&#39;228276&#39;)</code> должен вернуться &#39;2282765&#39;. &quot;)'
testString: 'assert(sedol("228276") === "2282765", "<code>sedol("228276")</code> should return "2282765".");'
- text: <code>sedol</code> is a function.
testString: assert(typeof sedol === 'function');
- text: <code>sedol('a')</code> should return null.
testString: assert(sedol('a') === null);
- text: <code>sedol('710889')</code> should return '7108899'.
testString: assert(sedol('710889') === '7108899');
- text: <code>sedol('BOATER')</code> should return null.
testString: assert(sedol('BOATER') === null);
- text: <code>sedol('228276')</code> should return '2282765'.
testString: assert(sedol('228276') === '2282765');
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function sedol (input) {
function sedol(input) {
// Good luck!
return true;
}
@@ -48,14 +51,33 @@ function sedol (input) {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function sedol(input) {
const checkDigit = sedolCheckDigit(input);
if (checkDigit !== null) {
return input + checkDigit;
}
return null;
}
const weight = [1, 3, 1, 7, 3, 9, 1];
function sedolCheckDigit(char6) {
if (char6.search(/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$/) === -1) {
return null;
}
let sum = 0;
for (let i = 0; i < char6.length; i++) {
sum += weight[i] * parseInt(char6.charAt(i), 36);
}
const check = (10 - (sum % 10)) % 10;
return check.toString();
}
```
</section>

View File

@@ -2,15 +2,23 @@
title: Taxicab numbers
id: 594ecc0d9a8cf816e3340187
challengeType: 5
videoUrl: ''
forumTopicId: 302337
localeTitle: Номера такси
---
## Description
<section id="description"> Номер <a href="https://en.wikipedia.org/wiki/HardyRamanujan number" title="wp: номер Харди-Рамануджана">такси</a> (определение, которое используется здесь) является положительным целым числом, которое может быть выражено как сумма двух положительных кубов более чем одним способом. Первый номер такси составляет 1729, что составляет: 1 <sup>3</sup> + 12 <sup>3</sup> и 9 <sup>3</sup> + 10 <sup>3</sup> . Номера такси также известны как: * номера такси * номера такси-такси * номера такси * номера Hardy-Ramanujan Задача: Напишите функцию, которая возвращает самые низкие номера такси. Для каждого номера такси, укажите номер, а также его составные кубы. См. Также: [http://oeis.org/A001235 A001235 номера такси) в онлайновой энциклопедии целочисленных последовательностей. <a href="http://mathworld.wolfram.com/Hardy-RamanujanNumber.html">Харди-Рамануджан</a> на MathWorld. <a href="http://mathworld.wolfram.com/TaxicabNumber.html">номер такси</a> для MathWorld. <a href="https://en.wikipedia.org/wiki/Taxicab_number">номер такси</a> в Википедии. </section>
<section id='description'>
Номер <a href="https://en.wikipedia.org/wiki/HardyRamanujan number" title="wp: номер Харди-Рамануджана">такси</a> (определение, которое используется здесь) является положительным целым числом, которое может быть выражено как сумма двух положительных кубов более чем одним способом. Первый номер такси составляет 1729, что составляет: 1 <sup>3</sup> + 12 <sup>3</sup> и 9 <sup>3</sup> + 10 <sup>3</sup> . Номера такси также известны как: * номера такси * номера такси-такси * номера такси * номера Hardy-Ramanujan Задача: Напишите функцию, которая возвращает самые низкие номера такси. Для каждого номера такси, укажите номер, а также его составные кубы. См. Также: [http://oeis.org/A001235 A001235 номера такси) в онлайновой энциклопедии целочисленных последовательностей. <a href="http://mathworld.wolfram.com/Hardy-RamanujanNumber.html">Харди-Рамануджан</a> на MathWorld. <a href="http://mathworld.wolfram.com/TaxicabNumber.html">номер такси</a> для MathWorld. <a href="https://en.wikipedia.org/wiki/Taxicab_number">номер такси</a> в Википедии.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that returns the lowest <code>n</code> taxicab numbers. For each of the taxicab numbers, show the number as well as its constituent cubes.
<strong>See also:</strong>
<ul>
<li><a href="https://oeis.org/A001235" target="_blank">A001235 taxicab numbers</a> on The On-Line Encyclopedia of Integer Sequences.</li>
<li><a href="https://en.wikipedia.org/wiki/Taxicab_number" target="_blank">taxicab number</a> on Wikipedia.</li>
</ul>
</section>
## Tests
@@ -18,18 +26,18 @@ localeTitle: Номера такси
```yml
tests:
- text: <code>taxicabNumbers</code> - это функция.
testString: 'assert(typeof taxicabNumbers === "function", "<code>taxicabNumbers </code> is a function.");'
- text: <code>taxicabNumbers</code> должны возвращать массив.
testString: 'assert(typeof taxicabNumbers(2) === "object", "<code>taxicabNumbers </code> should return an array.");'
- text: <code>taxicabNumbers</code> должен возвращать массив чисел.
testString: 'assert(typeof taxicabNumbers(100)[0] === "number", "<code>taxicabNumbers </code> should return an array of numbers.");'
- text: '<code>taxicabNumbers(4)</code> должны вернуть [1729, 4104, 13832, 20683].'
testString: 'assert.deepEqual(taxicabNumbers(4), res4, "<code>taxicabNumbers(4) </code> must return [1729, 4104, 13832, 20683].");'
- text: 'taxicabNumbers (25) должны возвращаться [1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656, 110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 262656, 314496, 320264 , 327763, 373464, 402597]'
testString: 'assert.deepEqual(taxicabNumbers(25), res25, "taxicabNumbers(25) should return [1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656, 110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 262656, 314496, 320264, 327763, 373464, 402597]");'
- text: 'taxicabNumbers (39) итоговые цифры от 20 до 29 должны быть [314496,320264,327763,373464,402597,439101,443889,513000,513856].'
testString: 'assert.deepEqual(taxicabNumbers(39).slice(20, 29), res39From20To29, "taxicabNumbers(39) resulting numbers from 20 - 29 should be [314496,320264,327763,373464,402597,439101,443889,513000,513856].");'
- text: <code>taxicabNumbers</code> is a function.
testString: assert(typeof taxicabNumbers === 'function');
- text: <code>taxicabNumbers</code> should return an array.
testString: assert(typeof taxicabNumbers(2) === 'object');
- text: <code>taxicabNumbers</code> should return an array of numbers.
testString: assert(typeof taxicabNumbers(100)[0] === 'number');
- text: <code>taxicabNumbers(4)</code> must return [1729, 4104, 13832, 20683].
testString: assert.deepEqual(taxicabNumbers(4), res4);
- text: <code>taxicabNumbers(25)</code> should return [1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656, 110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 262656, 314496, 320264, 327763, 373464, 402597]
testString: assert.deepEqual(taxicabNumbers(25), res25);
- text: <code>taxicabNumbers(39)</code> resulting numbers from 20 - 29 should be [314496,320264,327763,373464,402597,439101,443889,513000,513856].
testString: assert.deepEqual(taxicabNumbers(39).slice(20, 29), res39From20To29);
```
@@ -41,7 +49,7 @@ tests:
<div id='js-seed'>
```js
function taxicabNumbers (n) {
function taxicabNumbers(n) {
// Good luck!
return true;
}
@@ -50,12 +58,19 @@ function taxicabNumbers (n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const res4 = [1729, 4104, 13832, 20683];
const res25 = [
1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656,
110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 262656, 314496, 320264, 327763,
373464, 402597
];
const res39From20To29 = [314496, 320264, 327763, 373464, 402597, 439101, 443889, 513000, 513856];
```
</div>
@@ -66,6 +81,42 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function taxicabNumbers(nNumbers) {
const cubeN = [];
const s3s = {};
const e = 100;
for (let n = 1; n < e; n += 1) {
cubeN[n] = n * n * n;
}
for (let a = 1; a < e - 1; a += 1) {
const a3 = cubeN[a];
for (let b = a; b < e; b += 1) {
const b3 = cubeN[b];
const s3 = a3 + b3;
let abs = s3s[s3];
if (!abs) {
s3s[s3] = abs = [];
}
abs.push([a, b]);
}
}
let i = 0;
const res = [];
Object.keys(s3s).forEach(s3 => {
const abs = s3s[s3];
if (abs.length >= 2) { // No two cube pairs found
i += 1;
if (i <= nNumbers) {
res.push(s3);
}
}
});
return res.map(item => parseInt(item, 10));
}
```
</section>

View File

@@ -2,16 +2,19 @@
title: Tokenize a string with escaping
id: 594faaab4e2a8626833e9c3d
challengeType: 5
videoUrl: ''
forumTopicId: 302338
localeTitle: Токенизировать строку с экранированием
---
## Description
<section id="description"><p> Напишите функцию или программу, которые могут разбивать строку на каждое неэкранированное вхождение символа разделителя. </p><p> Он должен принимать три входных параметра: </p> <b>Строка</b> Символ <b>разделителя</b> Управляющий <b>символ</b> <p> Он должен вывести список строк. </p><p> Правила разделения: </p> Поля, разделенные разделителями, становятся элементами выходного списка. Пустые поля должны быть сохранены, даже в начале и в конце. <p> Правила побега: </p> «Escaped» означает, что предшествует появление escape-символа, который еще не сбежал. Когда escape-символ предшествует персонажу, который не имеет особого значения, он по-прежнему считается побегом (но не делает ничего особенного). Каждое появление escape-символа, которое использовалось для выхода из него, не должно становиться частью выхода. <p> Продемонстрируйте, что ваша функция удовлетворяет следующему тестовому сценарию: заданная строка </p><pre> один ^ | у || три ^^^^ | четыре ^^^ | ^ куатро | </pre> и использование <pre> | </pre> как разделитель и <pre> ^ </pre> как escape-символ, ваша функция должна выводить следующий массив: <p></p><pre> [&#39;one | uno&#39;, &quot;, &#39;three ^^&#39;, &#39;four ^ | quatro&#39;,&quot;]
</pre></section>
<section id='description'>
<p> Напишите функцию или программу, которые могут разбивать строку на каждое неэкранированное вхождение символа разделителя. </p><p> Он должен принимать три входных параметра: </p> <b>Строка</b> Символ <b>разделителя</b> Управляющий <b>символ</b> <p> Он должен вывести список строк. </p><p> Правила разделения: </p> Поля, разделенные разделителями, становятся элементами выходного списка. Пустые поля должны быть сохранены, даже в начале и в конце. <p> Правила побега: </p> «Escaped» означает, что предшествует появление escape-символа, который еще не сбежал. Когда escape-символ предшествует персонажу, который не имеет особого значения, он по-прежнему считается побегом (но не делает ничего особенного). Каждое появление escape-символа, которое использовалось для выхода из него, не должно становиться частью выхода. <p> Продемонстрируйте, что ваша функция удовлетворяет следующему тестовому сценарию: заданная строка </p><pre> один ^ | у || три ^^^^ | четыре ^^^ | ^ куатро | </pre> и использование <pre> | </pre> как разделитель и <pre> ^ </pre> как escape-символ, ваша функция должна выводить следующий массив: <p></p><pre> [&#39;one | uno&#39;, &quot;, &#39;three ^^&#39;, &#39;four ^ | quatro&#39;,&quot;]
</pre>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -19,14 +22,14 @@ localeTitle: Токенизировать строку с экранирован
```yml
tests:
- text: <code>tokenize</code> - это функция.
testString: 'assert(typeof tokenize === "function", "<code>tokenize</code> is a function.");'
- text: <code>tokenize</code> должен возвращать массив.
testString: 'assert(typeof tokenize("a", "b", "c") === "object", "<code>tokenize</code> should return an array.");'
- text: '<code>tokenize(&quot;one^|uno||three^^^^|four^^^|^cuatro|&quot;, &quot;|&quot;, &quot;^&quot;)</code> должно возвращать [&quot;one | uno&quot;, &quot;&quot;, &quot;three ^^&quot; , &quot;four ^ | cuatro&quot;, &quot;&quot;] &quot;)'
testString: 'assert.deepEqual(tokenize(testStr1, "|", "^"), res1, "<code>tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") </code> should return ["one|uno", "", "three^^", "four^|cuatro", ""]");'
- text: '<code>tokenize(&quot;a@&amp;bcd&amp;ef&amp;&amp;@@hi&quot;, &quot;&amp;&quot;, &quot;@&quot;)</code> должны возвращать <code>[&quot;a&amp;bcd&quot;, &quot;ef&quot;, &quot;&quot;, &quot;@hi&quot;]</code>'
testString: 'assert.deepEqual(tokenize(testStr2, "&", "@"), res2, "<code>tokenize("a@&bcd&ef&&@@hi", "&", "@")</code> should return <code>["a&bcd", "ef", "", "@hi"]</code>");'
- text: <code>tokenize</code> is a function.
testString: assert(typeof tokenize === 'function');
- text: <code>tokenize</code> should return an array.
testString: assert(typeof tokenize('a', 'b', 'c') === 'object');
- text: <code>tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^') </code> should return <code>['one|uno', '', 'three^^', 'four^|cuatro', '']</code>
testString: assert.deepEqual(tokenize(testStr1, '|', '^'), res1);
- text: <code>tokenize('a@&bcd&ef&&@@hi', '&', '@')</code> should return <code>['a&bcd', 'ef', '', '@hi']</code>
testString: assert.deepEqual(tokenize(testStr2, '&', '@'), res2);
```
@@ -46,12 +49,17 @@ function tokenize(str, esc, sep) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testStr1 = 'one^|uno||three^^^^|four^^^|^cuatro|';
const res1 = ['one|uno', '', 'three^^', 'four^|cuatro', ''];
// TODO add more tests
const testStr2 = 'a@&bcd&ef&&@@hi';
const res2 = ['a&bcd', 'ef', '', '@hi'];
```
</div>
@@ -62,6 +70,31 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// tokenize :: String -> Character -> Character -> [String]
function tokenize(str, charDelim, charEsc) {
const dctParse = str.split('')
.reduce((a, x) => {
const blnEsc = a.esc;
const blnBreak = !blnEsc && x === charDelim;
const blnEscChar = !blnEsc && x === charEsc;
return {
esc: blnEscChar,
token: blnBreak ? '' : (
a.token + (blnEscChar ? '' : x)
),
list: a.list.concat(blnBreak ? a.token : [])
};
}, {
esc: false,
token: '',
list: []
});
return dctParse.list.concat(
dctParse.token
);
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Top rank per group
id: 595011cba5a81735713873bd
challengeType: 5
videoUrl: ''
forumTopicId: 302339
localeTitle: Высший разряд на группу
---
## Description
<section id="description"> Задача: <p> Найдите верхние N ранжированных данных в каждой группе, где N предоставляется в качестве параметра. В качестве параметра также указывается имя ранга и группы. </p> Учитывая следующие данные: <pre> [
<section id='description'>
Задача: <p> Найдите верхние N ранжированных данных в каждой группе, где N предоставляется в качестве параметра. В качестве параметра также указывается имя ранга и группы. </p> Учитывая следующие данные: <pre> [
{имя: &#39;Tyler Bennett&#39;, id: &#39;E10297&#39;, зарплата: 32000, отдел: &#39;D101&#39;},
{name: &#39;John Rappl&#39;, id: &#39;E21437&#39;, зарплата: 47000, отдел: &#39;D050&#39;},
{имя: &#39;George Woltman&#39;, id: &#39;E00127&#39;, зарплата: 53500, отдел: &#39;D101&#39;},
@@ -29,10 +30,12 @@ localeTitle: Высший разряд на группу
{name: &#39;Maze Runner&#39;, жанр: &#39;scifi&#39;, рейтинг: 7.1},
{name: &#39;Blade runner&#39;, жанр: &#39;scifi&#39;, рейтинг: 8.9}
];
</pre> можно <code>topRankPerGroup(1, data, &#39;genre&#39;, &#39;rating&#39;)</code> рейтинг фильма с самым высоким рейтингом в каждом жанре, назвав <code>topRankPerGroup(1, data, &#39;genre&#39;, &#39;rating&#39;)</code> </section>
</pre> можно <code>topRankPerGroup(1, data, &#39;genre&#39;, &#39;rating&#39;)</code> рейтинг фильма с самым высоким рейтингом в каждом жанре, назвав <code>topRankPerGroup(1, data, &#39;genre&#39;, &#39;rating&#39;)</code>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -40,20 +43,20 @@ localeTitle: Высший разряд на группу
```yml
tests:
- text: <code>topRankPerGroup</code> - это функция.
testString: 'assert(typeof topRankPerGroup === "function", "<code>topRankPerGroup</code> is a function.");'
- text: <code>topRankPerGroup</code> возвращает undefined при отрицательных значениях n.
testString: 'assert(typeof topRankPerGroup(-1, []) === "undefined", "<code>topRankPerGroup</code> returns undefined on negative n values.");'
- text: Первый отдел должен быть D050
testString: 'assert.equal(res1[0][0].dept, "D050", "First department must be D050");'
- text: Первый отдел должен быть D050
testString: 'assert.equal(res1[0][1].salary, 21900, "First department must be D050");'
- text: Последний отдел должен быть D202
testString: 'assert.equal(res1[3][3].dept, "D202", "The last department must be D202");'
- text: '<code>topRankPerGroup(1, ...)</code> должен возвращать только результат высшего рейтинга для каждой группы.'
testString: 'assert.equal(res2[2].length, 1, "<code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.");'
- text: '<code>topRankPerGroup(1, ...)</code> должен возвращать только результат высшего рейтинга для каждой группы.'
testString: 'assert.equal(res3[2][1].name, "Maze Runner", "<code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.");'
- text: <code>topRankPerGroup</code> is a function.
testString: assert(typeof topRankPerGroup === 'function');
- text: <code>topRankPerGroup</code> returns undefined on negative n values.
testString: assert(typeof topRankPerGroup(-1, []) === 'undefined');
- text: First department must be D050
testString: assert.equal(res1[0][0].dept, 'D050');
- text: First department must be D050
testString: assert.equal(res1[0][1].salary, 21900);
- text: The last department must be D202
testString: assert.equal(res1[3][3].dept, 'D202');
- text: <code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.
testString: assert.equal(res2[2].length, 1);
- text: <code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.
testString: assert.equal(res3[2][1].name, 'Maze Runner');
```
@@ -74,12 +77,39 @@ function topRankPerGroup(n, data, groupName, rankName) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const testData1 = [
{ name: 'Tyler Bennett', id: 'E10297', salary: 32000, dept: 'D101' },
{ name: 'John Rappl', id: 'E21437', salary: 47000, dept: 'D050' },
{ name: 'George Woltman', id: 'E00127', salary: 53500, dept: 'D101' },
{ name: 'Adam Smith', id: 'E63535', salary: 18000, dept: 'D202' },
{ name: 'Claire Buckman', id: 'E39876', salary: 27800, dept: 'D202' },
{ name: 'David McClellan', id: 'E04242', salary: 41500, dept: 'D101' },
{ name: 'Rich Holcomb', id: 'E01234', salary: 49500, dept: 'D202' },
{ name: 'Nathan Adams', id: 'E41298', salary: 21900, dept: 'D050' },
{ name: 'Richard Potter', id: 'E43128', salary: 15900, dept: 'D101' },
{ name: 'David Motsinger', id: 'E27002', salary: 19250, dept: 'D202' },
{ name: 'Tim Sampair', id: 'E03033', salary: 27000, dept: 'D101' },
{ name: 'Kim Arlich', id: 'E10001', salary: 57000, dept: 'D190' },
{ name: 'Timothy Grove', id: 'E16398', salary: 29900, dept: 'D190' }
];
const res1 = topRankPerGroup(10, testData1, 'dept', 'salary');
const testData2 = [
{ name: 'Friday 13th', genre: 'horror', rating: 9.9 },
{ name: "Nightmare on Elm's Street", genre: 'horror', rating: 5.7 },
{ name: 'Titanic', genre: 'drama', rating: 7.3 },
{ name: 'Maze Runner', genre: 'scifi', rating: 7.1 },
{ name: 'Blade runner', genre: 'scifi', rating: 8.9 }
];
const res2 = topRankPerGroup(1, testData2, 'genre', 'rating');
const res3 = topRankPerGroup(2, testData2, 'genre', 'rating');
```
</div>
@@ -90,6 +120,32 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
const collectDept = function (arrOfObj, groupName) {
const collect = arrOfObj.reduce((rtnObj, obj) => {
if (rtnObj[obj[groupName]] === undefined) {
rtnObj[obj[groupName]] = [];
}
rtnObj[obj[groupName]].push(obj);
return rtnObj;
}, {} // initial value to reduce
);
return Object.keys(collect).sort().map(key => collect[key]);
};
const sortRank = function (arrOfRankArrs, rankName) {
return arrOfRankArrs.map(item => item.sort((a, b) => {
if (a[rankName] > b[rankName]) { return -1; }
if (a[rankName] < b[rankName]) { return 1; }
return 0;
}));
};
function topRankPerGroup(n, data, groupName, rankName) {
if (n < 0) { return; }
return sortRank(collectDept(data, groupName),
rankName).map(list => list.slice(0, n));
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Topological sort
id: 594fa2746886f41f7d8bf225
challengeType: 5
videoUrl: ''
forumTopicId: 302340
localeTitle: Топологическая сортировка
---
## Description
<section id="description"><p> Учитывая сопоставление между элементами и элементами, на которых они зависят, <a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: топологическая сортировка">топологические</a> позиции <a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: топологическая сортировка">сортировки сортируются,</a> так что ни один элемент не предшествует элементу, от которого он зависит. </p><p> Компиляция библиотеки на языке <a href="https://en.wikipedia.org/wiki/VHDL" title="wp: VHDL">VHDL</a> имеет ограничение на то, что библиотека должна быть скомпилирована после любой библиотеки, от которой она зависит. </p> Задача: <p> Напишите функцию, которая вернет действительный порядок компиляции библиотек VHDL из их зависимостей. </p> Предположим, что имена библиотек - это одиночные слова. Пункты, упомянутые как только иждивенцы, не имеют собственных иждивенцев, но их порядок компиляции должен быть дан. Любые собственные зависимости следует игнорировать. Любые неустановимые зависимости следует игнорировать. <p> В качестве примера используйте следующие данные: </p><pre> БИБЛИОТЕЧНЫЕ БИОГРАФИЧЕСКИЕ ЗАВИСИМОСТИ
<section id='description'>
<p> Учитывая сопоставление между элементами и элементами, на которых они зависят, <a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: топологическая сортировка">топологические</a> позиции <a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: топологическая сортировка">сортировки сортируются,</a> так что ни один элемент не предшествует элементу, от которого он зависит. </p><p> Компиляция библиотеки на языке <a href="https://en.wikipedia.org/wiki/VHDL" title="wp: VHDL">VHDL</a> имеет ограничение на то, что библиотека должна быть скомпилирована после любой библиотеки, от которой она зависит. </p> Задача: <p> Напишите функцию, которая вернет действительный порядок компиляции библиотек VHDL из их зависимостей. </p> Предположим, что имена библиотек - это одиночные слова. Пункты, упомянутые как только иждивенцы, не имеют собственных иждивенцев, но их порядок компиляции должен быть дан. Любые собственные зависимости следует игнорировать. Любые неустановимые зависимости следует игнорировать. <p> В качестве примера используйте следующие данные: </p><pre> БИБЛИОТЕЧНЫЕ БИОГРАФИЧЕСКИЕ ЗАВИСИМОСТИ
======= =============================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
@@ -22,10 +23,47 @@ gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
Synopsys
</pre><p> <small>Примечание: вышеуказанные данные были бы неустановимыми, если, например, <code>dw04</code> добавляется в список зависимостей <code>dw01</code> .</small> </p> Cf: <pre> <code>&lt;a href=&quot;http://rosettacode.org/wiki/Topological sort/Extracted top item&quot; title=&quot;Topological sort/Extracted top item&quot;&gt;Topological sort/Extracted top item&lt;/a&gt;.</code> </pre><p> Существует два популярных алгоритма топологической сортировки: </p><p> Канский топологический сорт 1962 года и поиск по глубине: <a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: топологическая сортировка">топологическая сортировка</a> </p><p> Джейсон Сакс: <a href="http://www.embeddedrelated.com/showarticle/799.php" title="ссылка: http://www.embeddedrelated.com/showarticle/799.php">«Десять небольших алгоритмов, часть 4: топологическая сортировка»</a> . </p></section>
</pre><p> <small>Примечание: вышеуказанные данные были бы неустановимыми, если, например, <code>dw04</code> добавляется в список зависимостей <code>dw01</code> .</small> </p> Cf: <pre> <code>&lt;a href=&quot;http://rosettacode.org/wiki/Topological sort/Extracted top item&quot; title=&quot;Topological sort/Extracted top item&quot;&gt;Topological sort/Extracted top item&lt;/a&gt;.</code> </pre><p> Существует два популярных алгоритма топологической сортировки: </p><p> Канский топологический сорт 1962 года и поиск по глубине: <a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: топологическая сортировка">топологическая сортировка</a> </p><p> Джейсон Сакс: <a href="http://www.embeddedrelated.com/showarticle/799.php" title="ссылка: http://www.embeddedrelated.com/showarticle/799.php">«Десять небольших алгоритмов, часть 4: топологическая сортировка»</a> . </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
<ul>
<li>Assume library names are single words.</li>
<li>Items mentioned as only dependents have no dependents of their own, but their order of compiling must be given.</li>
<li>Any self dependencies should be ignored.</li>
<li>Any un-orderable dependencies should be ignored.</li>
</ul>
Use the following data as an example:
<pre>
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
</pre>
<small>Note: the above data would be un-orderable if, for example, <code>dw04</code> is added to the list of dependencies of <code>dw01</code>.</small>
<strong>C.f.:</strong>
<ul>
<li><a href="https://rosettacode.org/wiki/Topological sort/Extracted top item" title="Topological sort/Extracted top item" target="_blank">Topological sort/Extracted top item</a>.</li>
</ul>
There are two popular algorithms for topological sorting:
<ul>
<li><a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: Topological sorting" target="_blank">Kahn's 1962 topological sort</a></li>
<li><a href="https://www.embeddedrelated.com/showarticle/799.php" target="_blank">depth-first search</a></li>
</ul>
</section>
## Tests
@@ -33,16 +71,16 @@ Synopsys
```yml
tests:
- text: <code>topologicalSort</code> функция <code>topologicalSort</code> является функцией.
testString: 'assert(typeof topologicalSort === "function", "<code>topologicalSort</code> is a function.");'
- text: <code>topologicalSort</code> должен вернуть правильный порядок библиотек.
testString: 'assert.deepEqual(topologicalSort(libsSimple), ["bbb", "aaa"], "<code>topologicalSort</code> must return correct library order..");'
- text: <code>topologicalSort</code> должен вернуть правильный порядок библиотек.
testString: 'assert.deepEqual(topologicalSort(libsVHDL), solutionVHDL, "<code>topologicalSort</code> must return correct library order..");'
- text: <code>topologicalSort</code> должен вернуть правильный порядок библиотек.
testString: 'assert.deepEqual(topologicalSort(libsCustom), solutionCustom, "<code>topologicalSort</code> must return correct library order..");'
- text: <code>topologicalSort</code> должен игнорировать неупорядоченные зависимости.
testString: 'assert.deepEqual(topologicalSort(libsUnorderable), solutionUnorderable, "<code>topologicalSort</code> must ignore unorderable dependencies..");'
- text: <code>topologicalSort</code> is a function.
testString: assert(typeof topologicalSort === 'function');
- text: <code>topologicalSort</code> must return correct library order..
testString: assert.deepEqual(topologicalSort(libsSimple), ['bbb', 'aaa']);
- text: <code>topologicalSort</code> must return correct library order..
testString: assert.deepEqual(topologicalSort(libsVHDL), solutionVHDL);
- text: <code>topologicalSort</code> must return correct library order..
testString: assert.deepEqual(topologicalSort(libsCustom), solutionCustom);
- text: <code>topologicalSort</code> must ignore unorderable dependencies..
testString: assert.deepEqual(topologicalSort(libsUnorderable), solutionUnorderable);
```
@@ -63,12 +101,50 @@ function topologicalSort(libs) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const libsSimple =
`aaa bbb
bbb`;
const libsVHDL =
`des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys`;
const solutionVHDL = [
'ieee', 'std_cell_lib', 'gtech', 'dware', 'dw07', 'dw06',
'dw05', 'dw02', 'dw01', 'dw04', 'std', 'ramlib', 'synopsys',
'dw03', 'des_system_lib'
];
const libsCustom =
`a b c d
b c d
d c
c base
base`;
const solutionCustom = ['base', 'c', 'd', 'b', 'a'];
const libsUnorderable =
`TestLib Base MainLib
MainLib TestLib
Base`;
const solutionUnorderable = ['Base'];
```
</div>
@@ -79,6 +155,50 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function topologicalSort(libs) {
// A map of the input data, with the keys as the packages, and the values as
// and array of packages on which it depends.
const D = libs
.split('\n')
.map(e => e.split(' ').filter(ep => ep !== ''))
.reduce((p, c) =>
p.set(c[0], c.filter((e, i) => (i > 0 && e !== c[0] ? e : null))), new Map());
[].concat(...D.values()).forEach(e => {
D.set(e, D.get(e) || []);
});
// The above map rotated so that it represents a DAG of the form
// Map {
// A => [ A, B, C],
// B => [C],
// C => []
// }
// where each key represents a node, and the array contains the edges.
const G = [...D.keys()].reduce((p, c) =>
p.set(
c,
[...D.keys()].filter(e => D.get(e).includes(c))),
new Map()
);
// An array of leaf nodes; nodes with 0 in degrees.
const Q = [...D.keys()].filter(e => D.get(e).length === 0);
// The result array.
const S = [];
while (Q.length) {
const u = Q.pop();
S.push(u);
G.get(u).forEach(v => {
D.set(v, D.get(v).filter(e => e !== u));
if (D.get(v).length === 0) {
Q.push(v);
}
});
}
return S;
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Towers of Hanoi
id: 5951ed8945deab770972ae56
challengeType: 5
videoUrl: ''
forumTopicId: 302341
localeTitle: Башни Ханоя
---
## Description
<section id="description"> Задача: <p> Решите проблему <a href="https://en.wikipedia.org/wiki/Towers_of_Hanoi" title="wp: Towers_of_Hanoi">Башни Ханоя</a> . </p><p> Ваше решение должно принять количество дисков в качестве первых параметров и три строки, используемые для идентификации каждого из трех стеков дисков, например <code>towerOfHanoi(4, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;)</code> . Функция должна возвращать массив массивов, содержащий список ходов, source -&gt; destination. Например, массив <code>[[&#39;A&#39;, &#39;C&#39;], [&#39;B&#39;, &#39;A&#39;]]</code> указывает, что 1-й ход состоял в том, чтобы переместить диск из стека A в C, а второй шаг состоял в том, чтобы переместить диск из стека B в A. </p></section>
<section id='description'>
Задача: <p> Решите проблему <a href="https://en.wikipedia.org/wiki/Towers_of_Hanoi" title="wp: Towers_of_Hanoi">Башни Ханоя</a> . </p><p> Ваше решение должно принять количество дисков в качестве первых параметров и три строки, используемые для идентификации каждого из трех стеков дисков, например <code>towerOfHanoi(4, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;)</code> . Функция должна возвращать массив массивов, содержащий список ходов, source -&gt; destination. Например, массив <code>[[&#39;A&#39;, &#39;C&#39;], [&#39;B&#39;, &#39;A&#39;]]</code> указывает, что 1-й ход состоял в том, чтобы переместить диск из стека A в C, а второй шаг состоял в том, чтобы переместить диск из стека B в A. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
</section>
## Tests
@@ -18,16 +21,16 @@ localeTitle: Башни Ханоя
```yml
tests:
- text: <code>towerOfHanoi</code> - это функция.
testString: 'assert(typeof towerOfHanoi === "function", "<code>towerOfHanoi</code> is a function.");'
- text: '<code>towerOfHanoi(3, ...)</code> должен возвращать 7 ходов.'
testString: 'assert(res3.length === 7, "<code>towerOfHanoi(3, ...)</code> should return 7 moves.");'
- text: '<code>towerOfHanoi(3, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;)</code> должны возвращать [[«A», «B»], [«A», «C»], [«B», «C»], [ &quot;А&quot;, &quot;В&quot;], [ &quot;С&quot;, &quot;А&quot;], [ &quot;С&quot;, &quot;В&quot;], [ &quot;А&quot;, &quot;Б&quot;]]. &quot;)'
testString: 'assert.deepEqual(towerOfHanoi(3, "A", "B", "C"), res3Moves, "<code>towerOfHanoi(3, "A", "B", "C")</code> should return [["A","B"],["A","C"],["B","C"],["A","B"],["C","A"],["C","B"],["A","B"]].");'
- text: '<code>towerOfHanoi(5, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;)</code> 10-й ход должен быть Y -&gt; X.'
testString: 'assert.deepEqual(res5[9], ["Y", "X"], "<code>towerOfHanoi(5, "X", "Y", "Z")</code> 10th move should be Y -> X.");'
- text: '<code>towerOfHanoi(7, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;)</code> первые десять ходов - [[«А», «В»], [«А», «С»], [«В», «С»] , [ &quot;А&quot;, &quot;В&quot;], [ &quot;С&quot;, &quot;А&quot;], [ &quot;С&quot;, &quot;В&quot;], [ &quot;А&quot;, &quot;В&quot;], [ &quot;А&quot;, &quot;С&quot;] , [ &quot;В&quot;, &quot;С&quot;], [ &quot;В&quot;, &quot;А&quot;]] &quot;.)'
testString: 'assert.deepEqual(towerOfHanoi(7, "A", "B", "C").slice(0, 10), res7First10Moves, "<code>towerOfHanoi(7, "A", "B", "C")</code> first ten moves are [["A","B"],["A","C"],["B","C"],["A","B"],["C","A"],["C","B"],["A","B"],["A","C"],["B","C"],["B","A"]].");'
- text: <code>towerOfHanoi</code> is a function.
testString: assert(typeof towerOfHanoi === 'function');
- text: <code>towerOfHanoi(3, ...)</code> should return 7 moves.
testString: assert(res3.length === 7);
- text: <code>towerOfHanoi(3, 'A', 'B', 'C')</code> should return <code>[['A','B'], ['A','C'], ['B','C'], ['A','B'], ['C','A'], ['C','B'], ['A','B']]</code>.
testString: assert.deepEqual(towerOfHanoi(3, 'A', 'B', 'C'), res3Moves);
- text: <code>towerOfHanoi(5, "X", "Y", "Z")</code> 10th move should be Y -> X.
testString: assert.deepEqual(res5[9], ['Y', 'X']);
- text: <code>towerOfHanoi(7, 'A', 'B', 'C')</code> first ten moves are <code>[['A','B'], ['A','C'], ['B','C'], ['A','B'], ['C','A'], ['C','B'], ['A','B'], ['A','C'], ['B','C'], ['B','A']]</code>
testString: assert.deepEqual(towerOfHanoi(7, 'A', 'B', 'C').slice(0, 10), res7First10Moves);
```
@@ -39,7 +42,7 @@ tests:
<div id='js-seed'>
```js
function towerOfHanoi (n, a, b, c) {
function towerOfHanoi(n, a, b, c) {
// Good luck!
return [[]];
}
@@ -48,12 +51,15 @@ function towerOfHanoi (n, a, b, c) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const res3 = towerOfHanoi(3, 'A', 'B', 'C');
const res3Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B']];
const res5 = towerOfHanoi(5, 'X', 'Y', 'Z');
const res7First10Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['B', 'A']];
```
</div>
@@ -64,6 +70,19 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function towerOfHanoi(n, a, b, c) {
const res = [];
towerOfHanoiHelper(n, a, c, b, res);
return res;
}
function towerOfHanoiHelper(n, a, b, c, res) {
if (n > 0) {
towerOfHanoiHelper(n - 1, a, c, b, res);
res.push([a, c]);
towerOfHanoiHelper(n - 1, b, a, c, res);
}
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Vector cross product
id: 594810f028c0303b75339ad2
challengeType: 5
videoUrl: ''
forumTopicId: 302342
localeTitle: Векторный перекрестный продукт
---
## Description
<section id="description"> Вектор определяется как имеющий три измерения как представленный упорядоченным набором из трех чисел: (X, Y, Z). <p> Задача: </p><pre> <code>Write a function that takes two vectors (arrays) as input and computes their cross product.</code> </pre><p> Ваша функция должна возвращать значение <code>null</code> на недопустимые входы (т. Е. Векторы разной длины). </p><p></p></section>
<section id='description'>
Вектор определяется как имеющий три измерения как представленный упорядоченным набором из трех чисел: (X, Y, Z). <p> Задача: </p><pre> <code>Write a function that takes two vectors (arrays) as input and computes their cross product.</code> </pre><p> Ваша функция должна возвращать значение <code>null</code> на недопустимые входы (т. Е. Векторы разной длины). </p><p></p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes two vectors (arrays) as input and computes their cross product. Your function should return <code>null</code> on invalid inputs such as vectors of different lengths.
</section>
## Tests
@@ -18,12 +21,12 @@ localeTitle: Векторный перекрестный продукт
```yml
tests:
- text: dotProduct должен быть функцией
testString: 'assert.equal(typeof crossProduct, "function", "dotProduct must be a function");'
- text: dotProduct () должен возвращать значение null
testString: 'assert.equal(crossProduct(), null, "dotProduct() must return null");'
- text: 'crossProduct ([1, 2, 3], [4, 5, 6]) должен вернуться [-3, 6, -3].'
testString: 'assert.deepEqual(res12, exp12, "crossProduct([1, 2, 3], [4, 5, 6]) must return [-3, 6, -3].");'
- text: dotProduct must be a function
testString: assert.equal(typeof crossProduct, 'function');
- text: dotProduct() must return null
testString: assert.equal(crossProduct(), null);
- text: crossProduct([1, 2, 3], [4, 5, 6]) must return [-3, 6, -3].
testString: assert.deepEqual(res12, exp12);
```
@@ -35,7 +38,7 @@ tests:
<div id='js-seed'>
```js
function crossProduct() {
function crossProduct(a, b) {
// Good luck!
}
@@ -43,12 +46,15 @@ function crossProduct() {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const tv1 = [1, 2, 3];
const tv2 = [4, 5, 6];
const res12 = crossProduct(tv1, tv2);
const exp12 = [-3, 6, -3];
```
</div>
@@ -59,6 +65,22 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function crossProduct(a, b) {
if (!a || !b) {
return null;
}
// Check lengths
if (a.length !== 3 || b.length !== 3) {
return null;
}
return [
(a[1] * b[2]) - (a[2] * b[1]),
(a[2] * b[0]) - (a[0] * b[2]),
(a[0] * b[1]) - (a[1] * b[0])
];
}
```
</section>

View File

@@ -2,15 +2,18 @@
title: Vector dot product
id: 594810f028c0303b75339ad3
challengeType: 5
videoUrl: ''
forumTopicId: 302343
localeTitle: Векторный точечный продукт
---
## Description
<section id="description"><p> Вектор определяется как имеющий три измерения как представленный упорядоченным набором из трех чисел: (X, Y, Z). </p><p> Задача: </p><pre> <code>Write a function that takes any numbers of vectors (arrays) as input and computes their dot product.</code> </pre><p> Ваша функция должна возвращать значение <code>null</code> на недопустимые входы (т. Е. Векторы разной длины). </p><p></p></section>
<section id='description'>
<p> Вектор определяется как имеющий три измерения как представленный упорядоченным набором из трех чисел: (X, Y, Z). </p><p> Задача: </p><pre> <code>Write a function that takes any numbers of vectors (arrays) as input and computes their dot product.</code> </pre><p> Ваша функция должна возвращать значение <code>null</code> на недопустимые входы (т. Е. Векторы разной длины). </p><p></p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes any numbers of vectors (arrays) as input and computes their dot product. Your function should return <code>null</code> on invalid inputs such as vectors of different lengths.
</section>
## Tests
@@ -18,18 +21,18 @@ localeTitle: Векторный точечный продукт
```yml
tests:
- text: dotProduct должен быть функцией
testString: 'assert.equal(typeof dotProduct, "function", "dotProduct must be a function");'
- text: dotProduct () должен возвращать значение null
testString: 'assert.equal(dotProduct(), null, "dotProduct() must return null");'
- text: 'dotProduct ([[1], [1]]) должен возвращать 1.'
testString: 'assert.equal(dotProduct([1], [1]), 1, "dotProduct([[1], [1]]) must return 1.");'
- text: 'dotProduct ([[1], [1, 2]]) должен возвращать null.'
testString: 'assert.equal(dotProduct([1], [1, 2]), null, "dotProduct([[1], [1, 2]]) must return null.");'
- text: 'dotProduct ([1, 3, -5], [4, -2, -1]) должен вернуть 3.'
testString: 'assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3, "dotProduct([1, 3, -5], [4, -2, -1]) must return 3.");'
- text: <code>dotProduct(...nVectors)</code> должен возвращать 156000
testString: 'assert.equal(dotProduct([ 0, 1, 2, 3, 4 ], [ 0, 2, 4, 6, 8 ], [ 0, 3, 6, 9, 12 ], [ 0, 4, 8, 12, 16 ], [ 0, 5, 10, 15, 20 ]), 156000, "<code>dotProduct(...nVectors)</code> should return 156000");'
- text: dotProduct must be a function
testString: assert.equal(typeof dotProduct, 'function');
- text: dotProduct() must return null
testString: assert.equal(dotProduct(), null);
- text: dotProduct([[1], [1]]) must return 1.
testString: assert.equal(dotProduct([1], [1]), 1);
- text: dotProduct([[1], [1, 2]]) must return null.
testString: assert.equal(dotProduct([1], [1, 2]), null);
- text: dotProduct([1, 3, -5], [4, -2, -1]) must return 3.
testString: assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3);
- text: <code>dotProduct(...nVectors)</code> should return 156000
testString: assert.equal(dotProduct([ 0, 1, 2, 3, 4 ], [ 0, 2, 4, 6, 8 ], [ 0, 3, 6, 9, 12 ], [ 0, 4, 8, 12, 16 ], [ 0, 5, 10, 15, 20 ]), 156000);
```
@@ -41,7 +44,7 @@ tests:
<div id='js-seed'>
```js
function dotProduct() {
function dotProduct(...vectors) {
// Good luck!
}
@@ -49,14 +52,45 @@ function dotProduct() {
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
function dotProduct(...vectors) {
if (!vectors || !vectors.length) {
return null;
}
if (!vectors[0] || !vectors[0].length) {
return null;
}
const vectorLen = vectors[0].length;
const numVectors = vectors.length;
// If all vectors not same length, return null
for (let i = 0; i < numVectors; i++) {
if (vectors[i].length !== vectorLen) {
return null; // return undefined
}
}
let prod = 0;
let sum = 0;
let j = vectorLen;
let i = numVectors;
// Sum terms
while (j--) {
i = numVectors;
prod = 1;
while (i--) {
prod *= vectors[i][j];
}
sum += prod;
}
return sum;
}
```
</section>

View File

@@ -2,12 +2,13 @@
title: Word wrap
id: 594810f028c0303b75339ad4
challengeType: 5
videoUrl: ''
forumTopicId: 302344
localeTitle: Перенос слова
---
## Description
<section id="description"><p> Даже сегодня, с пропорциональными шрифтами и сложными макетами, все еще есть случаи, когда вам нужно обернуть текст в указанном столбце. Основная задача - обтекание абзаца текста простым способом. Пример текста: </p><pre> Оберните текст, используя более сложный алгоритм, такой как алгоритм Knuth и Plass TeX.
<section id='description'>
<p> Даже сегодня, с пропорциональными шрифтами и сложными макетами, все еще есть случаи, когда вам нужно обернуть текст в указанном столбце. Основная задача - обтекание абзаца текста простым способом. Пример текста: </p><pre> Оберните текст, используя более сложный алгоритм, такой как алгоритм Knuth и Plass TeX.
Если ваш язык предоставляет это, вы получаете легкий дополнительный кредит,
но вы «должны ссылаться на документацию», указывая на то, что алгоритм
что-то лучше, чем простой алгоритм минимальной длины.
@@ -15,10 +16,19 @@ localeTitle: Перенос слова
алгоритм. Если ваш язык предоставляет это, вы получаете легкий дополнительный кредит, но вы
должен ссылаться на документацию, указывающую, что алгоритм лучше чем
чем простой алгоритм минимальной длины.
</pre></section>
</pre>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that can wrap this text to any number of characters. As an example, the text wrapped to 80 characters should look like the following:
<pre>
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX
algorithm. If your language provides this, you get easy extra credit, but you
must reference documentation indicating that the algorithm is something better
than a simple minimum length algorithm.
</pre>
</section>
## Tests
@@ -26,18 +36,18 @@ localeTitle: Перенос слова
```yml
tests:
- text: wrap должна быть функцией.
testString: 'assert.equal(typeof wrap, "function", "wrap must be a function.");'
- text: wrap должен возвращать строку.
testString: 'assert.equal(typeof wrap("abc", 10), "string", "wrap must return a string.");'
- text: wrap (80) должен возвращать 4 строки.
testString: 'assert(wrapped80.split("\n").length === 4, "wrap(80) must return 4 lines.");'
- text: Функция <code>wrap</code> должна возвращать ожидаемый текст
testString: 'assert.equal(wrapped80.split("\n")[0], firstRow80, "Your <code>wrap</code> function should return our expected text");'
- text: wrap (42) должен возвращать 7 строк.
testString: 'assert(wrapped42.split("\n").length === 7, "wrap(42) must return 7 lines.");'
- text: Функция <code>wrap</code> должна возвращать ожидаемый текст
testString: 'assert.equal(wrapped42.split("\n")[0], firstRow42, "Your <code>wrap</code> function should return our expected text");'
- text: wrap must be a function.
testString: assert.equal(typeof wrap, 'function');
- text: wrap must return a string.
testString: assert.equal(typeof wrap('abc', 10), 'string');
- text: wrap(80) must return 4 lines.
testString: assert(wrapped80.split('\n').length === 4);
- text: Your <code>wrap</code> function should return our expected text
testString: assert.equal(wrapped80.split('\n')[0], firstRow80);
- text: wrap(42) must return 7 lines.
testString: assert(wrapped42.split('\n').length === 7);
- text: Your <code>wrap</code> function should return our expected text
testString: assert.equal(wrapped42.split('\n')[0], firstRow42);
```
@@ -49,7 +59,7 @@ tests:
<div id='js-seed'>
```js
function wrap (text, limit) {
function wrap(text, limit) {
return text;
}
@@ -57,12 +67,24 @@ function wrap (text, limit) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const text =
`Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimimum length algorithm.`;
const wrapped80 = wrap(text, 80);
const wrapped42 = wrap(text, 42);
const firstRow80 =
'Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX';
const firstRow42 = 'Wrap text using a more sophisticated';
```
</div>
@@ -73,6 +95,19 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function wrap(text, limit) {
const noNewlines = text.replace('\n', '');
if (noNewlines.length > limit) {
// find the last space within limit
const edge = noNewlines.slice(0, limit).lastIndexOf(' ');
if (edge > 0) {
const line = noNewlines.slice(0, edge);
const remainder = noNewlines.slice(edge + 1);
return line + '\n' + wrap(remainder, limit);
}
}
return text;
}
```
</section>

View File

@@ -2,15 +2,23 @@
title: Y combinator
id: 594810f028c0303b75339ad5
challengeType: 5
videoUrl: ''
forumTopicId: 302345
localeTitle: И комбинатор
---
## Description
<section id="description"><p> В строгом <a href="https://en.wikipedia.org/wiki/Functional programming" title="wp: функциональное программирование">функциональном программировании</a> и <a href="https://en.wikipedia.org/wiki/lambda calculus" title="wp: лямбда-исчисление">исчислении лямбда</a> функции (лямбда-выражения) не имеют состояния и могут быть разрешены только к аргументам включенных функций. Это исключает обычное определение рекурсивной функции, в которой функция связана с состоянием переменной, и состояние этой переменной используется в теле функции. </p><p> <a href="http://mvanier.livejournal.com/2897.html">Комбинатор Y</a> сам по себе является функцией без состояния, которая при применении к другой функции без сохранения возвращает рекурсивную версию функции. Комбинатор Y является простейшим из класса таких функций, называемых <a href="https://en.wikipedia.org/wiki/Fixed-point combinator" title="wp: комбинатор с фиксированной запятой">комбинаторами с фиксированной запятой</a> . </p> Задача: <pre> <code>Define the stateless Y combinator function and use it to compute &lt;a href=&quot;https://en.wikipedia.org/wiki/Factorial&quot; title=&quot;wp: factorial&quot;&gt;factorial&lt;/a&gt;.</code> </pre><p> Функция <code>factorial(N)</code> уже предоставлена ​​вам. См. Также <a href="http://vimeo.com/45140590">Джим Вейрих: Приключения в функциональном программировании</a> . </p></section>
<section id='description'>
<p> В строгом <a href="https://en.wikipedia.org/wiki/Functional programming" title="wp: функциональное программирование">функциональном программировании</a> и <a href="https://en.wikipedia.org/wiki/lambda calculus" title="wp: лямбда-исчисление">исчислении лямбда</a> функции (лямбда-выражения) не имеют состояния и могут быть разрешены только к аргументам включенных функций. Это исключает обычное определение рекурсивной функции, в которой функция связана с состоянием переменной, и состояние этой переменной используется в теле функции. </p><p> <a href="http://mvanier.livejournal.com/2897.html">Комбинатор Y</a> сам по себе является функцией без состояния, которая при применении к другой функции без сохранения возвращает рекурсивную версию функции. Комбинатор Y является простейшим из класса таких функций, называемых <a href="https://en.wikipedia.org/wiki/Fixed-point combinator" title="wp: комбинатор с фиксированной запятой">комбинаторами с фиксированной запятой</a> . </p> Задача: <pre> <code>Define the stateless Y combinator function and use it to compute &lt;a href=&quot;https://en.wikipedia.org/wiki/Factorial&quot; title=&quot;wp: factorial&quot;&gt;factorial&lt;/a&gt;.</code> </pre><p> Функция <code>factorial(N)</code> уже предоставлена ​​вам. См. Также <a href="http://vimeo.com/45140590">Джим Вейрих: Приключения в функциональном программировании</a> . </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Define the stateless Y combinator function and use it to compute <a href="https://en.wikipedia.org/wiki/Factorial" title="wp: factorial" target="_blank">factorial</a>. The <code>factorial(N)</code> function is already given to you.
<strong>See also:</strong>
<ul>
<li><a href="https://vimeo.com/45140590" target="_blank">Jim Weirich: Adventures in Functional Programming</a>.</li>
</ul>
</section>
## Tests
@@ -18,18 +26,18 @@ localeTitle: И комбинатор
```yml
tests:
- text: Y должен возвращать функцию
testString: 'assert.equal(typeof Y(f => n => n), "function", "Y must return a function");'
- text: factorial (1) должен возвращать 1.
testString: 'assert.equal(factorial(1), 1, "factorial(1) must return 1.");'
- text: factorial (2) должен вернуть 2.
testString: 'assert.equal(factorial(2), 2, "factorial(2) must return 2.");'
- text: факториал (3) должен возвращать 6.
testString: 'assert.equal(factorial(3), 6, "factorial(3) must return 6.");'
- text: факториал (4) должен возвращать 24.
testString: 'assert.equal(factorial(4), 24, "factorial(4) must return 24.");'
- text: factorial (10) должен вернуть 3628800.
testString: 'assert.equal(factorial(10), 3628800, "factorial(10) must return 3628800.");'
- text: Y must return a function
testString: assert.equal(typeof Y(f => n => n), 'function');
- text: factorial(1) must return 1.
testString: assert.equal(factorial(1), 1);
- text: factorial(2) must return 2.
testString: assert.equal(factorial(2), 2);
- text: factorial(3) must return 6.
testString: assert.equal(factorial(3), 6);
- text: factorial(4) must return 24.
testString: assert.equal(factorial(4), 24);
- text: factorial(10) must return 3628800.
testString: assert.equal(factorial(10), 3628800);
```
@@ -57,12 +65,12 @@ var factorial = Y(function(f) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
var factorial = Y(f => n => (n > 1 ? n * f(n - 1) : 1));
```
</div>
@@ -73,6 +81,7 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
var Y = f => (x => x(x))(y => f(x => y(y)(x)));
```
</section>

View File

@@ -2,15 +2,18 @@
title: Zeckendorf number representation
id: 594810f028c0303b75339ad6
challengeType: 5
videoUrl: ''
forumTopicId: 302346
localeTitle: Отметить номер деревни
---
## Description
<section id="description"><p> Подобно тому, как числа могут быть представлены в позиционной нотации как суммы кратных степеням десяти (десятичных) или двух (двоичных); все положительные целые числа могут быть представлены в виде суммы одного или нулевого числа отдельных членов ряда Фибоначчи. </p><p> Напомним, что первые шесть различных чисел Фибоначчи: <code>1, 2, 3, 5, 8, 13</code> . Десятичное число одиннадцать может быть записано как <code>0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1</code> или <code>010100</code> в позиционной нотации, где столбцы представляют собой умножение на определенный член последовательности. Ведущие нули отбрасываются так, что 11 десятичных знаков становятся <code>10100</code> . </p><p> 10100 - не единственный способ сделать 11 из чисел Фибоначчи, однако <code>0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1</code> или 010011 также будет представлять десятичную 11. Для истинного числа Зеекендорфа существует дополнительное ограничение, что «нельзя использовать два последовательных числа Фибоначчи», что приводит к первому уникальному решению. </p><p> Задача: Напишите функцию, которая генерирует и возвращает массив первых чисел N Zeckendorf по порядку. </p></section>
<section id='description'>
<p> Подобно тому, как числа могут быть представлены в позиционной нотации как суммы кратных степеням десяти (десятичных) или двух (двоичных); все положительные целые числа могут быть представлены в виде суммы одного или нулевого числа отдельных членов ряда Фибоначчи. </p><p> Напомним, что первые шесть различных чисел Фибоначчи: <code>1, 2, 3, 5, 8, 13</code> . Десятичное число одиннадцать может быть записано как <code>0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1</code> или <code>010100</code> в позиционной нотации, где столбцы представляют собой умножение на определенный член последовательности. Ведущие нули отбрасываются так, что 11 десятичных знаков становятся <code>10100</code> . </p><p> 10100 - не единственный способ сделать 11 из чисел Фибоначчи, однако <code>0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1</code> или 010011 также будет представлять десятичную 11. Для истинного числа Зеекендорфа существует дополнительное ограничение, что «нельзя использовать два последовательных числа Фибоначчи», что приводит к первому уникальному решению. </p><p> Задача: Напишите функцию, которая генерирует и возвращает массив первых чисел N Zeckendorf по порядку. </p>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that generates and returns an array of the first <code>n</code> Zeckendorf numbers in order.
</section>
## Tests
@@ -18,10 +21,10 @@ localeTitle: Отметить номер деревни
```yml
tests:
- text: zeckendorf должен функционировать
testString: 'assert.equal(typeof zeckendorf, "function", "zeckendorf must be function");'
- text: Ваша функция <code>zeckendorf</code> должна вернуть правильный ответ
testString: 'assert.deepEqual(answer, solution20, "Your <code>zeckendorf</code> function should return the correct answer");'
- text: zeckendorf must be function
testString: assert.equal(typeof zeckendorf, 'function');
- text: Your <code>zeckendorf</code> function should return the correct answer
testString: assert.deepEqual(answer, solution20);
```
@@ -41,12 +44,24 @@ function zeckendorf(n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const range = (m, n) => (
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i)
);
const solution20 = [
'1', '10', '100', '101', '1000', '1001', '1010', '10000', '10001',
'10010', '10100', '10101', '100000', '100001', '100010', '100100', '100101',
'101000', '101001', '101010'
];
const answer = range(1, 20).map(zeckendorf);
```
</div>
@@ -57,6 +72,44 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
// zeckendorf :: Int -> String
function zeckendorf(n) {
const f = (m, x) => (m < x ? [m, 0] : [m - x, 1]);
return (n === 0 ? ([0]) :
mapAccumL(f, n, reverse(
tail(fibUntil(n))
))[1]).join('');
}
// fibUntil :: Int -> [Int]
let fibUntil = n => {
const xs = [];
until(
([a]) => a > n,
([a, b]) => (xs.push(a), [b, a + b]), [1, 1]
);
return xs;
};
let mapAccumL = (f, acc, xs) => (
xs.reduce((a, x) => {
const pair = f(a[0], x);
return [pair[0], a[1].concat(pair[1])];
}, [acc, []])
);
let until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
const tail = xs => (
xs.length ? xs.slice(1) : undefined
);
const reverse = xs => xs.slice(0).reverse();
```
</section>

View File

@@ -2,12 +2,13 @@
title: Zhang-Suen thinning algorithm
id: 594810f028c0303b75339ad7
challengeType: 5
videoUrl: ''
forumTopicId: 302347
localeTitle: Алгоритм прореживания Чжан-Суен
---
## Description
<section id="description"> Это алгоритм, используемый для тонкого черно-белого изображения, т.е. одного бита на пиксель. Например, с входным изображением: <pre> ###############################
<section id='description'>
Это алгоритм, используемый для тонкого черно-белого изображения, т.е. одного бита на пиксель. Например, с входным изображением: <pre> ###############################
#####################################
#########################################################################
######## ############################
@@ -57,10 +58,12 @@ localeTitle: Алгоритм прореживания Чжан-Суен
Задача:
Напишите рутину, чтобы прореживать Чжан-Суен на матрице изображений единиц и нулей.
</p>
</pre></section>
</pre>
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a routine to perform Zhang-Suen thinning on the provided image matrix.
</section>
## Tests
@@ -68,14 +71,14 @@ localeTitle: Алгоритм прореживания Чжан-Суен
```yml
tests:
- text: <code>thinImage</code> должна быть функцией
testString: 'assert.equal(typeof thinImage, "function", "<code>thinImage</code> must be a function");'
- text: <code>thinImage</code> должен возвращать массив
testString: 'assert(Array.isArray(result), "<code>thinImage</code> must return an array");'
- text: <code>thinImage</code> должен возвращать массив строк
testString: 'assert.equal(typeof result[0], "string", "<code>thinImage</code> must return an array of strings");'
- text: <code>thinImage</code> должен возвращать массив строк
testString: 'assert.deepEqual(result, expected, "<code>thinImage</code> must return an array of strings");'
- text: <code>thinImage</code> must be a function
testString: assert.equal(typeof thinImage, 'function');
- text: <code>thinImage</code> must return an array
testString: assert(Array.isArray(result));
- text: <code>thinImage</code> must return an array of strings
testString: assert.equal(typeof result[0], 'string');
- text: <code>thinImage</code> must return an array of strings
testString: assert.deepEqual(result, expected);
```
@@ -115,12 +118,51 @@ function thinImage(image) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const imageForTests = [
' ',
' ################# ############# ',
' ################## ################ ',
' ################### ################## ',
' ######## ####### ################### ',
' ###### ####### ####### ###### ',
' ###### ####### ####### ',
' ################# ####### ',
' ################ ####### ',
' ################# ####### ',
' ###### ####### ####### ',
' ###### ####### ####### ',
' ###### ####### ####### ###### ',
' ######## ####### ################### ',
' ######## ####### ###### ################## ###### ',
' ######## ####### ###### ################ ###### ',
' ######## ####### ###### ############# ###### ',
' '];
const expected = [
' ',
' ',
' # ########## ####### ',
' ## # #### # ',
' # # ## ',
' # # # ',
' # # # ',
' # # # ',
' ############ # ',
' # # # ',
' # # # ',
' # # # ',
' # # # ',
' # ## ',
' # ############ ',
' ### ### ',
' ',
' '
];
const result = thinImage(imageForTests);
```
</div>
@@ -131,6 +173,114 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function Point(x, y) {
this.x = x;
this.y = y;
}
const ZhangSuen = (function () {
function ZhangSuen() {
}
ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]];
ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]];
ZhangSuen.toWhite = [];
ZhangSuen.main = function (image) {
ZhangSuen.grid = new Array(image);
for (let r = 0; r < image.length; r++) {
ZhangSuen.grid[r] = image[r].split('');
}
ZhangSuen.thinImage();
return ZhangSuen.getResult();
};
ZhangSuen.thinImage = function () {
let firstStep = false;
let hasChanged;
do {
hasChanged = false;
firstStep = !firstStep;
for (let r = 1; r < ZhangSuen.grid.length - 1; r++) {
for (let c = 1; c < ZhangSuen.grid[0].length - 1; c++) {
if (ZhangSuen.grid[r][c] !== '#') {
continue;
}
const nn = ZhangSuen.numNeighbors(r, c);
if (nn < 2 || nn > 6) {
continue;
}
if (ZhangSuen.numTransitions(r, c) !== 1) {
continue;
}
if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) {
continue;
}
ZhangSuen.toWhite.push(new Point(c, r));
hasChanged = true;
}
}
for (let i = 0; i < ZhangSuen.toWhite.length; i++) {
const p = ZhangSuen.toWhite[i];
ZhangSuen.grid[p.y][p.x] = ' ';
}
ZhangSuen.toWhite = [];
} while ((firstStep || hasChanged));
};
ZhangSuen.numNeighbors = function (r, c) {
let count = 0;
for (let i = 0; i < ZhangSuen.nbrs.length - 1; i++) {
if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#') {
count++;
}
}
return count;
};
ZhangSuen.numTransitions = function (r, c) {
let count = 0;
for (let i = 0; i < ZhangSuen.nbrs.length - 1; i++) {
if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') {
if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#') {
count++;
}
}
}
return count;
};
ZhangSuen.atLeastOneIsWhite = function (r, c, step) {
let count = 0;
const group = ZhangSuen.nbrGroups[step];
for (let i = 0; i < 2; i++) {
for (let j = 0; j < group[i].length; j++) {
const nbr = ZhangSuen.nbrs[group[i][j]];
if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') {
count++;
break;
}
}
}
return count > 1;
};
ZhangSuen.getResult = function () {
const result = [];
for (let i = 0; i < ZhangSuen.grid.length; i++) {
const row = ZhangSuen.grid[i].join('');
result.push(row);
}
return result;
};
return ZhangSuen;
}());
function thinImage(image) {
return ZhangSuen.main(image);
}
```
</section>

View File

@@ -2,20 +2,23 @@
title: Zig-zag matrix
id: 594810f028c0303b75339ad8
challengeType: 5
videoUrl: ''
forumTopicId: 302348
localeTitle: Зигзагообразная матрица
---
## Description
<section id="description"> Массив «зиг-зага» квадратное расположение первого $ N ^ 2 $, где целых число увеличения последовательно , как вы зигзагообразный вдоль массива <a href="https://en.wiktionary.org/wiki/antidiagonal">анти-диагоналей</a> . Например, с учетом «5», создайте этот массив: <pre> 0 1 5 6 14
<section id='description'>
Массив «зиг-зага» квадратное расположение первого $ N ^ 2 $, где целых число увеличения последовательно , как вы зигзагообразный вдоль массива <a href="https://en.wiktionary.org/wiki/antidiagonal">анти-диагоналей</a> . Например, с учетом «5», создайте этот массив: <pre> 0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
</pre> Напишите функцию, которая принимает размер матрицы зигзага, и возвращает соответствующую матрицу в виде двумерного массива. </section>
</pre> Напишите функцию, которая принимает размер матрицы зигзага, и возвращает соответствующую матрицу в виде двумерного массива.
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
Write a function that takes the size of the zig-zag matrix, and returns the corresponding matrix as two-dimensional array.
</section>
## Tests
@@ -23,18 +26,18 @@ localeTitle: Зигзагообразная матрица
```yml
tests:
- text: ZigZagMatrix должна быть функцией
testString: 'assert.equal(typeof ZigZagMatrix, "function", "ZigZagMatrix must be a function");'
- text: ZigZagMatrix должен возвращать массив
testString: 'assert.equal(typeof ZigZagMatrix(1), "object", "ZigZagMatrix should return array");'
- text: ZigZagMatrix должен возвращать массив массивов гнезд
testString: 'assert.equal(typeof ZigZagMatrix(1)[0], "object", "ZigZagMatrix should return an array of nestes arrays");'
- text: 'ZigZagMatrix (1) должен возвращать [[0]]'
testString: 'assert.deepEqual(ZigZagMatrix(1), zm1, "ZigZagMatrix(1) should return [[0]]");'
- text: 'ZigZagMatrix (2) должен возвращать [[0, 1], [2, 3]]'
testString: 'assert.deepEqual(ZigZagMatrix(2), zm2, "ZigZagMatrix(2) should return [[0, 1], [2, 3]]");'
- text: ZigZagMatrix (5) должен возвращать заданную матрицу
testString: 'assert.deepEqual(ZigZagMatrix(5), zm5, "ZigZagMatrix(5) must return specified matrix");'
- text: ZigZagMatrix must be a function
testString: assert.equal(typeof ZigZagMatrix, 'function');
- text: ZigZagMatrix should return array
testString: assert.equal(typeof ZigZagMatrix(1), 'object');
- text: ZigZagMatrix should return an array of nested arrays
testString: assert.equal(typeof ZigZagMatrix(1)[0], 'object');
- text: ZigZagMatrix(1) should return [[0]]
testString: assert.deepEqual(ZigZagMatrix(1), zm1);
- text: ZigZagMatrix(2) should return [[0, 1], [2, 3]]
testString: assert.deepEqual(ZigZagMatrix(2), zm2);
- text: ZigZagMatrix(5) must return specified matrix
testString: assert.deepEqual(ZigZagMatrix(5), zm5);
```
@@ -55,12 +58,20 @@ function ZigZagMatrix(n) {
</div>
### After Test
### After Tests
<div id='js-teardown'>
```js
console.info('after the test');
const zm1 = [[0]];
const zm2 = [[0, 1], [2, 3]];
const zm5 = [
[0, 1, 5, 6, 14],
[2, 4, 7, 13, 15],
[3, 8, 12, 16, 21],
[9, 11, 17, 20, 22],
[10, 18, 19, 23, 24]
];
```
</div>
@@ -71,6 +82,30 @@ console.info('after the test');
<section id='solution'>
```js
// solution required
function ZigZagMatrix(n) {
const mtx = [];
for (let i = 0; i < n; i++) {
mtx[i] = [];
}
let i = 1;
let j = 1;
for (let e = 0; e < n * n; e++) {
mtx[i - 1][j - 1] = e;
if ((i + j) % 2 === 0) {
// Even stripes
if (j < n) j++;
else i += 2;
if (i > 1) i--;
} else {
// Odd stripes
if (i < n) i++;
else j += 2;
if (j > 1) j--;
}
}
return mtx;
}
```
</section>