chore(curriculum): Remove files in wrong format

This commit is contained in:
Bouncey
2018-10-04 14:37:37 +01:00
committed by Stuart Taylor
parent 61222b1fb6
commit 8f39bc1288
2947 changed files with 118541 additions and 212907 deletions

View File

@ -0,0 +1,78 @@
---
title: 100 doors
id: 594810f028c0303b75339acb
challengeType: 5
---
## Description
<section id='description'>
<p>There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and 'toggle' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (i.e., door #2, #4, #6, ...) and toggle it. The third time, visit every 3rd door (i.e., door #3, #6, #9, ...), etc., until you only visit the 100th door.</p>
<p>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.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getFinalOpenedDoors</code> is a function.
testString: 'assert(typeof getFinalOpenedDoors === ''function'', ''<code>getFinalOpenedDoors</code> is a function.'');'
- text: <code>getFinalOpenedDoors</code> should return an array.
testString: 'assert(Array.isArray(getFinalOpenedDoors(100)), ''<code>getFinalOpenedDoors</code> should return an array.'');'
- text: <code>getFinalOpenedDoors</code> did not produce the correct results.
testString: 'assert.deepEqual(getFinalOpenedDoors(100), solution, ''<code>getFinalOpenedDoors</code> did not produce the correct results.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getFinalOpenedDoors (numDoors) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,155 @@
---
title: 24 game
id: 5951e88f64ebf159166a1176
challengeType: 5
---
## Description
<section id='description'>
<p>Implement a function that takes a string of four digits as its argument, with each digit from 1 ──► 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."</p>
<p>Rules:</p>
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
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).
The order of the digits when given does not have to be preserved.
<p>Example inputs:</p>
<code>solve24("4878");</code>
<code>solve24("1234");</code>
<code>solve24("6789");</code>
<code>solve24("1127");</code>
<p>Example outputs (strings):</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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>solve24</code> is a function.
testString: 'assert(typeof solve24 === ''function'', ''<code>solve24</code> is a 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])), ''<code>solve24("4878")</code> should return <code>(7-8/8)*4</code> or <code>4*(7-8/8)</code>'');'
- text: <code>solve24("1234")</code> should return any arrangement of <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("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])), ''<code>solve24("6789")</code> should return <code>(6*8)/(9-7)</code> or <code>(8*6)/(9-7)</code>'');'
- text: <code>solve24("1127")</code> should return a permutation of <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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function solve24 (numStr) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,102 @@
---
title: 9 billion names of God the integer
id: 5949b579404977fbaefcd736
challengeType: 5
---
## Description
<section id='description'>
<p>This task is a variation of the <a href="https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary" title="wp: The Nine Billion Names of God#Plot_summary">short story by Arthur C. Clarke</a>.</p>
<p>(Solvers should be aware of the consequences of completing this task.)</p>
<p>In detail, to specify what is meant by a “name”:</p>
<p>The integer 1 has 1 name “1”.</p>
<p>The integer 2 has 2 names “1+1”, and “2”.</p>
<p>The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.</p>
<p>The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.</p>
<p>The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.</p>
<p>This can be visualized in the following form:</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>Where row $n$ corresponds to integer $n$, and each column $C$ in row $m$ from left to right corresponds to the number of names beginning with $C$.</p>
<p>Optionally note that the sum of the $n$-th row $P(n)$ is the <a href="http://mathworld.wolfram.com/PartitionFunctionP.html" title="link: http://mathworld.wolfram.com/PartitionFunctionP.html">integer partition function</a>.</p>
Task
<p>Implement a function that returns the sum of the $n$-th row.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>numberOfNames</code> is a function.
testString: 'assert(typeof numberOfNames === ''function'', ''<code>numberOfNames</code> is a function.'');'
- text: <code>numberOfNames(5)</code> should equal 7.
testString: 'assert.equal(numberOfNames(5), 7, ''<code>numberOfNames(5)</code> should equal 7.'');'
- text: <code>numberOfNames(12)</code> should equal 77.
testString: 'assert.equal(numberOfNames(12), 77, ''<code>numberOfNames(12)</code> should equal 77.'');'
- text: <code>numberOfNames(18)</code> should equal 385.
testString: 'assert.equal(numberOfNames(18), 385, ''<code>numberOfNames(18)</code> should equal 385.'');'
- text: <code>numberOfNames(23)</code> should equal 1255.
testString: 'assert.equal(numberOfNames(23), 1255, ''<code>numberOfNames(23)</code> should equal 1255.'');'
- text: <code>numberOfNames(42)</code> should equal 53174.
testString: 'assert.equal(numberOfNames(42), 53174, ''<code>numberOfNames(42)</code> should equal 53174.'');'
- text: <code>numberOfNames(123)</code> should equal 2552338241.
testString: 'assert.equal(numberOfNames(123), 2552338241, ''<code>numberOfNames(123)</code> should equal 2552338241.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function numberOfNames (num) {
// Good luck!
return true;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,121 @@
---
title: ABC Problem
id: 594810f028c0303b75339acc
challengeType: 5
---
## Description
<section id='description'>
<p>You are given a collection of ABC blocks (e.g., childhood alphabet blocks). There are 20 blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:</p>
<p>(B O)</p>
<p>(X K)</p>
<p>(D Q)</p>
<p>(C P)</p>
<p>(N A)</p>
<p>(G T)</p>
<p>(R E)</p>
<p>(T G)</p>
<p>(Q D)</p>
<p>(F S)</p>
<p>(J W)</p>
<p>(H U)</p>
<p>(V I)</p>
<p>(A N)</p>
<p>(O B)</p>
<p>(E R)</p>
<p>(F S)</p>
<p>(L Y)</p>
<p>(P C)</p>
<p>(Z M)</p>
<p>Some rules to keep in mind:</p>
Once a letter on a block is used, that block cannot be used again.
The function should be case-insensitive.
<p>Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>canMakeWord</code> is a function.
testString: 'assert(typeof canMakeWord === ''function'', ''<code>canMakeWord</code> is a function.'');'
- text: <code>canMakeWord</code> should return a boolean.
testString: 'assert(typeof canMakeWord(''hi'') === ''boolean'', ''<code>canMakeWord</code> should return a boolean.'');'
- text: <code>canMakeWord("bark")</code> should return true.
testString: 'assert(canMakeWord(words[0]), ''<code>canMakeWord("bark")</code> should return true.'');'
- text: <code>canMakeWord("BooK")</code> should return false.
testString: 'assert(!canMakeWord(words[1]), ''<code>canMakeWord("BooK")</code> should return false.'');'
- text: <code>canMakeWord("TReAT")</code> should return true.
testString: 'assert(canMakeWord(words[2]), ''<code>canMakeWord("TReAT")</code> should return true.'');'
- text: <code>canMakeWord("COMMON")</code> should return false.
testString: 'assert(!canMakeWord(words[3]), ''<code>canMakeWord("COMMON")</code> should return false.'');'
- text: <code>canMakeWord("squAD")</code> should return true.
testString: 'assert(canMakeWord(words[4]), ''<code>canMakeWord("squAD")</code> should return true.'');'
- text: <code>canMakeWord("conFUSE")</code> should return true.
testString: 'assert(canMakeWord(words[5]), ''<code>canMakeWord("conFUSE")</code> should return true.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function canMakeWord (word) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,93 @@
---
title: 'Abundant, deficient and perfect number classifications'
id: 594810f028c0303b75339acd
challengeType: 5
---
## Description
<section id='description'>
<p>These define three classifications of positive integers based on their <a href="http://rosettacode.org/wiki/Proper divisors" title="Proper divisors">proper divisors</a>.</p>
<p>Let $P(n)$ be the sum of the proper divisors of n where proper divisors are all positive integers n other than n itself.</p>
<p>If <code>P(n) < n</code> then n is classed as "deficient"</p>
<p>If <code>P(n) === n</code> then n is classed as "perfect"</p>
<p>If <code>P(n) > n</code> then n is classed as "abundant"</p>
<p>Example:</p>
<p>6 has proper divisors of 1, 2, and 3.</p>
<p>1 + 2 + 3 = 6, so 6 is classed as a perfect number.</p>
<p>Implement a function that calculates how many of the integers from 1 to 20,000 (inclusive) are in each of the three classes. Output the result as an array in the following format <code>[deficient, perfect, abundant]</code>.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getDPA</code> is a function.
testString: 'assert(typeof getDPA === ''function'', ''<code>getDPA</code> is a function.'');'
- text: <code>getDPA</code> should return an array.
testString: 'assert(Array.isArray(getDPA(100)), ''<code>getDPA</code> should return an array.'');'
- text: <code>getDPA</code> return value should have a length of 3.
testString: 'assert(getDPA(100).length === 3, ''<code>getDPA</code> return value should have a length of 3.'');'
- text: '<code>getDPA(20000)</code> should equal [15043, 4, 4953]'
testString: 'assert.deepEqual(getDPA(20000), solution, ''<code>getDPA(20000)</code> should equal [15043, 4, 4953]'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getDPA (num) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,77 @@
---
title: Accumulator factory
id: 594810f028c0303b75339ace
challengeType: 5
---
## Description
<section id='description'>
<p>Create a function that takes a single (numeric) argument and returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).</p>
<p>Rules:</p>
<p>Do not use global variables.</p>
<p>Hint:</p>
<p>Closures save outer state.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>accumulator</code> is a function.
testString: 'assert(typeof accumulator === ''function'', ''<code>accumulator</code> is a function.'');'
- text: <code>accumulator(0)</code> should return a function.
testString: 'assert(typeof accumulator(0) === ''function'', ''<code>accumulator(0)</code> should return a function.'');'
- text: <code>accumulator(0)(2)</code> should return a number.
testString: 'assert(typeof accumulator(0)(2) === ''number'', ''<code>accumulator(0)(2)</code> should return a number.'');'
- text: 'Passing in the values 3, -4, 1.5, and 5 should return 5.5.'
testString: 'assert(testFn(5) === 5.5, ''Passing in the values 3, -4, 1.5, and 5 should return 5.5.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function accumulator (sum) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function accumulator (sum) {
return function (n) {
return sum += n;
};
}
```
</section>

View File

@ -0,0 +1,73 @@
---
title: Ackermann function
id: 594810f028c0303b75339acf
challengeType: 5
---
## Description
<section id='description'>
<p>The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.</p>
<p>The Ackermann function is usually defined as follows:</p>
$$A(m, n) =
\begin{cases}
n+1 & \mbox{if } m = 0 \\
A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\
A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0.
\end{cases}$$
<p>Its arguments are never negative and it always terminates. Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>ack</code> is a function.
testString: 'assert(typeof ack === ''function'', ''<code>ack</code> is a function.'');'
- text: '<code>ack(0, 0)</code> should return 1.'
testString: 'assert(ack(0, 0) === 1, ''<code>ack(0, 0)</code> should return 1.'');'
- text: '<code>ack(1, 1)</code> should return 3.'
testString: 'assert(ack(1, 1) === 3, ''<code>ack(1, 1)</code> should return 3.'');'
- text: '<code>ack(2, 5)</code> should return 13.'
testString: 'assert(ack(2, 5) === 13, ''<code>ack(2, 5)</code> should return 13.'');'
- text: '<code>ack(3, 3)</code> should return 61.'
testString: 'assert(ack(3, 3) === 61, ''<code>ack(3, 3)</code> should return 61.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function ack (m, n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function ack (m, n) {
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
}
```
</section>

View File

@ -0,0 +1,152 @@
---
title: Align columns
id: 594810f028c0303b75339ad0
challengeType: 5
---
## Description
<section id='description'>
<p>Given a text file of many lines, where fields within a line are delineated by a single <code>$</code> 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.</p>
<p>Use the following text to test your programs:</p>
<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>
<p>Note that:</p>
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>formatText</code> is a function.
testString: 'assert(typeof formatText === ''function'', ''<code>formatText</code> is a function.'');'
- text: '<code>formatText</code> with the above input and "right" justification should produce the following: '
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> with the above input and "left" justification should produce the following: '
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> with the above input and "center" justification should produce the following: '
testString: 'assert.strictEqual(formatText(testInput, ''center''), centerAligned, ''<code>formatText</code> with the above input and "center" justification should produce the following: '');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
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.'
];
function formatText (input, justification) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,118 @@
---
title: Amicable pairs
id: 5949b579404977fbaefcd737
challengeType: 5
---
## Description
<section id='description'>
Two integers $N$ and $M$ are said to be <a href="https://en.wikipedia.org/wiki/Amicable numbers" title="wp: Amicable numbers">amicable pairs</a> if $N \neq M$ and the sum of the <a href="http://rosettacode.org/wiki/Proper divisors" title="Proper divisors">proper divisors</a> of $N$ ($\mathrm{sum}(\mathrm{propDivs}(N))$) $= M$ as well as $\mathrm{sum}(\mathrm{propDivs}(M)) = N$.
Example:
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task:
Calculate and show here the Amicable pairs below 20,000 (there are eight).
Related tasks
<a href="http://rosettacode.org/wiki/Proper divisors" title="Proper divisors">Proper divisors</a>
<a href="http://rosettacode.org/wiki/Abundant, deficient and perfect number classifications" title="Abundant, deficient and perfect number classifications">Abundant, deficient and perfect number classifications</a>
<a href="http://rosettacode.org/wiki/Aliquot sequence classifications" title="Aliquot sequence classifications">Aliquot sequence classifications</a> and its amicable classification.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>amicablePairsUpTo</code> is a function.
testString: 'assert(typeof amicablePairsUpTo === ''function'', ''<code>amicablePairsUpTo</code> is a function.'');'
- text: '<code>amicablePairsUpTo(300)</code> should return <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> should return <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> 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, ''<code>amicablePairsUpTo(20000)</code> should return <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function amicablePairsUpTo (maxNum) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,88 @@
---
title: Averages-Mode
id: 594d8d0ab97724821379b1e6
challengeType: 5
---
## Description
<section id='description'>
<p>Write a program to find the <a href="https://en.wikipedia.org/wiki/Mode (statistics)" title="wp: Mode (statistics)">mode</a> value of a collection.</p><p>The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.</p><p>If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>mode</code> is a function.
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> should equal <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> should equal <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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function mode (arr) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,138 @@
---
title: Averages-Pythagorean means
id: 594d966a1467eb84194f0086
challengeType: 5
---
## Description
<section id='description'>
<p class='rosetta__paragraph'>Compute all three of the <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Pythagorean means' title='wp: Pythagorean means'>Pythagorean means</a> of the set of integers <big>1</big> through <big>10</big> (inclusive).</p><p class='rosetta__paragraph'>Show that <big>$A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n)$</big> for this set of positive integers.</p> The most common of the three means, the <a class='rosetta__link--rosetta' href='http://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean'>arithmetic mean</a>, is the sum of the list divided by its length: <big>$ A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n}$</big>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean'>geometric mean</a> is the $n$th root of the product of the list: <big>$ G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n} $</big>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean'>harmonic mean</a> is $n$ divided by the sum of the reciprocal of each item in the list: <big>$ H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} $</big>
<p class='rosetta__paragraph'>Assume the input is an ordered array of all inclusive numbers.</p>
<p class='rosetta__paragraph'>For the answer, please output an object in the following format:</p>
<pre class='rosetta__pre'>
{
values: {
Arithmetic: 5.5,
Geometric: 4.528728688116765,
Harmonic: 3.414171521474055
},
test: 'is A >= G >= H ? yes'
}
</pre>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>pythagoreanMeans</code> is a function.
testString: 'assert(typeof pythagoreanMeans === ''function'', ''<code>pythagoreanMeans</code> is a function.'');'
- text: '<code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.'
testString: 'assert.deepEqual(pythagoreanMeans(range1), answer1, ''<code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function pythagoreanMeans (rangeArr) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,70 @@
---
title: Averages-Root mean square
id: 594da033de4190850b893874
challengeType: 5
---
## Description
<section id='description'>
<p>Compute the <a href="https://en.wikipedia.org/wiki/Root mean square" title="wp: Root mean square">Root mean square</a> of the numbers 1 through 10 inclusive.</p>
<p>The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.</p><p>The RMS is calculated as the mean of the squares of the numbers, square-rooted:</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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>rms</code> is a function.
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> should equal <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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function rms (arr) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function rms (arr) {
const sumOfSquares = arr.reduce((s, x) => s + x * x, 0);
return Math.sqrt(sumOfSquares / arr.length);
}
```
</section>

View File

@ -0,0 +1,86 @@
---
title: Babbage problem
id: 594db4d0dedb4c06a2a4cefd
challengeType: 5
---
## Description
<section id='description'>
<p><a href="https://en.wikipedia.org/wiki/Charles_Babbage" title="wp: Charles_Babbage">Charles Babbage</a>, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:</p>
<blockquote>What is the smallest positive integer whose square ends in the digits 269,696?</blockquote>
<p> - Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, <i>Electronic Computers</i>, second edition, 1970, p. 125.</p>
<p>He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.</p>
<p>The task is to find out if Babbage had the right answer.</p>
<p>Implement a function to return the lowest integer that satisfies the Babbage problem. If Babbage was right, return Babbage's number.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>babbage</code> is a function.
testString: 'assert(typeof babbage === ''function'', ''<code>babbage</code> is a function.'');'
- text: '<code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).'
testString: 'assert.equal(babbage(babbageAns, endDigits), answer, ''<code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function babbage (babbageNum, endDigits) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,117 @@
---
title: Balanced brackets
id: 594dc6c729e5700999302b45
challengeType: 5
---
## Description
<section id='description'>
<p>Determine whether a generated string of brackets is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.</p>
Examples:
<p class='rosetta__paragraph'>(empty) 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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isBalanced</code> is a function.
testString: 'assert(typeof isBalanced === ''function'', ''<code>isBalanced</code> is a function.'');'
- text: '<code>isBalanced("[]")</code> should return true.'
testString: 'assert(isBalanced(testCases[0]), ''<code>isBalanced("[]")</code> should return true.'');'
- text: '<code>isBalanced("]][[[][][][]][")</code> should return false.'
testString: 'assert(!isBalanced(testCases[1]), ''<code>isBalanced("]][[[][][][]][")</code> should return false.'');'
- text: '<code>isBalanced("[][[[[][][[[]]]]]]")</code> should return true.'
testString: 'assert(isBalanced(testCases[2]), ''<code>isBalanced("[][[[[][][[[]]]]]]")</code> should return true.'');'
- text: '<code>isBalanced("][")</code> should return true.'
testString: 'assert(!isBalanced(testCases[3]), ''<code>isBalanced("][")</code> should return true.'');'
- text: '<code>isBalanced("[[[]]]][[]")</code> should return true.'
testString: 'assert(!isBalanced(testCases[4]), ''<code>isBalanced("[[[]]]][[]")</code> should return true.'');'
- text: '<code>isBalanced("][[]")</code> should return true.'
testString: 'assert(!isBalanced(testCases[5]), ''<code>isBalanced("][[]")</code> should return true.'');'
- text: '<code>isBalanced("][[][]][[[]]")</code> should return true.'
testString: 'assert(!isBalanced(testCases[6]), ''<code>isBalanced("][[][]][[[]]")</code> should return true.'');'
- text: '<code>isBalanced("[[][]]][")</code> should return true.'
testString: 'assert(!isBalanced(testCases[7]), ''<code>isBalanced("[[][]]][")</code> should return true.'');'
- text: '<code>isBalanced("[[[]]][[]]]][][[")</code> should return true.'
testString: 'assert(!isBalanced(testCases[8]), ''<code>isBalanced("[[[]]][[]]]][][[")</code> should return true.'');'
- text: '<code>isBalanced("[]][[]]][[[[][]]")</code> should return true.'
testString: 'assert(!isBalanced(testCases[9]), ''<code>isBalanced("[]][[]]][[[[][]]")</code> should return true.'');'
- text: '<code>isBalanced("][]][[][")</code> should return true.'
testString: 'assert(!isBalanced(testCases[10]), ''<code>isBalanced("][]][[][")</code> should return true.'');'
- text: '<code>isBalanced("[[]][[][]]")</code> should return true.'
testString: 'assert(isBalanced(testCases[11]), ''<code>isBalanced("[[]][[][]]")</code> should return true.'');'
- text: '<code>isBalanced("[[]]")</code> should return true.'
testString: 'assert(isBalanced(testCases[12]), ''<code>isBalanced("[[]]")</code> should return true.'');'
- text: '<code>isBalanced("]][]][[]][[[")</code> should return true.'
testString: 'assert(!isBalanced(testCases[13]), ''<code>isBalanced("]][]][[]][[[")</code> should return true.'');'
- text: '<code>isBalanced("][]][][[")</code> should return true.'
testString: 'assert(!isBalanced(testCases[14]), ''<code>isBalanced("][]][][[")</code> should return true.'');'
- text: '<code>isBalanced("][][")</code> should return true.'
testString: 'assert(!isBalanced(testCases[15]), ''<code>isBalanced("][][")</code> should return true.'');'
- text: '<code>isBalanced("[[]]][][][[]][")</code> should return true.'
testString: 'assert(!isBalanced(testCases[16]), ''<code>isBalanced("[[]]][][][[]][")</code> should return true.'');'
- text: <code>isBalanced("")</code> should return true.
testString: 'assert(isBalanced(testCases[17]), ''<code>isBalanced("")</code> should return true.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isBalanced (str) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,129 @@
---
title: Circles of given radius through two points
id: 5951815dd895584b06884620
challengeType: 5
---
## Description
<section id='description'>
<p>Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.</p>
Exceptions:
A radius of zero should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless the radius is equal to zero as well which then collapses the circles to a point.
If the points form a diameter then return a single circle.
If the points are too far apart then no circles can be drawn.Task:
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.
For edge cases, return the following:
If points are on the diameter, return one point. If the radius is also zero however, return <code>"Radius Zero"</code>.
If points are coincident, return <code>"Coincident point. Infinite solutions"</code>.
If points are farther apart than the diameter, return <code>"No intersection. Points further apart than circle diameter"</code>.
Sample inputs:
<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="link: http://mathforum.org/library/drmath/view/53027.html">Finding the Center of a Circle from 2 Points and Radius</a> from Math forum @ Drexel
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getCircles</code> is a function.
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> should return <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> should return <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> should return <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> should return <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> should return <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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getCircles (...args) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,257 @@
---
title: Closest-pair problem
id: 5951a53863c8a34f02bf1bdc
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the <a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Closest pair of points problem">Closest pair of points problem</a> in the planar case.</p><p>The straightforward solution is a O(n<sup>2</sup>) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:</p>
<pre>
bruteForceClosestPair of P(1), P(2), ... P(N)
if N &lt; 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance |P(i) - P(j)|
minPoints { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
</pre>
<p>A better algorithm is based on the recursive divide&amp;conquer approach, as explained also at <a href="https://en.wikipedia.org/wiki/Closest pair of points problem#Planar_case" title="wp: Closest pair of points problem#Planar_case">Wikipedia's Closest pair of points problem</a>, which is O(n log n); a pseudo-code could be:</p>
<pre>
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)<sub>x</sub>
yL ← { p ∈ yP : p<sub>x</sub> ≤ xm }
yR ← { p ∈ yP : p<sub>x</sub> &gt; xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL &lt; dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - p<sub>x</sub>| &lt; dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)<sub>y</sub> - yS(i)<sub>y</sub> &lt; dmin
if |yS(k) - yS(i)| &lt; closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
</pre>
References and further readings:
<a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Closest pair of points problem">Closest pair of points problem</a>
<a href="http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html" title="link: http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html">Closest Pair (McGill)</a>
<a href="http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf" title="link: http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf">Closest Pair (UCSB)</a>
<a href="http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf" title="link: http://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf">Closest pair (WUStL)</a>
<a href="http://www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt" title="link: http://www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt">Closest pair (IUPUI)</a>
<p>For the input, expect the argument to be an array of objects (points) with <code>x</code> and <code>y</code> members set to numbers. For the output, return an object containing the key:value pairs for <code>distance</code> and <code>pair</code> (i.e., the pair of two closest points).</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getClosestPair</code> is a function.
testString: 'assert(typeof getClosestPair === ''function'', ''<code>getClosestPair</code> is a function.'');'
- text: Distance should be the following.
testString: 'assert.equal(getClosestPair(points1).distance, answer1.distance, ''Distance should be the following.'');'
- text: Points should be the following.
testString: 'assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points1))).pair, answer1.pair, ''Points should be the following.'');'
- text: Distance should be the following.
testString: 'assert.equal(getClosestPair(points2).distance, answer2.distance, ''Distance should be the following.'');'
- text: Points should be the following.
testString: 'assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points2))).pair, answer2.pair, ''Points should be the following.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
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;
};
function getClosestPair (pointsArr) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,104 @@
---
title: Combinations
id: 5958469238c0d8d2632f46db
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Given non-negative integers <big> m </big> and <big> n</big>, generate all size <big> m </big> <a href="http://mathworld.wolfram.com/Combination.html" title="link: http://mathworld.wolfram.com/Combination.html">combinations</a> of the integers from <big> 0</big> (zero) to <big> n-1 </big> in sorted order (each combination is sorted and the entire table is sorted).</p>
Example:
<p><big>3</big> comb <big> 5 </big>is:</p>
<pre>
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
</pre>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>combinations</code> is a function.
testString: 'assert(typeof combinations === ''function'', ''<code>combinations</code> is a 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, ''<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> 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, ''<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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function combinations (m, n) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,91 @@
---
title: Comma quibbling
id: 596e414344c3b2872167f0fe
challengeType: 5
---
## Description
<section id='description'>
<p>Comma quibbling is a task originally set by Eric Lippert in his <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx" title="link: http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx">blog</a>.</p>
Task:<p>Write a function to generate a string output which is the concatenation of input words from a list/sequence where:</p>
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
<p>Test your function with the following series of inputs showing your output here on this page:</p>
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
<p>Note: Assume words are non-empty strings of uppercase characters for this task.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>quibble</code> is a function.
testString: 'assert(typeof quibble === ''function'', ''<code>quibble</code> is a function.'');'
- text: '<code>quibble(["ABC"])</code> should return a string.'
testString: 'assert(typeof quibble(["ABC"]) === ''string'', ''<code>quibble(["ABC"])</code> should return a string.'');'
- text: '<code>quibble([])</code> should return "{}".'
testString: 'assert.equal(quibble(testCases[0]), results[0], ''<code>quibble([])</code> should return "{}".'');'
- text: '<code>quibble(["ABC"])</code> should return "{ABC}".'
testString: 'assert.equal(quibble(testCases[1]), results[1], ''<code>quibble(["ABC"])</code> should return "{ABC}".'');'
- text: '<code>quibble(["ABC", "DEF"])</code> should return "{ABC and DEF}".'
testString: 'assert.equal(quibble(testCases[2]), results[2], ''<code>quibble(["ABC", "DEF"])</code> should return "{ABC and DEF}".'');'
- text: '<code>quibble(["ABC", "DEF", "G", "H"])</code> should return "{ABC,DEF,G and H}".'
testString: 'assert.equal(quibble(testCases[3]), results[3], ''<code>quibble(["ABC", "DEF", "G", "H"])</code> should return "{ABC,DEF,G and H}".'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function quibble (words) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function quibble (words) {
return "{" +
words.slice(0, words.length - 1).join(",") +
(words.length > 1 ? " and " : "") +
(words[words.length - 1] || '') +
"}";
}
```
</section>

View File

@ -0,0 +1,106 @@
---
title: Compare a list of strings
id: 596e457071c35c882915b3e4
challengeType: 5
---
## Description
<section id='description'>
<p>Given a <a href="https://en.wikipedia.org/wiki/List_(abstract_data_type)" title="wp: List_(abstract_data_type)">list</a> of arbitrarily many strings, implement a function for each of the following conditions:</p> test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>allEqual</code> is a function.
testString: 'assert(typeof allEqual === ''function'', ''<code>allEqual</code> is a function.'');'
- text: <code>azSorted</code> is a function.
testString: 'assert(typeof azSorted === ''function'', ''<code>azSorted</code> is a function.'');'
- text: '<code>allEqual(["AA", "AA", "AA", "AA"])</code> returns true.'
testString: 'assert(allEqual(testCases[0]), ''<code>allEqual(["AA", "AA", "AA", "AA"])</code> returns true.'');'
- text: '<code>azSorted(["AA", "AA", "AA", "AA"])</code> returns false.'
testString: 'assert(!azSorted(testCases[0]), ''<code>azSorted(["AA", "AA", "AA", "AA"])</code> returns false.'');'
- text: '<code>allEqual(["AA", "ACB", "BB", "CC"])</code> returns false.'
testString: 'assert(!allEqual(testCases[1]), ''<code>allEqual(["AA", "ACB", "BB", "CC"])</code> returns false.'');'
- text: '<code>azSorted(["AA", "ACB", "BB", "CC"])</code> returns true.'
testString: 'assert(azSorted(testCases[1]), ''<code>azSorted(["AA", "ACB", "BB", "CC"])</code> returns true.'');'
- text: '<code>allEqual([])</code> returns true.'
testString: 'assert(allEqual(testCases[2]), ''<code>allEqual([])</code> returns true.'');'
- text: '<code>azSorted([])</code> returns true.'
testString: 'assert(azSorted(testCases[2]), ''<code>azSorted([])</code> returns true.'');'
- text: '<code>allEqual(["AA"])</code> returns true.'
testString: 'assert(allEqual(testCases[3]), ''<code>allEqual(["AA"])</code> returns true.'');'
- text: '<code>azSorted(["AA"])</code> returns true.'
testString: 'assert(azSorted(testCases[3]), ''<code>azSorted(["AA"])</code> returns true.'');'
- text: '<code>allEqual(["BB", "AA"])</code> returns false.'
testString: 'assert(!allEqual(testCases[4]), ''<code>allEqual(["BB", "AA"])</code> returns false.'');'
- text: '<code>azSorted(["BB", "AA"])</code> returns false.'
testString: 'assert(!azSorted(testCases[4]), ''<code>azSorted(["BB", "AA"])</code> returns false.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function allEqual (arr) {
// Good luck!
return true;
}
function azSorted (arr) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,160 @@
---
title: Convert seconds to compound duration
id: 596fd036dc1ab896c5db98b1
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Implement a function which:</p>
takes a positive integer representing a duration in seconds as input (e.g., <code>100</code>), and
returns a string which shows the same duration decomposed into weeks, days, hours, minutes, and seconds as detailed below (e.g., "<code>1 min, 40 sec</code>").
<p>Demonstrate that it passes the following three test-cases:</p><p style="font-size:115%; margin:1em 0 0 0">Test Cases</p>
<table>
<tbody>
<tr>
<th>input number</th>
<th>output number</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">Details</p>
The following five units should be used:
<table>
<tbody>
<tr>
<th>unit</th>
<th>suffix used in output</th>
<th>conversion</th>
</tr>
<tr>
<td>week</td>
<td><code>wk</code></td>
<td>1 week = 7 days</td>
</tr>
<tr>
<td>day</td>
<td><code>d</code></td>
<td>1 day = 24 hours</td>
</tr>
<tr>
<td>hour</td>
<td><code>hr</code></td>
<td>1 hour = 60 minutes</td>
</tr>
<tr>
<td>minute</td>
<td><code>min</code></td>
<td>1 minute = 60 seconds</td>
</tr>
<tr>
<td>second</td>
<td><code>sec</code></td>
<td></td>
</tr>
</tbody>
</table>
However, only include quantities with non-zero values in the output (e.g., return "<code>1 d</code>" and not "<code>0 wk, 1 d, 0 hr, 0 min, 0 sec</code>").Give larger units precedence over smaller ones as much as possible (e.g., return <code>2 min, 10 sec</code> and not <code>1 min, 70 sec</code> or <code>130 sec</code>)Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
<p><hr style="margin:1em 0;"/></p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>convertSeconds</code> is a function.
testString: 'assert(typeof convertSeconds === ''function'', ''<code>convertSeconds</code> is a function.'');'
- text: '<code>convertSeconds(7259)</code> should return <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> should return <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> should return <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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function convertSeconds (sec) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,79 @@
---
title: Count occurrences of a substring
id: 596fda99c69f779975a1b67d
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.</p><p>The function should take two arguments:</p>
the first argument being the string to search, and
the second a substring to be searched for.
<p>It should return an integer count.</p>
<p>The matching should yield the highest number of non-overlapping matches.</p><p>In general, this essentially means matching from left-to-right or right-to-left.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>countSubstring</code> is a function.
testString: 'assert(typeof countSubstring === ''function'', ''<code>countSubstring</code> is a function.'');'
- text: '<code>countSubstring("the three truths", "th")</code> should return <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("ababababab", "abab")</code> should return <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("abaabba*bbaba*bbab", "a*b")</code> should return <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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function countSubstring (str, subStr) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,91 @@
---
title: Count the coins
id: 59713bd26bdeb8a594fb9413
challengeType: 5
---
## Description
<section id='description'>
<p>There are four types of common coins in <a href="https://en.wikipedia.org/wiki/United_States" title="link: https://en.wikipedia.org/wiki/United_States">US</a> currency:</p>
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
<p>There are six ways to make change for 15 cents:</p>
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task:
<p>Implement a function to determine how many ways there are to make change for a dollar using these common coins? (1 dollar = 100 cents).</p>
Reference:
<a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52" title="link: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52">an algorithm from MIT Press</a>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>countCoins</code> is a function.
testString: 'assert(typeof countCoins === ''function'', ''<code>countCoins</code> is a function.'');'
- text: <code>countCoints()</code> should return 242.
testString: 'assert.equal(countCoins(), 242, ''<code>countCoints()</code> should return 242.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function countCoins () {
// Good luck!
return true;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,164 @@
---
title: Cramer's rule
id: 59713da0a428c1a62d7db430
challengeType: 5
---
## Description
<section id='description'>
<p>In <a href="https://en.wikipedia.org/wiki/linear algebra" title="wp: linear algebra">linear algebra</a>, <a href="https://en.wikipedia.org/wiki/Cramer's rule" title="wp: Cramer's rule">Cramer's rule</a> is an explicit formula for the solution of a <a href="https://en.wikipedia.org/wiki/system of linear equations" title="wp: system of linear equations">system of linear equations</a> with as many equations as unknowns, valid whenever the system has a unique solution. It expresses the solution in terms of the determinants of the (square) coefficient matrix and of matrices obtained from it by replacing one column by the vector of right hand sides of the equations.</p>
<p>Given</p>
<p><big></p>
<p> $\left\{\begin{matrix}a_1x + b_1y + c_1z&= {\color{red}d_1}\\a_2x + b_2y + c_2z&= {\color{red}d_2}\\a_3x + b_3y + c_3z&= {\color{red}d_3}\end{matrix}\right.$</p>
</big><p>which in matrix format is</p><p><big></p>
<p> $\begin{bmatrix} a_1 & b_1 & c_1 \\ a_2 & b_2 & c_2 \\ a_3 & b_3 & 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}.$</p>
</big><p>Then the values of $x, y$ and $z$ can be found as follows:</p><p><big></p>
<p>$x = \frac{\begin{vmatrix} {\color{red}d_1} & b_1 & c_1 \\ {\color{red}d_2} & b_2 & c_2 \\ {\color{red}d_3} & b_3 & c_3 \end{vmatrix} } { \begin{vmatrix} a_1 & b_1 & c_1 \\ a_2 & b_2 & c_2 \\ a_3 & b_3 & c_3 \end{vmatrix}}, \quad y = \frac {\begin{vmatrix} a_1 & {\color{red}d_1} & c_1 \\ a_2 & {\color{red}d_2} & c_2 \\ a_3 & {\color{red}d_3} & c_3 \end{vmatrix}} {\begin{vmatrix} a_1 & b_1 & c_1 \\ a_2 & b_2 & c_2 \\ a_3 & b_3 & c_3 \end{vmatrix}}, \text{ and }z = \frac { \begin{vmatrix} a_1 & b_1 & {\color{red}d_1} \\ a_2 & b_2 & {\color{red}d_2} \\ a_3 & b_3 & {\color{red}d_3} \end{vmatrix}} {\begin{vmatrix} a_1 & b_1 & c_1 \\ a_2 & b_2 & c_2 \\ a_3 & b_3 & c_3 \end{vmatrix} }.$</p>
</big>
Task
<p>Given the following system of equations:</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>solve for <big>$w$, $x$, $y$</big> and <big>$z$</big>, using Cramer's rule.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>cramersRule</code> is a function.
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> should return <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> should return <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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function cramersRule (matrix, freeTerms) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
/**
* 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

@ -0,0 +1,81 @@
---
title: Date format
id: 59669d08d75b60482359409f
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Return an array with the current date in the formats:</p>
<p>- 2007-11-23 and </p>
<p>- Sunday, November 23, 2007</p>
<p>Example output: <code>['2007-11-23', 'Sunday, November 23, 2007']</code></p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getDateFormats</code> is a function.
testString: 'assert(typeof getDateFormats === ''function'', ''<code>getDateFormats</code> is a function.'');'
- text: Should return an object.
testString: 'assert(typeof getDateFormats() === ''object'', ''Should return an object.'');'
- text: Should returned an array with 2 elements.
testString: 'assert(getDateFormats().length === 2, ''Should returned an array with 2 elements.'');'
- text: Should return the correct date in the right format
testString: 'assert.deepEqual(getDateFormats(), dates, equalsMessage);'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getDateFormats () {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,111 @@
---
title: Date manipulation
id: 5966c21cf732a95f1b67dd28
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Given a date string in EST, output the given date as a string with 12 hours added to the time. </p>
<p>Time zone should be preserved.</p>
<p>Example input: </p>
<p><code>"March 7 2009 7:30pm EST"</code></p>
<p>Example output: </p>
<p><code>"March 8 2009 7:30am EST"</code></p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>add12Hours</code> is a function.
testString: 'assert(typeof add12Hours === ''function'', ''<code>add12Hours</code> is a function.'');'
- text: <code>add12Hours(dateString)</code> should return a string.
testString: 'assert(typeof add12Hours(tests[0]) === ''string'', ''<code>add12Hours(dateString)</code> should return a string.'');'
- text: '<code>add12Hours("'' + tests[0] + ''")</code> should return <code>"'' + answers[0] + ''"</code>'
testString: 'assert(add12Hours(tests[0]) === answers[0], ''<code>add12Hours("'' + tests[0] + ''")</code> should return <code>"'' + answers[0] + ''"</code>'');'
- text: 'Should handel day change. <code>add12Hours("'' + tests[1] + ''")</code> should return <code>"'' + answers[1] + ''"</code>'
testString: 'assert(add12Hours(tests[1]) === answers[1], ''Should handel day change. <code>add12Hours("'' + tests[1] + ''")</code> should return <code>"'' + answers[1] + ''"</code>'');'
- text: 'Should handel month change in a leap years. <code>add12Hours("'' + tests[2] + ''")</code> should return <code>"'' + answers[2] + ''"</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: 'Should handel month change in a common years. <code>add12Hours("'' + tests[3] + ''")</code> should return <code>"'' + answers[3] + ''"</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: 'Should handel year change. <code>add12Hours("'' + tests[4] + ''")</code> should return <code>"'' + answers[4] + ''"</code>'
testString: 'assert(add12Hours(tests[4]) === answers[4], ''Should handel year change. <code>add12Hours("'' + tests[4] + ''")</code> should return <code>"'' + answers[4] + ''"</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function add12Hours (dateString) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,81 @@
---
title: Day of the week
id: 5966f99c45e8976909a85575
challengeType: 5
---
## Description
<section id='description'>
<p>A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).</p>
<p>Task:</p>
<p>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.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>findXmasSunday</code> is a function.
testString: 'assert(typeof findXmasSunday === ''function'', ''<code>findXmasSunday</code> is a function.'');'
- text: '<code>findChristmasSunday(2000, 2100)</code> should return an array.'
testString: 'assert(typeof findXmasSunday(2000, 2100) === ''object'', ''<code>findChristmasSunday(2000, 2100)</code> should return an array.'');'
- text: '<code>findChristmasSunday(2008, 2121</code> should return [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> 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, ''<code>findChristmasSunday(2008, 2121</code> should return [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function findXmasSunday (start, end) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,174 @@
---
title: Deal cards for FreeCell
id: 59694356a6e7011f7f1c5f4e
challengeType: 5
---
## Description
<section id='description'>
<p>Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for <a href="http://rosettacode.org/wiki/DOS" title="DOS">DOS</a>, then <a href="http://rosettacode.org/wiki/Windows" title="Windows">Windows</a>. </p>
<p>This version introduced 32000 numbered deals. (The <a href="http://www.solitairelaboratory.com/fcfaq.html" title="link: http://www.solitairelaboratory.com/fcfaq.html">FreeCell FAQ</a> tells this history.)</p><p>As the game became popular, Jim Horne disclosed <a href="http://www.solitairelaboratory.com/mshuffle.txt" title="link: http://www.solitairelaboratory.com/mshuffle.txt">the algorithm</a>, and other implementations of FreeCell began to reproduce the Microsoft deals. </p>
<p>These deals are numbered from 1 to 32000.</p>
<p>Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.</p><p>The algorithm uses this <a href="http://rosettacode.org/wiki/linear congruential generator" title="linear congruential generator">linear congruential generator</a> from Microsoft C:</p>$state_{n + 1} \equiv 214013 \times state_n + 2531011 \pmod{2^{31}}$
$rand_n = state_n \div 2^{16}$
$rand_n$ is in range 0 to 32767.
<p>The algorithm follows:</p>Seed the RNG with the number of the deal.
Create an <a href="http://rosettacode.org/wiki/array" title="array">array</a> of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index &equiv; next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Example:
<p>Order to deal cards</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
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52</pre></p>
<p>Game #1</p>
<p><pre>[
['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']
]</pre></p>
<p>Game #617</p>
<p><pre>[
['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']
]</pre></p>
Task:
<p>Write a function to take a deal number and deal cards in the same order as this algorithm.</p>
<p>The function must return a two dimensional array representing the FreeCell board.</p>
<p>Deals can also be checked against <a href="http://freecellgamesolutions.com/" title="link: http://freecellgamesolutions.com/">FreeCell solutions to 1000000 games</a>.</p>
<p>(Summon a video solution, and it displays the initial deal.)</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>dealFreeCell</code> is a function.
testString: 'assert(typeof dealFreeCell === ''function'', ''<code>dealFreeCell</code> is a function.'');'
- text: <code>dealFreeCell(seed)</code> should return an object.
testString: 'assert(typeof dealFreeCell(1) === ''object'', ''<code>dealFreeCell(seed)</code> should return an object.'');'
- text: <code>dealFreeCell(seed)</code> should return an array of length 7.
testString: 'assert(dealFreeCell(1).length === 7, ''<code>dealFreeCell(seed)</code> should return an array of length 7.'');'
- text: '<code>dealFreeCell(1)</code> should return an array identical to example "Game #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> should return an array identical to example "Game #617"'
testString: 'assert.deepEqual(dealFreeCell(617), game617, ''<code>dealFreeCell(617)</code> should return an array identical to example "Game #617"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function dealFreeCell (seed) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,82 @@
---
title: Deepcopy
id: 596a8888ab7c01048de257d5
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Write a function that returns a deep copy of a given object.</p>
<p>The copy must not be the same object that was given.</p>
<p>This task will not test for: </p>
Objects with properties that are functions
Date objects or object with properties that are Date objects
RegEx or object with properties that are RegEx objects
Prototype copying
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>deepcopy</code> should be a function.
testString: 'assert(typeof deepcopy === ''function'', ''<code>deepcopy</code> should be a function.'');'
- text: '<code>deepcopy({test: "test"})</code> should return an object.'
testString: 'assert(typeof deepcopy(obj1) === ''object'', ''<code>deepcopy({test: "test"})</code> should return an object.'');'
- text: Should not return the same object that was provided.
testString: 'assert(deepcopy(obj2) != obj2, ''Should not return the same object that was provided.'');'
- text: 'When passed an object containing an array, should return a deep copy of the object.'
testString: 'assert.deepEqual(deepcopy(obj2), obj2, ''When passed an object containing an array, should return a deep copy of the object.'');'
- text: 'When passed an object containing another object, should return a deep copy of the object.'
testString: 'assert.deepEqual(deepcopy(obj3), obj3, ''When passed an object containing another object, should return a deep copy of the object.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function deepcopy (obj) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function deepcopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
```
</section>

View File

@ -0,0 +1,117 @@
---
title: Define a primitive data type
id: 597089c87eec450c68aa1643
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10.</p>
Errors:
If you try to instantiate a <code>Num</code> with a value outside of 1 - 10
it should throw a <code>TypeError</code> with an error message of <code>'Out of range'</code>.
If you try to instantiate a <code>Num</code> with a value that is not a number
it should throw a <code>TypeError</code> with an error message of <code>'Not a Number'</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>Num</code> should be a function.
testString: 'assert(typeof Num === ''function'', ''<code>Num</code> should be a function.'');'
- text: <code>new Num(4)</code> should return an object.
testString: 'assert(typeof (new Num(4)) === ''object'', ''<code>new Num(4)</code> should return an object.'');'
- text: <code>new Num(\'test\')</code> should throw a TypeError with message \'Not a Number\'.
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> should throw a TypeError with message \'Out of range\'.
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> should throw a TypeError with message \'Out of range\'.
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> should throw a TypeError with message \'Out of range\'.
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> should throw a TypeError with message \'Out of range\'.
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> should equal 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> should equal -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> should equal 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> should equal 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) < new Num(4)</code> should be true.
testString: 'assert(new Num(3) < new Num(4), ''<code>new Num(3) < new Num(4)</code> should be true.'');'
- text: <code>new Num(3) > new Num(4)</code> should be false.
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> should return \'5\'
testString: 'assert.equal((new Num(5)).toString(), ''5'', ''<code>(new Num(5)).toString()</code> should return \''5\'''');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Num (n) {
// Good luck!
return n;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Num(n) {
const num = Math.floor(n);
if (isNaN(num)) {
throw new TypeError('Not a Number');
}
if (num < 1 || num > 10) {
throw new TypeError('Out of range');
}
this._value = num;
}
Num.prototype.valueOf = function() { return this._value; };
Num.prototype.toString = function () { return this._value.toString(); };
function throws(func, errorType, msg) {
let hasThrown = false;
let errorMsg = '';
let correctType = false;
try {
func();
}
catch (e) {
hasThrown = true;
errorMsg = e.message;
if (e instanceof errorType) {
correctType = true;
}
}
return hasThrown && correctType && msg === errorMsg;
}
```
</section>

View File

@ -0,0 +1,114 @@
---
title: Department Numbers
id: 59f40b17e79dbf1ab720ed7a
challengeType: 5
---
## Description
<section id='description'>
<p>There is a highly organized city that has decided to assign a number to each of their departments:</p>
Police department
Sanitation department
Fire department
<p>Each department can have a number between 1 and 7 (inclusive).</p><p>The three department numbers are to be unique (different from each other) and must add up to the number 12.</p><p>The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.</p>
Task:
<p>Write a program which outputs all valid combinations:</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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>combinations</code> should be a function.
testString: 'assert(typeof combinations === ''function'', ''<code>combinations</code> should be a function.'');'
- text: '<code>combinations([1, 2, 3], 6)</code> should return an Array.'
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> should return an array of length 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> should return all valid combinations.'
testString: 'assert.deepEqual(combinations(nums, total), result, ''<code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return all valid combinations.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function combinations (possibleNumbers, total) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,168 @@
---
title: Discordian date
id: 59f4eafba0343628bb682785
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Convert a given date from the <a href="https://en.wikipedia.org/wiki/Gregorian calendar" title="wp: Gregorian calendar">Gregorian calendar</a> to the <a href="https://en.wikipedia.org/wiki/Discordian calendar" title="wp: Discordian calendar">Discordian calendar</a>.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>discordianDate</code> is a function.
testString: 'assert(typeof discordianDate === ''function'', ''<code>discordianDate</code> is a 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'', ''<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> 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'', ''<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> 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!'', ''<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> 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'', ''<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> 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!'', ''<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> 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!'', ''<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> 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'', ''<code>discordianDate(new Date(2015, 9, 19))</code> should return <code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function discordianDate (date) {
// Good luck!
return true;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
/**
* 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

@ -0,0 +1,91 @@
---
title: Element-wise operations
id: 599c333915e0ea32d04d4bec
challengeType: 5
---
## Description
<section id='description'>
<p>Implement basic element-wise matrix-matrix and scalar-matrix operations.</p><p>Implement:</p>
<p>::* addition</p>
<p>::* subtraction</p>
<p>::* multiplication</p>
<p>::* division</p>
<p>::* exponentiation</p>
<p>The first parameter will be the operation to be performed, for example : "m_add" for matrix addition and "s_add" for scalar addition. The second and third parameters will be the matrices on which the operations are to be performed.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>operation</code> is a function.
testString: 'assert(typeof operation === ''function'', ''<code>operation</code> is a 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]], ''<code>operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[2,4],[6,8]]</code>.'');'
- 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]], ''<code>operation("s_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[3,4],[5,6]]</code>.'');'
- 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]], ''<code>operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[0,0],[0,0]]</code>.'');'
- 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]], ''<code>operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[9,16]]</code>.'');'
- 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]], ''<code>operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,1],[1,1]]</code>.'');'
- 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]], ''<code>operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[27,256]]</code>.'');'
- 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]], ''<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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function operation (op, arr1, arr2) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,98 @@
---
title: Emirp primes
id: 599d0ba974141b0f508b37d5
challengeType: 5
---
## Description
<section id='description'>
<p>An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.</p>
<p>Write a function that should be able to : Show the first <b>n</b> eprimes numbers.Show the eprimes numbers in a range.Show the number of eprimes in a range.Show the <b>n<sup>th</sup></b> eprimes number.<p>The function should have two parameters. The first will receive <b>n</b> or the range as an array. The second will receive a boolean, that specifies if the function returns the eprimes as an array or a single number(the number of primes in the range or the <b>n<sup>th</sup></b> prime). According to the parameters the function should return an array or a number.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>emirps</code> is a function.
testString: 'assert(typeof emirps === ''function'', ''<code>emirps</code> is a 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], ''<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> should return <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> 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], ''<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> should return <code>11</code>'
testString: 'assert.deepEqual(emirps([7700, 8000], false), 11, ''<code>emirps([7700,8000],true)</code> should return <code>11</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function emirps(n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,88 @@
---
title: Entropy
id: 599d15309e88c813a40baf58
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Calculate the Shannon entropy H of a given input string.</p><p>Given the discreet random variable $X$ that is a string of $N$ "symbols" (total characters) consisting of $n$ different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :</p>
<p>$H_2(X) = -\sum_{i=1}^n \frac{count_i}{N} \log_2 \left(\frac{count_i}{N}\right)$</p><p>where $count_i$ is the count of character $n_i$.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>entropy</code> is a function.
testString: 'assert(typeof entropy === ''function'', ''<code>entropy</code> is a function.'');'
- text: <code>entropy("0")</code> should return <code>0</code>
testString: 'assert.equal(entropy(''0''), 0, ''<code>entropy("0")</code> should return <code>0</code>'');'
- text: <code>entropy("01")</code> should return <code>1</code>
testString: 'assert.equal(entropy(''01''), 1, ''<code>entropy("01")</code> should return <code>1</code>'');'
- text: <code>entropy("0123")</code> should return <code>2</code>
testString: 'assert.equal(entropy(''0123''), 2, ''<code>entropy("0123")</code> should return <code>2</code>'');'
- text: <code>entropy("01234567")</code> should return <code>3</code>
testString: 'assert.equal(entropy(''01234567''), 3, ''<code>entropy("01234567")</code> should return <code>3</code>'');'
- text: <code>entropy("0123456789abcdef")</code> should return <code>4</code>
testString: 'assert.equal(entropy(''0123456789abcdef''), 4, ''<code>entropy("0123456789abcdef")</code> should return <code>4</code>'');'
- text: <code>entropy("1223334444")</code> should return <code>1.8464393446710154</code>
testString: 'assert.equal(entropy(''1223334444''), 1.8464393446710154, ''<code>entropy("1223334444")</code> should return <code>1.8464393446710154</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function entropy (s) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,94 @@
---
title: Equilibrium index
id: 5987fd532b954e0f21b5d3f6
challengeType: 5
---
## Description
<section id='description'>
<p>An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.</p>
<p>For example, in a sequence <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 is an equilibrium index, because:</p><p>:::: <big>$A_0 + A_1 + A_2 = A_4 + A_5 + A_6$</big></p><p>6 is also an equilibrium index, because:</p><p>:::: <big>$A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0$</big></p><p>(sum of zero elements is zero)</p><p>7 is not an equilibrium index, because it is not a valid index of sequence <big>$A$</big>.</p>
<p>Write a function that, given a sequence, returns its equilibrium indices (if any).</p><p>Assume that the sequence may be very long.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>equilibrium</code> is a function.
testString: 'assert(typeof equilibrium === ''function'', ''<code>equilibrium</code> is a function.'');'
- text: '<code>equilibrium([-7, 1, 5, 2, -4, 3, 0])</code> should return <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> should return <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> should return <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> should return <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> should return <code>[0]</code>.'
testString: 'assert.deepEqual(equilibrium(tests[4]), ans[4], ''<code>equilibrium([1])</code> should return <code>[0]</code>.'');'
- text: '<code>equilibrium([])</code> should return <code>[]</code>.'
testString: 'assert.deepEqual(equilibrium(tests[5]), ans[5], ''<code>equilibrium([])</code> should return <code>[]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function equilibrium (a) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,123 @@
---
title: Ethiopian multiplication
id: 599d1566a02b571412643b84
challengeType: 5
---
## Description
<section id='description'>
<p>Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.</p>
<p>Method: </p>
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
<p>For example: 17 &times; 34</p>
<p>17 34</p>
<p>Halving the first column:</p>
<p>17 34</p>
<p>8</p>
<p>4</p>
<p>2</p>
<p>1</p>
<p>Doubling the second column:</p>
<p>17 34</p>
<p>8 68</p>
<p>4 136</p>
<p>2 272</p>
<p>1 544</p>
<p>Strike-out rows whose first cell is even:</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>Sum the remaining numbers in the right-hand column:</p>
<p>17 34</p>
<p>8 --</p>
<p>4 ---</p>
<p>2 ---</p>
<p>1 544</p>
<p>====</p>
<p>578</p>
<p>So 17 multiplied by 34, by the Ethiopian method is 578.</p>
Task:
<p>The task is to define three named functions/methods/procedures/subroutines:</p>
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
<p>Use these functions to create a function that does Ethiopian multiplication.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>eth_mult</code> is a function.
testString: 'assert(typeof eth_mult === ''function'', ''<code>eth_mult</code> is a function.'');'
- text: '<code>eth_mult(17,34)</code> should return <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> should return <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> should return <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> should return <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> should return <code>4662</code>.'
testString: 'assert.equal(eth_mult(63, 74), 4662, ''<code>eth_mult(63,74)</code> should return <code>4662</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function eth_mult (a, b) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,89 @@
---
title: Euler method
id: 59880443fb36441083c6c20e
challengeType: 5
---
## Description
<section id='description'>
<p>Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in <a href="https://en.wikipedia.org/wiki/Euler method" title="wp: Euler method">the wikipedia page</a>.</p><p>The ODE has to be provided in the following form:</p><p>:: <big>$\frac{dy(t)}{dt} = f(t,y(t))$</big></p><p>with an initial value</p><p>:: <big>$y(t_0) = y_0$</big></p><p>To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:</p><p>:: <big>$\frac{dy(t)}{dt} \approx \frac{y(t+h)-y(t)}{h}$</big></p><p>then solve for $y(t+h)$:</p><p>:: <big>$y(t+h) \approx y(t) + h \, \frac{dy(t)}{dt}$</big></p><p>which is the same as</p><p>:: <big>$y(t+h) \approx y(t) + h \, f(t,y(t))$</big></p><p>The iterative solution rule is then:</p><p>:: <big>$y_{n+1} = y_n + h \, f(t_n, y_n)$</big></p><p>where <big>$h$</big> is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.</p>
<p>Example: Newton's Cooling Law</p><p>Newton's cooling law describes how an object of initial temperature <big>$T(t_0) = T_0$</big> cools down in an environment of temperature <big>$T_R$</big>:</p><p>:: <big>$\frac{dT(t)}{dt} = -k \, \Delta T$</big></p>
<p>or</p>
<p>:: <big>$\frac{dT(t)}{dt} = -k \, (T(t) - T_R)$</big></p>
<p>It says that the cooling rate <big>$\frac{dT(t)}{dt}$</big> of the object is proportional to the current temperature difference <big>$\Delta T = (T(t) - T_R)$</big> to the surrounding environment.</p><p>The analytical solution, which we will compare to the numerical approximation, is</p>
<p>:: <big>$T(t) = T_R + (T_0 - T_R) \; e^{-k t}$</big></p>
Task:
<p>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:</p>
<p>::* 2 s</p>
<p>::* 5 s and </p>
<p>::* 10 s </p>
<p>and to compare with the analytical solution.</p>
Initial values:
<p>::* initial temperature <big>$T_0$</big> shall be 100 °C</p>
<p>::* room temperature <big>$T_R$</big> shall be 20 °C</p>
<p>::* cooling constant <big>$k$</big> shall be 0.07 </p>
<p>::* time interval to calculate shall be from 0 s ──► 100 s</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>eulersMethod</code> is a function.
testString: 'assert(typeof eulersMethod === ''function'', ''<code>eulersMethod</code> is a function.'');'
- text: '<code>eulersMethod(0, 100, 100, 10)</code> should return a number.'
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> should return 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> should return 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> should return 20.000472392.'
testString: 'assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392, ''<code>eulersMethod(0, 100, 100, 10)</code> should return 20.000472392.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function eulersMethod (x1, y1, x2, h) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,71 @@
---
title: Evaluate binomial coefficients
id: 598de241872ef8353c58a7a2
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function to calculate the binomial coefficient for the given value of n and k.</p><p>This formula is recommended:</p>
$\binom{n}{k} = \frac{n!}{(n-k)!k!} = \frac{n(n-1)(n-2)\ldots(n-k+1)}{k(k-1)(k-2)\ldots 1}$
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>binom</code> is a function.
testString: 'assert(typeof binom === ''function'', ''<code>binom</code> is a function.'');'
- text: '<code>binom(5,3)</code> should return 10.'
testString: 'assert.equal(binom(5, 3), 10, ''<code>binom(5,3)</code> should return 10.'');'
- text: '<code>binom(7,2)</code> should return 21.'
testString: 'assert.equal(binom(7, 2), 21, ''<code>binom(7,2)</code> should return 21.'');'
- text: '<code>binom(10,4)</code> should return 210.'
testString: 'assert.equal(binom(10, 4), 210, ''<code>binom(10,4)</code> should return 210.'');'
- text: '<code>binom(6,1)</code> should return 6.'
testString: 'assert.equal(binom(6, 1), 6, ''<code>binom(6,1)</code> should return 6.'');'
- text: '<code>binom(12,8)</code> should return 495.'
testString: 'assert.equal(binom(12, 8), 495, ''<code>binom(12,8)</code> should return 495.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function binom (n, k) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,211 @@
---
title: Execute a Markov algorithm
id: 59e09e6d412c5939baa02d16
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Create an interpreter for a <a href="https://en.wikipedia.org/wiki/Markov algorithm" title="wp: Markov algorithm">Markov Algorithm</a>.</p><p>Rules have the syntax:</p>
<p><ruleset> ::= ((<comment> | <rule>) <newline>+)*</p>
<p><comment> ::= # {<any character>}</p>
<p><rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement></p>
<p><whitespace> ::= (<tab> | <space>) [<whitespace>]</p>
<p>There is one rule per line.</p><p>If there is a <b>.</b> (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.</p><p>A ruleset consists of a sequence of rules, with optional comments.</p>
<p><big><big> Rulesets </big></big></p><p>Use the following tests on entries:</p>
Ruleset 1:
<pre>
This rules file is extracted from Wikipedia:
http://en.wikipedia.org/wiki/Markov_AlgorithmA -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
</pre>
<p>Sample text of:</p>
<p> <code> I bought a B of As from T S. </code></p>
<p>Should generate the output:</p>
<p> <code> I bought a bag of apples from my brother. </code></p>
Ruleset 2:
<p>A test of the terminating rule</p>
<pre>
Slightly modified from the rules on WikipediaA -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule</pre>
<p>Sample text of:</p>
<p> <code>I bought a B of As from T S.</code></p>
<p>Should generate:</p>
<p> <code>I bought a bag of apples from T shop.</code></p>
Ruleset 3:
<p>This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.</p>
<pre>
BNF Syntax testing rulesA -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
</pre>
<p>Sample text of:</p>
<p> <code>I bought a B of As W my Bgage from T S.</code></p>
<p>Should generate:</p>
<p> <code>I bought a bag of apples with my money from T shop.</code></p>
Ruleset 4:
<p>This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)</p>
<pre>
## Unary Multiplication Engine, for testing Markov Algorithm implementations
## By Donal Fellows.
Unary addition engine_+1 -> _1+
1+1 -> 11+
Pass for converting from the splitting of multiplication into ordinary
addition1! -> !1
,! -> !+
_! -> _
Unary multiplication by duplicating left side, right side times1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
Next phase of applying1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
Termination cleanup for addition_1 -> 1
1+_ -> 1
_+_ ->
</pre>
<p>Sample text of:</p>
<p> <code> _1111*11111_ </code></p>
<p>should generate the output:</p>
<p> <code> 11111111111111111111 </code></p>
Ruleset 5:
<p>A simple <a href="http://en.wikipedia.org/wiki/Turing_machine" title="link: http://en.wikipedia.org/wiki/Turing_machine">Turing machine</a>,</p>
<p>implementing a three-state <a href="http://en.wikipedia.org/wiki/Busy_beaver" title="link: http://en.wikipedia.org/wiki/Busy_beaver">busy beaver</a>.</p><p>The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.</p>
<p>All parts of the initial tape the machine operates on have to be given in the input.</p><p>Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.</p>
<pre>
Turing machine: three-state busy beaver
# state A, symbol 0 => write 1, move right, new state BA0 -> 1B
state A, symbol 1 => write 1, move left, new state C0A1 -> C01
1A1 -> C11
state B, symbol 0 => write 1, move left, new state A0B0 -> A01
1B0 -> A11
state B, symbol 1 => write 1, move right, new state BB1 -> 1B
state C, symbol 0 => write 1, move left, new state B0C0 -> B01
1C0 -> B11
state C, symbol 1 => write 1, move left, halt0C1 -> H01
1C1 -> H11
</pre>
<p>This ruleset should turn</p>
<p> <code> 000000A000000 </code></p>
<p>into</p>
<p> <code> 00011H1111000 </code></p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>markov</code> is a function.
testString: 'assert(typeof markov === ''function'', ''<code>markov</code> is a 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],''<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(["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],''<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(["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],''<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(["_+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],''<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(["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],''<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".'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function markov (rules,test) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,212 @@
---
title: Execute Brain****
id: 59e0a8df964e4540d5abe599
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function to implement a Brain**** interpreter. The function will take a string as a parameter and should return a string as the output. More details are given below : </p>
<p>RCBF is a set of <a href="http://rosettacode.org/wiki/Brainf***" title="Brainf***">Brainf***</a> compilers and interpreters written for Rosetta Code in a variety of languages.</p><p>Below are links to each of the versions of RCBF.</p><p>An implementation need only properly implement the following instructions:</p>
<p>{|</p>
<p>!Command</p>
<p>!Description</p>
<p>|-</p>
<p>| style="text-align:center"| <code>&gt;</code> || Move the pointer to the right</p>
<p>|-</p>
<p>| style="text-align:center"| <code>&lt;</code> || Move the pointer to the left</p>
<p>|-</p>
<p>| style="text-align:center"| <code>+</code> || Increment the memory cell under the pointer</p>
<p>|-</p>
<p>| style="text-align:center"| <code>-</code> || Decrement the memory cell under the pointer</p>
<p>|-</p>
<p>| style="text-align:center"| <code>.</code> || Output the character signified by the cell at the pointer</p>
<p>|-</p>
<p>| style="text-align:center"| <code>,</code> || Input a character and store it in the cell at the pointer</p>
<p>|-</p>
<p>| style="text-align:center"| <code>[</code> || Jump past the matching <code>]</code> if the cell under the pointer is 0</p>
<p>|-</p>
<p>| style="text-align:center"| <code>]</code> || Jump back to the matching <code>[</code> if the cell under the pointer is nonzero</p>
<p>|}</p>
<p>Any cell size is allowed, EOF (<u>E</u>nd-<u>O</u>-<u>F</u>ile) support is optional, as is whether you have bounded or unbounded memory.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>brain(bye)</code> should retuen a string
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> should return <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> should return <code>Hello World!\\n</code>'
testString: 'assert.equal(brain(hello), "Hello World!\n", ''<code>brain(hello)</code> should return <code>Hello World!\\n</code>'');'
- 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", ''<code>brain(fib)</code> should return <code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function brain (prog) {
// Good luck!
}
```
</div>
### Before Test
<div id='js-setup'>
```js
let fib=`+
++
+++
++++
+>+>>
>>++++
+++++++
++++++++
+++++++++
++++++++++
++++++>++++
++++++++++++
+++++++++++++
+++<<<<<<[>[>>
>>>>+>+<<<<<<<-
]>>>>>>>[<<<<<<<
+>>>>>>>-]<[>++++
++++++[-<-[>>+>+<<
<-]>>>[<<<+>>>-]+<[
>[-]<[-]]>[<<[>>>+<<
<-]>>[-]]<<]>>>[>>+>+
<<<-]>>>[<<<+>>>-]+<[>
[-]<[-]]>[<<+>>[-]]<<<<
<<<]>>>>>[++++++++++++++
+++++++++++++++++++++++++
+++++++++.[-]]++++++++++<[
->-<]>+++++++++++++++++++++
+++++++++++++++++++++++++++.
[-]<<<<<<<<<<<<[>>>+>+<<<<-]>
>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]
<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+
>-]>[<+>-]<<<-]`;
let hello='++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'
let bye='++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.<+++++++.--------.<<<<<+.<+++.---.';
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,101 @@
---
title: Extensible prime generator
id: 598ee8b91b410510ae82efef
challengeType: 5
---
## Description
<section id='description'>
<p>Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.</p> The generator should be able to : Show the first <b>n</b> prime numbers.Show the prime numbers in a range.Show the number of primes in a range.Show the <b>n<sup>th</sup></b> prime number.<p>The function should have two parameters. The first will receive <b>n</b> or the range as an array. The second will receive a boolean, that specifies if the function returns the prime numbers as an array or a single number(the number of primes in the range or the <b>n<sup>th</sup></b> prime). According to the parameters the function should return an array.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>primeGenerator</code> is a function.
testString: 'assert(typeof primeGenerator === ''function'', ''<code>primeGenerator</code> is a 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], ''<code>primeGenerator</code> is a function.'');'
- text: <code>primeGenerator</code> is a function.
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> is a function.
testString: 'assert.equal(primeGenerator([7700, 8000], false), 30, ''<code>primeGenerator</code> is a function.'');'
- text: <code>primeGenerator</code> is a function.
testString: 'assert.equal(primeGenerator(10000, false), 104729, ''<code>primeGenerator</code> is a function.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function primeGenerator (num, showPrimes) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,89 @@
---
title: Factorial
id: 597b2b2a2702b44414742771
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function to return the factorial of a number.</p>
<p>Factorial of a number is given by : </p>
n! = n * (n-1) * (n-2) * ..... * 1
<p>
For example :
3! = 3*2*1 = 6
4! = 4*3*2*1 = 24
</p>
<p>Note :
0! = 1
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>factorial</code> is a function.
testString: 'assert(typeof factorial === ''function'', ''<code>factorial</code> is a function.'');'
- text: <code>factorial(2)</code> should return a number.
testString: 'assert(typeof factorial(2) === ''number'', ''<code>factorial(2)</code> should return a number.'');'
- text: <code>factorial(3)</code> should return 6.")
testString: 'assert.equal(factorial(3),results[0],"<code>factorial(3)</code> should return 6.");'
- text: <code>factorial(3)</code> should return 120.")
testString: 'assert.equal(factorial(5),results[1],"<code>factorial(3)</code> should return 120.");'
- text: '<code>factorial(3)</code> should return 3,628,800.")'
testString: 'assert.equal(factorial(10),results[2],"<code>factorial(3)</code> should return 3,628,800.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function factorial (n) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function factorial(n) {
let sum = 1;
while (n > 1) {
sum *= n;
n--;
}
return sum;
}
```
</section>

View File

@ -0,0 +1,134 @@
---
title: Factors of a Mersenne number
id: 598eea87e5cf4b116c3ff81a
challengeType: 5
---
## Description
<section id='description'>
<p>A Mersenne number is a number in the form of 2<sup>P</sup>-1.</p><p>If P is prime, the Mersenne number may be a Mersenne prime</p>
<p>(if P is not prime, the Mersenne number is also not prime).</p><p>In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, <a href="http://rosettacode.org/wiki/Lucas-Lehmer test" title="Lucas-Lehmer test">Lucas-Lehmer test</a>.</p><p>There are very efficient algorithms for determining if a number divides 2<sup>P</sup>-1 (or equivalently, if 2<sup>P</sup> mod (the number) = 1).</p>
<p>Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).</p><p>The following is how to implement this modPow yourself:</p><p>For example, let's compute 2<sup>23</sup> mod 47.</p>
<p>Convert the exponent 23 to binary, you get 10111. Starting with <tt>square</tt> = 1, repeatedly square it.</p>
<p>Remove the top bit of the exponent, and if it's 1 multiply <tt>square</tt> by the base of the exponentiation (2), then compute <tt>square</tt> modulo 47.</p>
<p>Use the result of the modulo from the last step as the initial value of <tt>square</tt> in the next step:</p><p>Remove Optional</p>
<p>square top bit multiply by 2 mod 47</p>
<p>------------ ------- ------------- ------</p>
<p>1*1 = 1 1 0111 1*2 = 2 2</p>
<p>2*2 = 4 0 111 no 4</p>
<p>4*4 = 16 1 11 16*2 = 32 32</p>
<p>32*32 = 1024 1 1 1024*2 = 2048 27</p>
<p>27*27 = 729 1 729*2 = 1458 1</p><p>Since 2<sup>23</sup> mod 47 = 1, 47 is a factor of 2<sup>P</sup>-1.</p>
<p>(To see this, subtract 1 from both sides: 2<sup>23</sup>-1 = 0 mod 47.)</p>
<p>Since we've shown that 47 is a factor, 2<sup>23</sup>-1 is not prime.</p>
<p>Further properties of Mersenne numbers allow us to refine the process even more.</p>
<p>Any factor q of 2<sup>P</sup>-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.</p>
<p>Finally any potential factor q must be <a href="http://rosettacode.org/wiki/Primality by Trial Division" title="Primality by Trial Division">prime</a>.</p>
<p>As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).</p><p>These primality tests only work on Mersenne numbers where P is prime. For example, M<sub>4</sub>=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.</p>
Task:
<p>Using the above method find a factor of 2<sup>929</sup>-1 (aka M929)</p>
Related tasks:
<a href="http://rosettacode.org/wiki/count in factors" title="count in factors">count in factors</a>
<a href="http://rosettacode.org/wiki/prime decomposition" title="prime decomposition">prime decomposition</a>
<a href="http://rosettacode.org/wiki/factors of an integer" title="factors of an integer">factors of an integer</a>
<a href="http://rosettacode.org/wiki/Sieve of Eratosthenes" title="Sieve of Eratosthenes">Sieve of Eratosthenes</a>
<a href="http://rosettacode.org/wiki/primality by trial division" title="primality by trial division">primality by trial division</a>
<a href="http://rosettacode.org/wiki/trial factoring of a Mersenne number" title="trial factoring of a Mersenne number">trial factoring of a Mersenne number</a>
<a href="http://rosettacode.org/wiki/partition an integer X into N primes" title="partition an integer X into N primes">partition an integer X into N primes</a>
<a href="http://rosettacode.org/wiki/sequence of primes by Trial Division" title="sequence of primes by Trial Division">sequence of primes by Trial Division</a>
<a href="https://www.youtube.com/watch?v=SNwvJ7psoow" title="link: https://www.youtube.com/watch?v=SNwvJ7psoow">Computers in 1948: 2¹²⁷-1</a>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>check_mersenne</code> is a function.
testString: 'assert(typeof check_mersenne === ''function'', ''<code>check_mersenne</code> is a function.'');'
- text: <code>check_mersenne(3)</code> should return a string.
testString: 'assert(typeof check_mersenne(3) == ''string'', ''<code>check_mersenne(3)</code> should return a string.'');'
- text: <code>check_mersenne(3)</code> should return "M3 = 2^3-1 is prime".
testString: 'assert.equal(check_mersenne(3),"M3 = 2^3-1 is prime",''<code>check_mersenne(3)</code> should return "M3 = 2^3-1 is prime".'');'
- text: <code>check_mersenne(23)</code> should return "M23 = 2^23-1 is composite with factor 47".
testString: 'assert.equal(check_mersenne(23),"M23 = 2^23-1 is composite with factor 47",''<code>check_mersenne(23)</code> should return "M23 = 2^23-1 is composite with factor 47".'');'
- text: <code>check_mersenne(929)</code> should return "M929 = 2^929-1 is composite with factor 13007
testString: 'assert.equal(check_mersenne(929),"M929 = 2^929-1 is composite with factor 13007",''<code>check_mersenne(929)</code> should return "M929 = 2^929-1 is composite with factor 13007'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function check_mersenne (p) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function check_mersenne(p){
function isPrime(value){
for (let i=2; i < value; i++){
if (value % i == 0){
return false;
}
if (value % i != 0){
return true;
}
}
}
function trial_factor(base, exp, mod){
let square, bits;
square = 1;
bits = exp.toString(2).split('');
for (let i=0,ln=bits.length; i<ln; i++){
square = Math.pow(square, 2) * (bits[i] == 1 ? base : 1) % mod;
}
return (square == 1);
}
function mersenne_factor(p){
let limit, k, q;
limit = Math.sqrt(Math.pow(2,p) - 1);
k = 1;
while ((2*k*p - 1) < limit){
q = 2*k*p + 1;
if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){
return q; // q is a factor of 2**p-1
}
k++;
}
return null;
}
let f, result;
result="M"+p+" = 2^"+p+"-1 is ";
f = mersenne_factor(p);
result+=f == null ? "prime" : "composite with factor "+f;
return result;
}
```
</section>

View File

@ -0,0 +1,83 @@
---
title: Factors of an integer
id: 597f1e7fbc206f0e9ba95dc4
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function that returns the factors of a positive integer.</p><p>These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.</p>
///
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>factors</code> is a function.
testString: 'assert(typeof factors === ''function'', ''<code>factors</code> is a function.'');'
- text: '<code>factors(45)</code> should return <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> should return <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> should return <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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function factors (num) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,91 @@
---
title: Farey sequence
id: 59c3ec9f15068017c96eb8a3
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function that returns the Farey sequence of order n. The function should have one parameter that is n. It should return the sequence as an array. Read the following for more details : </p><p>The <a href="https://en.wikipedia.org/wiki/Farey sequence" title="wp: Farey sequence">Farey sequence</a> F<sub>n</sub> of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.</p><p>The Farey sequence is sometimes incorrectly called a Farey series.</p>
<p>Each Farey sequence:</p>
<p>::* starts with the value 0, denoted by the fraction $ \frac{0}{1} $</p>
<p>::* ends with the value 1, denoted by the fraction $ \frac{1}{1}$.</p>
<p>The Farey sequences of orders 1 to 5 are:</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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>farey</code> is a function.
testString: 'assert(typeof farey === ''function'', ''<code>farey</code> is a function.'');'
- text: <code>farey(3)</code> should return an array
testString: 'assert(Array.isArray(farey(3)), ''<code>farey(3)</code> should return an array'');'
- 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"], ''<code>farey(3)</code> should return <code>["1/3","1/2","2/3"]</code>'');'
- 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"], ''<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> 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"], ''<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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function farey (n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,120 @@
---
title: Fibonacci n-step number sequences
id: 598eef80ba501f1268170e1e
challengeType: 5
---
## Description
<section id='description'>
<p>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 "f" then return the Fibonacci sequence and if it is "l", then return the Lucas sequence. The sequences must be returned as an array. More details are given below : </p><p>These number series are an expansion of the ordinary <a href="http://rosettacode.org/wiki/Fibonacci sequence" title="Fibonacci sequence">Fibonacci sequence</a> where:</p>
For $n = 2$ we have the Fibonacci sequence; with initial values $[1, 1]$ and $F_k^2 = F_{k-1}^2 + F_{k-2}^2$
For $n = 3$ we have the tribonacci sequence; with initial values $[1, 1, 2]$ and $F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3$
For $n = 4$ we have the tetranacci sequence; with initial values $[1, 1, 2, 4]$ and $F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4$...
For general $n>2$ we have the Fibonacci $n$-step sequence - $F_k^n$; with initial values of the first $n$ values of the $(n-1)$'th Fibonacci $n$-step sequence $F_k^{n-1}$; and $k$'th value of this $n$'th sequence being $F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}$
<p>For small values of $n$, <a href="https://en.wikipedia.org/wiki/Number prefix#Greek_series" title="wp: Number prefix#Greek_series">Greek numeric prefixes</a> are sometimes used to individually name each series.</p><p>{| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"</p>
<p>|+ Fibonacci $n$-step sequences</p>
<p>|- style="background-color: rgb(255, 204, 255);"</p>
<p>! $n$ !! Series name !! Values</p>
<p>|-</p>
<p>| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...</p>
<p>|-</p>
<p>| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...</p>
<p>|-</p>
<p>| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...</p>
<p>|-</p>
<p>| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...</p>
<p>|-</p>
<p>| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...</p>
<p>|-</p>
<p>| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...</p>
<p>|-</p>
<p>| 8 || octonacci || 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 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...</p>
<p>|}</p><p>Allied sequences can be generated where the initial values are changed:</p>
<p> The <a href="https://en.wikipedia.org/wiki/Lucas number" title="wp: Lucas number">Lucas series</a> sums the two preceding values like the fibonacci series for $n=2$ but uses $[2, 1]$ as its initial values.</p><p><!-- Lucas numbers, Lucas number, Lucas series [added to make searches easier.] --></p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fib_luc</code> is a function.
testString: 'assert(typeof fib_luc === ''function'', ''<code>fib_luc</code> is a 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],''<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,"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],''<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,"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],''<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,"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],''<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,"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],''<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,"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],''<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,"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],''<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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function fib_luc (n, len, w) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,76 @@
---
title: Fibonacci sequence
id: 597f24c1dda4e70f53c79c81
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function to generate the <big> n<sup>th</sup> </big> Fibonacci number.</p>
///<p>The <big> n<sup>th</sup> </big> Fibonacci number is given by :
///<p>F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></p>
///<p>The first two terms of the series are 0, 1.</p>
///<p>Hence, the series is : 0, 1, 1, 2, 3, 5, 8, 13...</p>
///
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fibonacci</code> is a function.
testString: 'assert(typeof fibonacci === ''function'', ''<code>fibonacci</code> is a function.'');'
- text: <code>fibonacci(2)</code> should return a number.
testString: 'assert(typeof fibonacci(2) == ''number'', ''<code>fibonacci(2)</code> should return a number.'');'
- text: <code>fibonacci(3)</code> should return 1.")
testString: 'assert.equal(fibonacci(3),1,"<code>fibonacci(3)</code> should return 1.");'
- text: <code>fibonacci(5)</code> should return 3.")
testString: 'assert.equal(fibonacci(5),3,"<code>fibonacci(5)</code> should return 3.");'
- text: <code>fibonacci(10)</code> should return 34.")
testString: 'assert.equal(fibonacci(10),34,"<code>fibonacci(10)</code> should return 34.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function fibonacci(n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function fibonacci(n) {
let a = 0, b = 1, t;
while (--n > 0) {
t = a;
a = b;
b += t;
}
return a;
}
```
</section>

View File

@ -0,0 +1,120 @@
---
title: Fibonacci word
id: 5992e222d397f00d21122931
challengeType: 5
---
## Description
<section id='description'>
<p>Write a function to return the Fibonacci Words upto N. N will be provided as a parameter to the function. The function should return an array of objects. The objects should be of the form : { N: 1, Length: 1, Entropy: 0, Word: '1' }. More details are given below : </p><p>The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence <a href="http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf" title="link: http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf">as described here</a>:</p><p>Define F_Word<sub>1</sub> as 1</p>
<p>Define F_Word<sub>2</sub> as 0</p>
<p>Form F_Word<sub>3</sub> as F_Word<sub>2</sub> concatenated with F_Word<sub>1</sub> i.e.: 01</p>
<p>Form F_Word<sub>n</sub> as F_Word<sub>n-1</sub> concatenated with F_word<sub>n-2</sub></p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fibWord</code> is a function.
testString: 'assert(typeof fibWord === ''function'', ''<code>fibWord</code> is a function.'');'
- text: <code>fibWord(5)</code> should return an array.
testString: 'assert(Array.isArray(fibWord(5)),''<code>fibWord(5)</code> should return an array.'');'
- text: <code>fibWord(5)</code> should return <code>'+JSON.stringify(ans)+'</code>.
testString: 'assert.deepEqual(fibWord(5),ans,''<code>fibWord(5)</code> should return <code>''+JSON.stringify(ans)+''</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function fibWord (n) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,117 @@
---
title: Fractran
id: 5a7dad05be01840e1778a0d1
challengeType: 3
---
## 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> is a Turing-complete esoteric programming language invented by the mathematician <a class="rosetta__link--wiki" href="https://en.wikipedia.org/wiki/John Horton Conway" title="wp: John Horton Conway">John Horton Conway</a>.</p><br/><p class="rosetta__paragraph">A FRACTRAN program is an ordered list of positive fractions $P = (f_1, f_2, \ldots, f_m)$, together with an initial positive integer input $n$.</p>
<br/><p class="rosetta__paragraph">The program is run by updating the integer $n$ as follows:</p><br/><ul class="rosetta__unordered-list"><li class="rosetta__list-item--unordered">for the first fraction, $f_i$, in the list for which $nf_i$ is an integer, replace $n$ with $nf_i$ ;</li>
<li class="rosetta__list-item--unordered">repeat this rule until no fraction in the list produces an integer when multiplied by $n$, then halt.</li></ul>
<br>
<p class="rosetta__paragraph">Conway gave a program for primes in FRACTRAN:</p><br/><p class="rosetta__paragraph"><span class="rosetta__text--indented"> $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$</span></p><br/><p class="rosetta__paragraph">Starting with $n=2$, this FRACTRAN program will change $n$ to $15=2\times (15/2)$, then $825=15\times (55/1)$, generating the following sequence of integers:</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">After 2, this sequence contains the following powers of 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">which are the prime powers of 2.</p>
<br/><dl class="rosetta__description-list"><dt class="rosetta__description-title">Task:</dt></dl>
<p class="rosetta__paragraph">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.</p></div>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fractran</code> should be a function.
testString: 'assert(typeof fractran==''function'',''<code>fractran</code> should be a function.'');'
- text: '<code>fractran("''+tests[0]+''")</code> should return an array.'
testString: 'assert(Array.isArray(fractran(tests[0])),''<code>fractran("''+tests[0]+''")</code> should return an array.'');'
- text: '<code>fractran("''+tests[0]+''")</code> should return <code>''+JSON.stringify(results[0])+''</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("''+tests[1]+''")</code> should return <code>''+JSON.stringify(results[1])+''</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("''+tests[2]+''")</code> should return <code>''+JSON.stringify(results[2])+''</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("''+tests[3]+''")</code> should return <code>''+JSON.stringify(results[3])+''</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("''+tests[4]+''")</code> should return <code>''+JSON.stringify(results[4])+''</code>.'
testString: 'assert.deepEqual(fractran(tests[4]),results[4],''<code>fractran("''+tests[4]+''")</code> should return <code>''+JSON.stringify(results[4])+''</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function fractran (progStr) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,98 @@
---
title: Gamma function
id: 5a23c84252665b21eecc7e76
challengeType: 5
---
## Description
<section id='description'>
Implement one algorithm (or more) to compute the <a href="https://en.wikipedia.org/wiki/Gamma function">Gamma</a> ($\Gamma$) function (in the real field only).
The Gamma function can be defined as:
<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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>gamma</code> should be a function.
testString: 'assert(typeof gamma==''function'',''<code>gamma</code> should be a function.'')'
- text: '<code>gamma(''+tests[0]+'')</code> should return a number.'
testString: 'assert(typeof gamma(tests[0])==''number'',''<code>gamma(''+tests[0]+'')</code> should return a number.'')'
- text: '<code>gamma(''+tests[0]+'')</code> should return <code>''+results[0]+''</code>.'
testString: 'assert.equal(gamma(tests[0]),results[0],''<code>gamma(''+tests[0]+'')</code> should return <code>''+results[0]+''</code>.'')'
- text: '<code>gamma(''+tests[1]+'')</code> should return <code>''+results[1]+''</code>.'
testString: 'assert.equal(gamma(tests[1]),results[1],''<code>gamma(''+tests[1]+'')</code> should return <code>''+results[1]+''</code>.'')'
- text: '<code>gamma(''+tests[2]+'')</code> should return <code>''+results[2]+''</code>.'
testString: 'assert.equal(gamma(tests[2]),results[2],''<code>gamma(''+tests[2]+'')</code> should return <code>''+results[2]+''</code>.'')'
- text: '<code>gamma(''+tests[3]+'')</code> should return <code>''+results[3]+''</code>.'
testString: 'assert.equal(gamma(tests[3]),results[3],''<code>gamma(''+tests[3]+'')</code> should return <code>''+results[3]+''</code>.'')'
- text: '<code>gamma(''+tests[4]+'')</code> should return <code>''+results[4]+''</code>.'
testString: 'assert.equal(gamma(tests[4]),results[4],''<code>gamma(''+tests[4]+'')</code> should return <code>''+results[4]+''</code>.'')'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gamma (x) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,176 @@
---
title: Gaussian elimination
id: 5a23c84252665b21eecc7e77
challengeType: 5
---
## Description
<section id='description'>
Write a function to solve \(A.x = b\) using Gaussian elimination then backwards substitution. \(A\) being an \(n \times n\) matrix. Also, \(x\) and \(b\) are \(n\) by 1 vectors. To improve accuracy, please use partial pivoting and scaling.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>gaussianElimination</code> should be a function.'''
testString: 'assert(typeof gaussianElimination==''function'',''<code>gaussianElimination</code> should be a function.'');'
- text: '''<code>gaussianElimination(''+JSON.stringify(tests[0][0])+'',''+JSON.stringify(tests[0][1])+'')</code> should return an array.'''
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(''+JSON.stringify(tests[0][0])+'',''+JSON.stringify(tests[0][1])+'')</code> should return <code>''+JSON.stringify(results[0])+''</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(''+JSON.stringify(tests[1][0])+'',''+JSON.stringify(tests[1][1])+'')</code> should return <code>''+JSON.stringify(results[1])+''</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(''+JSON.stringify(tests[2][0])+'',''+JSON.stringify(tests[2][1])+'')</code> should return <code>''+JSON.stringify(results[2])+''</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(''+JSON.stringify(tests[3][0])+'',''+JSON.stringify(tests[3][1])+'')</code> should return <code>''+JSON.stringify(results[3])+''</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(''+JSON.stringify(tests[4][0])+'',''+JSON.stringify(tests[4][1])+'')</code> should return <code>''+JSON.stringify(results[4])+''</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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gaussianElimination (A,b) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,98 @@
---
title: General FizzBuzz
id: 5a23c84252665b21eecc7e78
challengeType: 5
---
## Description
<section id='description'>
Write a generalized version of <a href="http://rosettacode.org/wiki/FizzBuzz">FizzBuzz</a> that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the rules of the game are supplied to the user. Create a function to implement this. The function should take two parameters.
The first will be an array with the FizzBuzz rules. For example: <code>[ [3,"Fizz"] , [5,"Buzz"] ]</code>.
This indcates that <code>Fizz</code> should be printed if the number is a multiple of 3 and <code>Buzz</code> if it is a multiple of 5. If it is a multiple of both then the strings should be concatenated in the order specified in the array. In this case, <code>FizzBuzz</code> if the number is a multiple of 3 and 5.
The second parameter is the number for which the function should return a string as stated above.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>genFizzBuzz</code> should be a function.'''
testString: 'assert(typeof genFizzBuzz==''function'',''<code>genFizzBuzz</code> should be a function.'');'
- text: '''<code>genFizzBuzz(''+JSON.stringify(tests[0][0])+'',''+tests[0][1]+'')</code> should return a type.'''
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(''+JSON.stringify(tests[0][0])+'',''+tests[0][1]+'')</code> should return <code>"''+results[0]+''"</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(''+JSON.stringify(tests[1][0])+'',''+tests[1][1]+'')</code> should return <code>"''+results[1]+''"</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(''+JSON.stringify(tests[2][0])+'',''+tests[2][1]+'')</code> should return <code>"''+results[2]+''"</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(''+JSON.stringify(tests[3][0])+'',''+tests[3][1]+'')</code> should return <code>"''+results[3]+''"</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(''+JSON.stringify(tests[4][0])+'',''+tests[4][1]+'')</code> should return <code>"''+results[4]+''"</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(''+JSON.stringify(tests[5][0])+'',''+tests[5][1]+'')</code> should return <code>"''+results[5]+''"</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(''+JSON.stringify(tests[6][0])+'',''+tests[6][1]+'')</code> should return <code>"''+results[6]+''"</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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function genFizzBuzz (rules, num) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,91 @@
---
title: Generate lower case ASCII alphabet
id: 5a23c84252665b21eecc7e7a
challengeType: 5
---
## Description
<section id='description'>
Write a function to generate an array of lower case ASCII characters, for a given range. For example: for range 1 to 4 the function should return <code>['a','b','c','d']</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>lascii</code> should be a function.'''
testString: 'assert(typeof lascii==''function'',''<code>lascii</code> should be a function.'');'
- text: '''<code>lascii("a","d")</code> should return an array.'''
testString: 'assert(Array.isArray(lascii(''a'',''d'')),''<code>lascii("a","d")</code> should return an array.'');'
- text: '"<code>lascii(''a'',''d'')</code> should return <code>[ ''a'', ''b'', ''c'', ''d'' ]</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(''c'',''i'')</code> should return <code>[ ''c'', ''d'', ''e'', ''f'', ''g'', ''h'', ''i'' ]</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(''m'',''q'')</code> should return <code>[ ''m'', ''n'', ''o'', ''p'', ''q'' ]</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(''k'',''n'')</code> should return <code>[ ''k'', ''l'', ''m'', ''n'' ]</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(''t'',''z'')</code> should return <code>[ ''t'', ''u'', ''v'', ''w'', ''x'', ''y'', ''z'' ]</code>."'
testString: 'assert.deepEqual(lascii("t","z"),results[4],"<code>lascii(''t'',''z'')</code> should return <code>[ ''t'', ''u'', ''v'', ''w'', ''x'', ''y'', ''z'' ]</code>.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function lascii (cFrom, cTo) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,106 @@
---
title: GeneratorExponential
id: 5a23c84252665b21eecc7e7b
challengeType: 5
---
## Description
<section id='description'>
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Write a function that uses generators to generate squares and cubes. Create a new generator that filters all cubes from the generator of squares.
The function should return the \( n^{th} \) value of the filtered generator.
For example for \(n=7\), the function should return 81 as the sequence would be 4,9,16,25,36,49,81. Here 64 is filtered out, as it is a cube.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>exponentialGenerator</code> should be a function.'''
testString: 'assert(typeof exponentialGenerator==''function'',''<code>exponentialGenerator</code> should be a function.'');'
- text: '''<code>exponentialGenerator()</code> should return a number.'''
testString: 'assert(typeof exponentialGenerator(10)==''number'',''<code>exponentialGenerator()</code> should return a number.'');'
- text: '''<code>exponentialGenerator(10)</code> should return <code>144</code>.'''
testString: 'assert.equal(exponentialGenerator(10),144,''<code>exponentialGenerator(10)</code> should return <code>144</code>.'');'
- text: '''<code>exponentialGenerator(12)</code> should return <code>196</code>.'''
testString: 'assert.equal(exponentialGenerator(12),196,''<code>exponentialGenerator(12)</code> should return <code>196</code>.'');'
- text: '''<code>exponentialGenerator(14)</code> should return <code>256</code>.'''
testString: 'assert.equal(exponentialGenerator(14),256,''<code>exponentialGenerator(14)</code> should return <code>256</code>.'');'
- text: '''<code>exponentialGenerator(20)</code> should return <code>484</code>.'''
testString: 'assert.equal(exponentialGenerator(20),484,''<code>exponentialGenerator(20)</code> should return <code>484</code>.'');'
- text: '''<code>exponentialGenerator(25)</code> should return <code>784</code>.'''
testString: 'assert.equal(exponentialGenerator(25),784,''<code>exponentialGenerator(25)</code> should return <code>784</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function exponentialGenerator (n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function exponentialGenerator(n){
function* PowersGenerator(m) {
var n=0;
while(1) {
yield Math.pow(n, m);
n += 1;
}
}
function* FilteredGenerator(g, f){
var value = g.next().value;
var filter = f.next().value;
while(1) {
if( value < filter ) {
yield value;
value = g.next().value;
} else if ( value > filter ) {
filter = f.next().value;
} else {
value = g.next().value;
filter = f.next().value;
}
}
}
var squares = PowersGenerator(2);
var cubes = PowersGenerator(3);
var filtered = FilteredGenerator(squares, cubes);
var curr=0;
for(var i=0;i<n;i++) curr=filtered.next();
return curr.value;
}
```
</section>

View File

@ -0,0 +1,89 @@
---
title: Gray code
id: 5a23c84252665b21eecc7e80
challengeType: 5
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Gray code">Gray code</a> is a form of binary encoding where transitions between consecutive numbers differ by only one bit.
This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs.
It is also useful for generating inputs for <a href="https://en.wikipedia.org/wiki/Karnaugh map">Karnaugh maps</a> in order from left to right or top to bottom.
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."<br>Encoding (MSB is bit 0, b is binary, g is Gray code):
<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> Or: <br><code> g = b xor (b logically right shifted 1 time)</code><br>Decoding (MSB is bit 0, b is binary, g is Gray code): <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>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>gray</code> should be a function.'''
testString: 'assert(typeof gray==''function'',''<code>gray</code> should be a function.'');'
- text: '''<code>gray(true,177)</code> should return a number.'''
testString: 'assert(typeof gray(true,177)==''number'',''<code>gray(true,177)</code> should return a number.'');'
- text: '''<code>gray(true,177)</code> should return <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> should return <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> should return <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> should return <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> should return <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> should return <code>870</code>.'''
testString: 'assert.equal(gray(false,725),870,''<code>gray(false,725)</code> should return <code>870</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gray(enc, number) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function gray(enc, number){
if(enc){
return number ^ (number >> 1);
}else{
let n = number;
while (number >>= 1) {
n ^= number;
}
return n;
}
}
```
</section>

View File

@ -0,0 +1,71 @@
---
title: Greatest common divisor
id: 5a23c84252665b21eecc7e82
challengeType: 5
---
## Description
<section id='description'>
Write a function that returns the greatest common divisor of two integers.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>gcd</code> should be a function.'''
testString: 'assert(typeof gcd==''function'',''<code>gcd</code> should be a function.'');'
- text: '''<code>gcd(24,36)</code> should return a number.'''
testString: 'assert(typeof gcd(24,36)==''number'',''<code>gcd(24,36)</code> should return a number.'');'
- text: '''<code>gcd(24,36)</code> should return <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> should return <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> should return <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> should return <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> should return <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> should return <code>50</code>.'''
testString: 'assert.equal(gcd(1300,250),50,''<code>gcd(1300,250)</code> should return <code>50</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gcd(a, b) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function gcd(a, b) {
return b==0 ? Math.abs(a):gcd(b, a % b);
}
```
</section>

View File

@ -0,0 +1,104 @@
---
title: Greatest subsequential sum
id: 5a23c84252665b21eecc7e84
challengeType: 5
---
## Description
<section id='description'>
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of \( 0 \); thus if all elements are negative, the result must be the empty sequence.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>maximumSubsequence</code> should be a function.'''
testString: 'assert(typeof maximumSubsequence==''function'',''<code>maximumSubsequence</code> should be a function.'');'
- text: '''<code>maximumSubsequence(''+JSON.stringify(tests[0])+'')</code> should return an array.'''
testString: 'assert(Array.isArray(maximumSubsequence(tests[0])),''<code>maximumSubsequence(''+JSON.stringify(tests[0])+'')</code> should return an array.'');'
- text: '''<code>maximumSubsequence(''+JSON.stringify(tests[0])+'')</code> should return <code>''+JSON.stringify(results[0])+''</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(''+JSON.stringify(tests[1])+'')</code> should return <code>''+JSON.stringify(results[1])+''</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(''+JSON.stringify(tests[2])+'')</code> should return <code>''+JSON.stringify(results[2])+''</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(''+JSON.stringify(tests[3])+'')</code> should return <code>''+JSON.stringify(results[3])+''</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(''+JSON.stringify(tests[4])+'')</code> should return <code>''+JSON.stringify(results[4])+''</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(''+JSON.stringify(tests[5])+'')</code> should return <code>''+JSON.stringify(results[5])+''</code>.'''
testString: 'assert.deepEqual(maximumSubsequence(tests[5]),results[5],''<code>maximumSubsequence(''+JSON.stringify(tests[5])+'')</code> should return <code>''+JSON.stringify(results[5])+''</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function maximumSubsequence (population) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,109 @@
---
title: Hailstone sequence
id: 595608ff8bcd7a50bd490181
challengeType: 5
---
## Description
<section id='description'>
<p>The Hailstone sequence of numbers can be generated from a starting positive integer, n by:</p>
If n is 1 then the sequence ends.
If n is even then the next n of the sequence <code> = n/2 </code>
If n is odd then the next n of the sequence <code> = (3 * n) + 1 </code><p>The (unproven) <a href="https://en.wikipedia.org/wiki/Collatz conjecture" title="wp: Collatz conjecture">Collatz conjecture</a> is that the hailstone sequence for any starting number always terminates.</p>
<p>The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the Collatz sequence.</p>
Task:
Create a routine to generate the hailstone sequence for a number.
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>
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!)See also:
<a href="http://xkcd.com/710" title="link: http://xkcd.com/710">xkcd</a> (humourous).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hailstoneSequence</code> is a function.
testString: 'assert(typeof hailstoneSequence === ''function'', ''<code>hailstoneSequence</code> is a function.'');'
- text: '<code>hailstoneSequence()</code> should return <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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// noprotect
function hailstoneSequence () {
const res = [];
// Good luck!
return res;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,97 @@
---
title: Happy numbers
id: 594810f028c0303b75339ad1
challengeType: 5
---
## Description
<section id='description'>
<p>A happy number is defined by the following process:</p>
<p>Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers.</p>
<p>Implement a function that returns true if the number is happy, or false if not.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>happy</code> is a function.
testString: 'assert(typeof happy === ''function'', ''<code>happy</code> is a function.'');'
- text: <code>happy(1)</code> should return a boolean.
testString: 'assert(typeof happy(1) === ''boolean'', ''<code>happy(1)</code> should return a boolean.'');'
- text: <code>happy(1)</code> should return true.
testString: 'assert(happy(1), ''<code>happy(1)</code> should return true.'');'
- text: <code>happy(2)</code> should return false.
testString: 'assert(!happy(2), ''<code>happy(2)</code> should return false.'');'
- text: <code>happy(7)</code> should return true.
testString: 'assert(happy(7), ''<code>happy(7)</code> should return true.'');'
- text: <code>happy(10)</code> should return true.
testString: 'assert(happy(10), ''<code>happy(10)</code> should return true.'');'
- text: <code>happy(13)</code> should return true.
testString: 'assert(happy(13), ''<code>happy(13)</code> should return true.'');'
- text: <code>happy(19)</code> should return true.
testString: 'assert(happy(19), ''<code>happy(19)</code> should return true.'');'
- text: <code>happy(23)</code> should return true.
testString: 'assert(happy(23), ''<code>happy(23)</code> should return true.'');'
- text: <code>happy(28)</code> should return true.
testString: 'assert(happy(28), ''<code>happy(28)</code> should return true.'');'
- text: <code>happy(31)</code> should return true.
testString: 'assert(happy(31), ''<code>happy(31)</code> should return true.'');'
- text: '<code>happy(32)</code> should return true:.'
testString: 'assert(happy(32), ''<code>happy(32)</code> should return true:.'');'
- text: <code>happy(33)</code> should return false.
testString: 'assert(!happy(33), ''<code>happy(33)</code> should return false.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function happy (number) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,106 @@
---
title: Harshad or Niven series
id: 595668ca4cfe1af2fb9818d4
challengeType: 5
---
## Description
<section id='description'>
<p>The <a href="http://mathworld.wolfram.com/HarshadNumber.html" title="link: http://mathworld.wolfram.com/HarshadNumber.html">Harshad</a> or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.</p><p>For example, 42 is a <a href="http://rosettacode.org/wiki/oeis:A005349" title="oeis:A005349">Harshad number</a> as 42 is divisible by (4 + 2) without remainder.</p>
Assume that the series is defined as the numbers in increasing order.
Task:
<p>Implement a function to generate successive members of the Harshad sequence.</p><p>Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isHarshadOrNiven</code> is a function.
testString: 'assert(typeof isHarshadOrNiven === ''function'', ''<code>isHarshadOrNiven</code> is a 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, ''<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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isHarshadOrNiven () {
const res = {
firstTwenty: [],
firstOver1000: undefined
};
// Change after this line
return res;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,83 @@
---
title: Hash from two arrays
id: 595671d4d2cdc305f0d5b36f
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values)</p>
Related task:
<a href="http://rosettacode.org/wiki/Associative arrays/Creation" title="Associative arrays/Creation">Associative arrays/Creation</a>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>arrToObj</code> is a function.
testString: 'assert(typeof arrToObj === ''function'', ''<code>arrToObj</code> is a 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], ''<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], ["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], ''<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], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c" }</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(["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], ''<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(["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], ''<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(["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], ''<code>arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 }</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function arrToObj (keys, vals) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function arrToObj (keys, vals) {
return keys.reduce((map, key, index) => {
map[key] = vals[index];
return map;
}, {});
}
```
</section>

View File

@ -0,0 +1,249 @@
---
title: Hash join
id: 5956795bc9e2c415eb244de1
challengeType: 5
---
## Description
<section id='description'>
<p>An <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join" title="wp: Join_(SQL)#Inner_join">inner join</a> is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the <a href="https://en.wikipedia.org/wiki/Nested loop join" title="wp: Nested loop join">nested loop join</a> algorithm, but a more scalable alternative is the <a href="https://en.wikipedia.org/wiki/hash join" title="wp: hash join">hash join</a> algorithm.</p>
<p>Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.</p><p>You should represent the tables as data structures that feel natural in your programming language.</p>
<p>The "hash join" algorithm consists of two steps:</p>
Hash phase: Create a <a href="https://en.wikipedia.org/wiki/Multimap" title="wp: Multimap">multimap</a> from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
<p>In pseudo-code, the algorithm could be expressed as follows:</p>
<pre>
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let j<sub>A</sub> = the join column ID of table A
let j<sub>B</sub> = the join column ID of table B
let M<sub>B</sub> = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap M<sub>B</sub> under key b(j<sub>B</sub>)
for each row a in table A:
for each row b in multimap M<sub>B</sub> under key a(j<sub>A</sub>):
let c = the concatenation of row a and row b
place row c in table C</p>
</pre>
Test-case
<p>Input</p>
<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>
<p>Output</p>
<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>
<p></p><p></p><p>The order of the rows in the output table is not significant.</p>
<p>If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form <code style="white-space:nowrap">[[27, "Jonah"], ["Jonah", "Whales"]]</code>.</p><hr>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hashJoin</code> is a function.
testString: 'assert(typeof hashJoin === ''function'', ''<code>hashJoin</code> is a 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, ''<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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function hashJoin (hash1, hash2) {
// Good luck!
return [];
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,140 @@
---
title: Heronian triangles
id: 595b98f8b5a2245e243aa831
challengeType: 5
---
## Description
<section id='description'>
<p><a href="https://en.wikipedia.org/wiki/Heron's formula" title="wp: Heron's formula">Hero's formula</a> for the area of a triangle given the length of its three sides <big> a,</big> <big>b,</big> and <big>c</big> is given by:</p><p><big>$$A = \sqrt{s(s-a)(s-b)(s-c)},$$</big></p><p>where <big>s</big> is half the perimeter of the triangle; that is,</p><p><big>$$s=\frac{a+b+c}{2}.$$</big></p>
<p><a href="http://www.had2know.com/academics/heronian-triangles-generator-calculator.html" title="link: http://www.had2know.com/academics/heronian-triangles-generator-calculator.html">Heronian triangles</a> are triangles whose sides and area are all integers.</p>
<p> An example is the triangle with sides 3, 4, 5 whose area is 6 (and whose perimeter is 12). </p>
<p>Note that any triangle whose sides are all an integer multiple of 3, 4, 5; such as 6, 8, 10, will also be a Heronian triangle.</p><p>Define a Primitive Heronian triangle as a Heronian triangle where the greatest common divisor</p>
<p>of all three sides is 1 (unity).</p><p>This will exclude, for example, triangle 6, 8, 10.</p>
Task:
<p>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.</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>heronianTriangle</code> is a function.
testString: 'assert(typeof heronianTriangle === ''function'', ''<code>heronianTriangle</code> is a 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], ''<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> 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], ''<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> 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], ''<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> 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], ''<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>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// noprotect
function heronianTriangle (n) {
// Good luck!
return [];
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,127 @@
---
title: Hofstadter Figure-Figure sequences
id: 59622f89e4e137560018a40e
challengeType: 5
---
## Description
<section id='description'>
<p>These two sequences of positive integers are defined as:</p>
<p><big>$$R(1)=1\ ;\ S(1)=2 \\R(n)=R(n-1)+S(n-1), \quad n>1.$$</big></p>
<p>The sequence <big>$S(n)$</big> is further defined as the sequence of positive integers not present in <big>$R(n)$</big>.</p><p>Sequence <big>$R$</big> starts:</p>
<p>1, 3, 7, 12, 18, ...</p>
<p>Sequence <big>$S$</big> starts:</p>
<p>2, 4, 5, 6, 8, ...</p>
Task:
Create two functions named ffr and ffs that when given n return R(n) or S(n) respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
No maximum value for n should be assumed.
Sloane's <a href="http://oeis.org/A005228" title="link: http://oeis.org/A005228">A005228</a> and <a href="http://oeis.org/A030124" title="link: http://oeis.org/A030124">A030124</a>.
<a href="http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html" title="link: 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 sequences</a>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>ffr</code> is a function.
testString: 'assert(typeof ffr === ''function'', ''<code>ffr</code> is a function.'');'
- text: <code>ffs</code> is a function.
testString: 'assert(typeof ffs === ''function'', ''<code>ffs</code> is a function.'');'
- text: <code>ffr</code> should return integer.
testString: 'assert(Number.isInteger(ffr(1)), ''<code>ffr</code> should return integer.'');'
- text: <code>ffs</code> should return integer.
testString: 'assert(Number.isInteger(ffs(1)), ''<code>ffs</code> should return integer.'');'
- text: <code>ffr()</code> should return <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> should return <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> should return <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> should return <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> should return <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> should return <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> should return <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> should return <code>1041</code>
testString: 'assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1], ''<code>ffs()</code> should return <code>1041</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// noprotect
function ffr(n) {
return n;
}
function ffs(n) {
return n;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,89 @@
---
title: Hofstadter Q sequence
id: 59637c4d89f6786115efd814
challengeType: 5
---
## Description
<section id='description'>
<p>The <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence" title="wp: Hofstadter_sequence#Hofstadter_Q_sequence">Hofstadter Q sequence</a> is defined as:</p>
<p>$Q(1)=Q(2)=1, \\ Q(n)=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)), \quad n>2.$</p>
<p>It is defined like the <a href="http://rosettacode.org/wiki/Fibonacci sequence" title="Fibonacci sequence">Fibonacci sequence</a>, but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.</p>
Task:
Implement the Hofstadter Q Sequence equation into JavaScript
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hofstadterQ</code> is a function.
testString: 'assert(typeof hofstadterQ === ''function'', ''<code>hofstadterQ</code> is a function.'');'
- text: <code>hofstadterQ()</code> should return <code>integer</code>
testString: 'assert(Number.isInteger(hofstadterQ(1000)), ''<code>hofstadterQ()</code> should return <code>integer</code>'');'
- text: <code>hofstadterQ(1000)</code> should return <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> should return <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> should return <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> should return <code>1261</code>
testString: 'assert.equal(hofstadterQ(testCase[3]), res[3], ''<code>hofstadterQ(2500)</code> should return <code>1261</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function hofstadterQ (n) {
// Good luck!
return n;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,80 @@
---
title: I before E except after C
id: 5a23c84252665b21eecc7eb0
challengeType: 5
---
## Description
<section id='description'>
The phrase <a href="https://en.wikipedia.org/wiki/I before E except after C"> "I before E, except after C"</a> is a widely known mnemonic which is supposed to help when spelling English words.
Using the words provided, check if the two sub-clauses of the phrase are plausible individually:
<ol><li style='margin-bottom: 5px;'><i>"I before E when not preceded by C".</i></li><li><i>"E before I when preceded by C".</i></li></ol>
If both sub-phrases are plausible then the original phrase can be said to be plausible.
Write a function that accepts a word and check if the word follows this rule. The function should return true if it follows the rule otherwise false.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>IBeforeExceptC</code> should be a function.'''
testString: 'assert(typeof IBeforeExceptC==''function'',''<code>IBeforeExceptC</code> should be a function.'');'
- text: '''<code>IBeforeExceptC("receive")</code> should return a boolean.'''
testString: 'assert(typeof IBeforeExceptC("receive")==''boolean'',''<code>IBeforeExceptC("receive")</code> should return a boolean.'');'
- text: '''<code>IBeforeExceptC("receive")</code> should return <code>true</code>.'''
testString: 'assert.equal(IBeforeExceptC("receive"),true,''<code>IBeforeExceptC("receive")</code> should return <code>true</code>.'');'
- text: '''<code>IBeforeExceptC("science")</code> should return <code>false</code>.'''
testString: 'assert.equal(IBeforeExceptC("science"),false,''<code>IBeforeExceptC("science")</code> should return <code>false</code>.'');'
- text: '''<code>IBeforeExceptC("imperceivable")</code> should return <code>true</code>.'''
testString: 'assert.equal(IBeforeExceptC("imperceivable"),true,''<code>IBeforeExceptC("imperceivable")</code> should return <code>true</code>.'');'
- text: '''<code>IBeforeExceptC("inconceivable")</code> should return <code>true</code>.'''
testString: 'assert.equal(IBeforeExceptC("inconceivable"),true,''<code>IBeforeExceptC("inconceivable")</code> should return <code>true</code>.'');'
- text: '''<code>IBeforeExceptC("insufficient")</code> should return <code>false</code>.'''
testString: 'assert.equal(IBeforeExceptC("insufficient"),false,''<code>IBeforeExceptC("insufficient")</code> should return <code>false</code>.'');'
- text: '''<code>IBeforeExceptC("omniscient")</code> should return <code>false</code>.'''
testString: 'assert.equal(IBeforeExceptC("omniscient"),false,''<code>IBeforeExceptC("omniscient")</code> should return <code>false</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function IBeforeExceptC (word) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,102 @@
---
title: IBAN
id: 5a23c84252665b21eecc7eaf
challengeType: 5
---
## Description
<section id='description'>
The <a href="https://en.wikipedia.org/wiki/International_Bank_Account_Number">International Bank Account Number (IBAN)</a> is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating <a href="https://en.wikipedia.org/wiki/Transcription_error">transcription errors</a>.
The IBAN consists of up to 34 alphanumeric characters:
<ul>
<li>first the two-letter ISO 3166-1 alpha-2 country code</li>
<li>then two check digits, and</li>
<li>finally a country-specific Basic Bank Account Number (BBAN).</li>
</ul>
The check digits enable a sanity check of the bank account number to confirm its integrity even before submitting a transaction.
Write a function that takes IBAN string as parameter. If it is valid return true. Otherwise, return false.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>isValid</code> should be a function.'''
testString: 'assert(typeof isValid==''function'',''<code>isValid</code> should be a function.'');'
- text: '''<code>isValid("''+tests[0]+''")</code> should return a boolean.'''
testString: 'assert(typeof isValid(tests[0])==''boolean'',''<code>isValid("''+tests[0]+''")</code> should return a boolean.'');'
- text: '''<code>isValid("''+tests[0]+''")</code> should return <code>true</code>.'''
testString: 'assert.equal(isValid(tests[0]),true,''<code>isValid("''+tests[0]+''")</code> should return <code>true</code>.'');'
- text: '''<code>isValid("''+tests[1]+''")</code> should return <code>false</code>.'''
testString: 'assert.equal(isValid(tests[1]),false,''<code>isValid("''+tests[1]+''")</code> should return <code>false</code>.'');'
- text: '''<code>isValid("''+tests[2]+''")</code> should return <code>false</code>.'''
testString: 'assert.equal(isValid(tests[2]),false,''<code>isValid("''+tests[2]+''")</code> should return <code>false</code>.'');'
- text: '''<code>isValid("''+tests[3]+''")</code> should return <code>false</code>.'''
testString: 'assert.equal(isValid(tests[3]),false,''<code>isValid("''+tests[3]+''")</code> should return <code>false</code>.'');'
- text: '''<code>isValid("''+tests[4]+''")</code> should return <code>true</code>.'''
testString: 'assert.equal(isValid(tests[4]),true,''<code>isValid("''+tests[4]+''")</code> should return <code>true</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isValid (iban) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,83 @@
---
title: Identity matrix
id: 5a23c84252665b21eecc7eb1
challengeType: 5
---
## Description
<section id='description'>
An <i>identity matrix</i> is a square matrix of size \( n \times n \),
where the diagonal elements are all <b>1</b>s (ones),
and all the other elements are all <b>0</b>s (zeroes).
\begin{bmatrix} 1 & 0 & 0 \cr 0 & 1 & 0 \cr 0 & 0 & 1 \cr \end{bmatrix}
Write a function that takes a number 'n' as a parameter and returns the identity matrix of order n x n.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>idMatrix</code> should be a function.'''
testString: 'assert(typeof idMatrix==''function'',''<code>idMatrix</code> should be a function.'');'
- text: '''<code>idMatrix(1)</code> should return an array.'''
testString: 'assert(Array.isArray(idMatrix(1)),''<code>idMatrix(1)</code> should return an array.'');'
- text: '''<code>idMatrix(1)</code> should return <code>''+JSON.stringify(results[0])+''</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> should return <code>''+JSON.stringify(results[1])+''</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> should return <code>''+JSON.stringify(results[2])+''</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> should return <code>''+JSON.stringify(results[3])+''</code>.'''
testString: 'assert.deepEqual(idMatrix(4),results[3],''<code>idMatrix(4)</code> should return <code>''+JSON.stringify(results[3])+''</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function idMatrix (n) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,83 @@
---
title: Iterated digits squaring
id: 5a23c84252665b21eecc7ec1
challengeType: 5
---
## Description
<section id='description'>
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
<pre>15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1</pre>
Write a function that takes a number as a parameter and returns 1 or 89 after performing the mentioned process.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>iteratedSquare</code> should be a function.'''
testString: 'assert(typeof iteratedSquare==''function'',''<code>iteratedSquare</code> should be a function.'');'
- text: '''<code>iteratedSquare(4)</code> should return a number.'''
testString: 'assert(typeof iteratedSquare(4)==''number'',''<code>iteratedSquare(4)</code> should return a number.'');'
- text: '''<code>iteratedSquare(4)</code> should return <code>89</code>.'''
testString: 'assert.equal(iteratedSquare(4),89,''<code>iteratedSquare(4)</code> should return <code>89</code>.'');'
- text: '''<code>iteratedSquare(7)</code> should return <code>1</code>.'''
testString: 'assert.equal(iteratedSquare(7),1,''<code>iteratedSquare(7)</code> should return <code>1</code>.'');'
- text: '''<code>iteratedSquare(15)</code> should return <code>89</code>.'''
testString: 'assert.equal(iteratedSquare(15),89,''<code>iteratedSquare(15)</code> should return <code>89</code>.'');'
- text: '''<code>iteratedSquare(20)</code> should return <code>89</code>.'''
testString: 'assert.equal(iteratedSquare(20),89,''<code>iteratedSquare(20)</code> should return <code>89</code>.'');'
- text: '''<code>iteratedSquare(70)</code> should return <code>1</code>.'''
testString: 'assert.equal(iteratedSquare(70),1,''<code>iteratedSquare(70)</code> should return <code>1</code>.'');'
- text: '''<code>iteratedSquare(100)</code> should return <code>1</code>.'''
testString: 'assert.equal(iteratedSquare(100),1,''<code>iteratedSquare(100)</code> should return <code>1</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function iteratedSquare (n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,125 @@
---
title: Jaro distance
id: 5a23c84252665b21eecc7ec2
challengeType: 5
---
## Description
<section id='description'>
The Jaro distance is a measure of similarity between two strings. The higher the Jaro distance for two strings is, the more similar the strings are. The score is normalized such that <b>0</b> equates to no similarity and <b>1</b> is an exact match. Definition The Jaro distance \( d_j \) of two given strings \(s_1\) and \(s_2\) is
\begin{align}d_j = \begin{cases}0&amp; & \text{if }m=0 \\\\{\frac {1}{3}}\left({\frac {m}{|s_{1}|}}+{\frac {m}{|s_{2}|}}+{\frac {m-t}{m}}\right)&amp; & \text{otherwise}\end{cases}\end{align}
Where: <ul><li>\(m\) is the number of <i>matching characters</i>;</li><li> \(t\) is half the number of <i>transpositions</i>.</li></uL>
Two characters from \(s_1\) and \(s_2\) respectively, are considered <i>matching</i> only if they are the same and not farther than \(\left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1\).
Each character of \(s_1\) is compared with all its matching characters in \(s_2\) . The number of matching (but different sequence order) characters divided by 2 defines the number of <i>transpositions</i>.
<b>Example</b>
Given the strings \(s_1\) <i>DWAYNE</i> and \(s_2\) <i>DUANE</i> we find:
<ul><li>\(m = 4\)</li><li>\(|s_1| = 6\) </li><li>\(|s_2| = 5\) </li><li>\(t = 0\) </li></ul>
We find a Jaro score of: \(d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822\).
Write a function a that takes two strings as parameters and returns the associated Jaro distance.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>jaro</code> should be a function.'''
testString: 'assert(typeof jaro==''function'',''<code>jaro</code> should be a function.'');'
- text: '''<code>jaro("''+tests[0][0]+''","''+tests[0][1]+''")</code> should return a number.'''
testString: 'assert(typeof jaro(tests[0][0],tests[0][1])==''number'',''<code>jaro()</code> should return a number.'');'
- text: '''<code>jaro("''+tests[0][0]+''","''+tests[0][1]+''")</code> should return <code>''+results[0]+''</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("''+tests[1][0]+''","''+tests[1][1]+''")</code> should return <code>''+results[1]+''</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("''+tests[2][0]+''","''+tests[2][1]+''")</code> should return <code>''+results[2]+''</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("''+tests[3][0]+''","''+tests[3][1]+''")</code> should return <code>''+results[3]+''</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("''+tests[4][0]+''","''+tests[4][1]+''")</code> should return <code>''+results[4]+''</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>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function jaro (s, t) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,89 @@
---
title: JortSort
id: 5a23c84252665b21eecc7ec4
challengeType: 5
---
## Description
<section id='description'>
jortSort is a sorting toolset that makes the user do the work and guarantees efficiency because you don't have to sort ever again. It was originally presented by Jenn "Moneydollars" Schiffer at the prestigious <a href="https://www.youtube.com/watch?v=pj4U_W0OFoE">JSConf</a>.
jortSort is a function that takes a single array of comparable objects as its argument. It then sorts the array in ascending order and compares the sorted array to the originally provided array. If the arrays match (i.e. the original array was already sorted), the function returns true. If the arrays do not match (i.e. the original array was not sorted), the function returns false.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>jortsort</code> should be a function.'''
testString: 'assert(typeof jortsort==''function'',''<code>jortsort</code> should be a function.'');'
- text: '''<code>jortsort(''+JSON.stringify(tests[0])+'')</code> should return a boolean.'''
testString: 'assert(typeof jortsort(tests[0].slice())==''boolean'',''<code>jortsort(''+JSON.stringify(tests[0])+'')</code> should return a boolean.'');'
- text: '''<code>jortsort(''+JSON.stringify(tests[0])+'')</code> should return <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(''+JSON.stringify(tests[1])+'')</code> should return <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(''+JSON.stringify(tests[2])+'')</code> should return <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(''+JSON.stringify(tests[3])+'')</code> should return <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(''+JSON.stringify(tests[4])+'')</code> should return <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(''+JSON.stringify(tests[5])+'')</code> should return <code>true</code>.'''
testString: 'assert.equal(jortsort(tests[5].slice()),true,''<code>jortsort(''+JSON.stringify(tests[5])+'')</code> should return <code>true</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function jortsort (array) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,108 @@
---
title: Josephus problem
id: 5a23c84252665b21eecc7ec5
challengeType: 5
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Josephus problem">Josephus problem</a> is a math puzzle with a grim description: $n$ prisoners are standing on a circle, sequentially numbered from $0$ to $n-1$.
An executioner walks along the circle, starting from prisoner $0$, removing every $k$-th prisoner and killing him.
As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed.
For example, if there are $n=5$ prisoners and $k=2$, the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2.
Given any <big>$n, k > 0$</big>, find out which prisoner will be the final survivor.
In one such incident, there were 41 prisoners and every 3<sup>rd</sup> prisoner was being killed (<big>$k=3$</big>).
Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale.
Which number was he?
Write a function that takes the initial number of prisoners and 'k' as parameter and returns the number of the prisoner that survives.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '''<code>josephus</code> should be a function.'''
testString: 'assert(typeof josephus==''function'',''<code>josephus</code> should be a function.'');'
- text: '''<code>josephus(30,3)</code> should return a number.'''
testString: 'assert(typeof josephus(30,3)==''number'',''<code>josephus(30,3)</code> should return a number.'');'
- text: '''<code>josephus(30,3)</code> should return <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> should return <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> should return <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> should return <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> should return <code>2</code>.'''
testString: 'assert.equal(josephus(29,4),2,''<code>josephus(29,4)</code> should return <code>2</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function josephus (init, kill) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,363 @@
{
"name": "Rosetta Code",
"dashedName": "rosetta-code",
"order": 5,
"time": "",
"template": "",
"required": [],
"superBlock": "coding-interview-prep",
"superOrder": 8,
"challengeOrder": [
[
"594810f028c0303b75339acb",
"100 doors"
],
[
"5951e88f64ebf159166a1176",
"24 game"
],
[
"5949b579404977fbaefcd736",
"9 billion names of God the integer"
],
[
"594810f028c0303b75339acc",
"ABC Problem"
],
[
"594810f028c0303b75339acd",
"Abundant, deficient and perfect number classifications"
],
[
"594810f028c0303b75339ace",
"Accumulator factory"
],
[
"594810f028c0303b75339acf",
"Ackermann function"
],
[
"594810f028c0303b75339ad0",
"Align columns"
],
[
"5949b579404977fbaefcd737",
"Amicable pairs"
],
[
"594d8d0ab97724821379b1e6",
"Averages-Mode"
],
[
"594d966a1467eb84194f0086",
"Averages-Pythagorean means"
],
[
"594da033de4190850b893874",
"Averages-Root mean square"
],
[
"594db4d0dedb4c06a2a4cefd",
"Babbage problem"
],
[
"594dc6c729e5700999302b45",
"Balanced brackets"
],
[
"5951815dd895584b06884620",
"Circles of given radius through two points"
],
[
"5951a53863c8a34f02bf1bdc",
"Closest-pair problem"
],
[
"5958469238c0d8d2632f46db",
"Combinations"
],
[
"596e414344c3b2872167f0fe",
"Comma quibbling"
],
[
"596e457071c35c882915b3e4",
"Compare a list of strings"
],
[
"596fd036dc1ab896c5db98b1",
"Convert seconds to compound duration"
],
[
"596fda99c69f779975a1b67d",
"Count occurrences of a substring"
],
[
"59713bd26bdeb8a594fb9413",
"Count the coins"
],
[
"59713da0a428c1a62d7db430",
"Cramer's rule"
],
[
"59669d08d75b60482359409f",
"Date format"
],
[
"5966c21cf732a95f1b67dd28",
"Date manipulation"
],
[
"5966f99c45e8976909a85575",
"Day of the week"
],
[
"59694356a6e7011f7f1c5f4e",
"Deal cards for FreeCell"
],
[
"596a8888ab7c01048de257d5",
"Deepcopy"
],
[
"597089c87eec450c68aa1643",
"Define a primitive data type"
],
[
"59f40b17e79dbf1ab720ed7a",
"Department Numbers"
],
[
"59f4eafba0343628bb682785",
"Discordian date"
],
[
"599c333915e0ea32d04d4bec",
"Element-wise operations"
],
[
"599d0ba974141b0f508b37d5",
"Emirp primes"
],
[
"599d15309e88c813a40baf58",
"Entropy"
],
[
"5987fd532b954e0f21b5d3f6",
"Equilibrium index"
],
[
"599d1566a02b571412643b84",
"Ethiopian multiplication"
],
[
"59880443fb36441083c6c20e",
"Euler method"
],
[
"598de241872ef8353c58a7a2",
"Evaluate binomial coefficients"
],
[
"59e09e6d412c5939baa02d16",
"Execute a Markov algorithm"
],
[
"59e0a8df964e4540d5abe599",
"Execute Brain****"
],
[
"598ee8b91b410510ae82efef",
"Extensible prime generator"
],
[
"597b2b2a2702b44414742771",
"Factorial"
],
[
"598eea87e5cf4b116c3ff81a",
"Factors of a Mersenne number"
],
[
"597f1e7fbc206f0e9ba95dc4",
"Factors of an integer"
],
[
"59c3ec9f15068017c96eb8a3",
"Farey sequence"
],
[
"598eef80ba501f1268170e1e",
"Fibonacci n-step number sequences"
],
[
"597f24c1dda4e70f53c79c81",
"Fibonacci sequence"
],
[
"5992e222d397f00d21122931",
"Fibonacci word"
],
[
"5a7dad05be01840e1778a0d1",
"Fractran"
],
[
"5a23c84252665b21eecc7e76",
"Gamma function"
],
[
"5a23c84252665b21eecc7e77",
"Gaussian elimination"
],
[
"5a23c84252665b21eecc7e78",
"General FizzBuzz"
],
[
"5a23c84252665b21eecc7e7a",
"Generate lower case ASCII alphabet"
],
[
"5a23c84252665b21eecc7e7b",
"GeneratorExponential"
],
[
"5a23c84252665b21eecc7e80",
"Gray code"
],
[
"5a23c84252665b21eecc7e82",
"Greatest common divisor"
],
[
"5a23c84252665b21eecc7e84",
"Greatest subsequential sum"
],
[
"595608ff8bcd7a50bd490181",
"Hailstone sequence"
],
[
"594810f028c0303b75339ad1",
"Happy numbers"
],
[
"595668ca4cfe1af2fb9818d4",
"Harshad or Niven series"
],
[
"595671d4d2cdc305f0d5b36f",
"Hash from two arrays"
],
[
"5956795bc9e2c415eb244de1",
"Hash join"
],
[
"595b98f8b5a2245e243aa831",
"Heronian triangles"
],
[
"59622f89e4e137560018a40e",
"Hofstadter Figure-Figure sequences"
],
[
"59637c4d89f6786115efd814",
"Hofstadter Q sequence"
],
[
"5a23c84252665b21eecc7eb0",
"I before E except after C"
],
[
"5a23c84252665b21eecc7eaf",
"IBAN"
],
[
"5a23c84252665b21eecc7eb1",
"Identity matrix"
],
[
"5a23c84252665b21eecc7ec1",
"Iterated digits squaring"
],
[
"5a23c84252665b21eecc7ec2",
"Jaro distance"
],
[
"5a23c84252665b21eecc7ec4",
"JortSort"
],
[
"5a23c84252665b21eecc7ec5",
"Josephus problem"
],
[
"59da22823d04c95919d46269",
"Sailors, coconuts and a monkey problem"
],
[
"59d9c6bc214c613ba73ff012",
"SEDOLs"
],
[
"59667989bf71cf555dd5d2ff",
"S-Expressions"
],
[
"594ecc0d9a8cf816e3340187",
"Taxicab numbers"
],
[
"594faaab4e2a8626833e9c3d",
"Tokenize a string with escaping"
],
[
"594fa2746886f41f7d8bf225",
"Topological sort"
],
[
"595011cba5a81735713873bd",
"Top rank per group"
],
[
"5951ed8945deab770972ae56",
"Towers of Hanoi"
],
[
"594810f028c0303b75339ad2",
"Vector cross product"
],
[
"594810f028c0303b75339ad3",
"Vector dot product"
],
[
"594810f028c0303b75339ad4",
"Word wrap"
],
[
"594810f028c0303b75339ad5",
"Y combinator"
],
[
"594810f028c0303b75339ad6",
"Zeckendorf number representation"
],
[
"594810f028c0303b75339ad7",
"Zhang-Suen thinning algorithm"
],
[
"594810f028c0303b75339ad8",
"Zig-zag matrix"
]
],
"helpRoom": "",
"nChallenges": 437,
"fileName": "08-coding-interview-prep/rosetta-code.json"
}

View File

@ -0,0 +1,120 @@
---
title: S-Expressions
id: 59667989bf71cf555dd5d2ff
challengeType: 5
---
## Description
<section id='description'>
<p>
<a href="https://en.wikipedia.org/wiki/S-Expression" title="wp: S-Expression">S-Expressions</a> are one convenient way to parse and store data.
</p>
Task:
<p>
Write a simple reader/parser for S-Expressions that handles quoted and unquoted strings, integers and floats.
</p>
<p>
The function should read a single but nested S-Expression from a string and
return it as a (nested) array.
</p>
<p>
Newlines and other whitespace may be ignored unless contained within a quoted string.
</p>
<p><tt>()</tt>” inside quoted strings are not interpreted, but treated as part of the string.
</p>
<p>
Handling escaped quotes inside a string is optional; thus “<tt>(foo"bar)</tt>” maybe treated as a string “<tt>foo"bar</tt>”, or as an error.
</p>
<p>
For this, the reader need not recognize “<tt>\</tt>” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes.
</p>
<p>
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.
</p>
<p>The reader should be able to read the following input</p>
<p>
<pre>
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
</pre>
</p>
<p>
and turn it into a native datastructure. (see the
<a href="http://rosettacode.org/wiki/#Pike" title="#Pike">Pike</a>,
<a href="http://rosettacode.org/wiki/#Python" title="#Python">Python</a> and
<a href="http://rosettacode.org/wiki/#Ruby" title="#Ruby">Ruby</a> implementations
for examples of native data structures.)
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>parseSexpr</code> is a function.
testString: 'assert(typeof parseSexpr === ''function'', ''<code>parseSexpr</code> is a function.'');'
- text: '<code>parseSexpr(''(data1 data2 data3)'')</code> should return [''data1'', ''data2'', ''data3'']")'
testString: 'assert.deepEqual(parseSexpr(simpleSExpr), simpleSolution, "<code>parseSexpr(''(data1 data2 data3)'')</code> should return [''data1'', ''data2'', ''data3'']");'
- text: <code>parseSexpr('(data1 data2 data3)')</code> should return an array with 3 elements")
testString: 'assert.deepEqual(parseSexpr(basicSExpr), basicSolution, "<code>parseSexpr(''(data1 data2 data3)'')</code> should return an array with 3 elements");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function parseSexpr(str) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,148 @@
---
title: 'Sailors, coconuts and a monkey problem'
id: 59da22823d04c95919d46269
challengeType: 5
---
## Description
<section id='description'>
<p>
Five sailors are shipwrecked on an island and
collect a large pile of coconuts during the day.
</p>
<p>That night the first sailor wakes up and decides
to take his first share early so tries to divide the pile of coconuts equally
into five piles but finds that there is one coconut left over, so he tosses it
to a monkey and then hides "his" one of the five equally sized piles of
coconuts and pushes the other four piles together to form a single visible pile
of coconuts again and goes to bed.
</p>
<p>
To cut a long story short, each of the sailors in
turn gets up once during the night and performs the same actions of dividing
the coconut pile into five, finding that one coconut is left over and giving
that single remainder coconut to the monkey.
</p>
<p>
In the morning (after the surreptitious and
separate action of each of the five sailors during the night), the remaining
coconuts are divided into five equal piles for each of the sailors, whereupon
it is found that the pile of coconuts divides equally amongst the sailors with
no remainder. (Nothing for the monkey in the morning.)
</p>
The task:
Create a function that returns the
the minimum possible size
of the initial pile of coconuts collected during the day for N
sailors.
Note:
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.
C.f:
<a
href="https://www.youtube.com/watch?v=U9qU20VmvaU" title="link: https://www.youtube.com/watch?v=U9qU20VmvaU">
Monkeys and Coconuts - Numberphile</a> (Video) Analytical solution.
<a
href="http://oeis.org/A002021" title="link: http://oeis.org/A002021">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).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>splitCoconuts</code> is a function.
testString: 'assert(typeof splitCoconuts === ''function'', ''<code>splitCoconuts</code> is a function.'');'
- text: <code>splitCoconuts(5)</code> should return 3121.
testString: 'assert(splitCoconuts(5) === 3121, ''<code>splitCoconuts(5)</code> should return 3121.'');'
- text: <code>splitCoconuts(6)</code> should return 233275.
testString: 'assert(splitCoconuts(6) === 233275, ''<code>splitCoconuts(6)</code> should return 233275.'');'
- text: <code>splitCoconuts(7)</code> should return 823537.
testString: 'assert(splitCoconuts(7) === 823537, ''<code>splitCoconuts(7)</code> should return 823537.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// noprotect
function splitCoconuts(intSailors) {
// Good luck!
return true;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,115 @@
---
title: SEDOLs
id: 59d9c6bc214c613ba73ff012
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>
For each number list of 6-digit
<a href="https://en.wikipedia.org/wiki/SEDOL" title="wp: SEDOL">SEDOL</a>s,
calculate and append the checksum digit.
</p>
<p>
That is, given the input string on the left, your function should return the
corresponding string on the right:
</p>
<pre>
710889 => 7108899
B0YBKJ => B0YBKJ7
406566 => 4065663
B0YBLH => B0YBLH2
228276 => 2282765
B0YBKL => B0YBKL9
557910 => 5579107
B0YBKR => B0YBKR5
585284 => 5852842
B0YBKT => B0YBKT7
B00030 => B000300
</pre>
<p>
Check also that each input is correctly formed, especially
with respect to valid characters allowed in a SEDOL string. Your function
should return <code>null</code> on invalid input.
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>sedol</code> is a function.
testString: 'assert(typeof sedol === ''function'', ''<code>sedol</code> is a function.'');'
- text: <code>sedol('a')</code> should return null.")
testString: 'assert(sedol(''a'') === null, "<code>sedol(''a'')</code> should return null.");'
- text: <code>sedol('710889')</code> should return '7108899'.")
testString: 'assert(sedol(''710889'') === ''7108899'', "<code>sedol(''710889'')</code> should return ''7108899''.");'
- text: <code>sedol('BOATER')</code> should return null.")
testString: 'assert(sedol(''BOATER'') === null, "<code>sedol(''BOATER'')</code> should return null.");'
- text: <code>sedol('228276')</code> should return '2282765'.")
testString: 'assert(sedol(''228276'') === ''2282765'', "<code>sedol(''228276'')</code> should return ''2282765''.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function sedol (input) {
// Good luck!
return true;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,126 @@
---
title: Taxicab numbers
id: 594ecc0d9a8cf816e3340187
challengeType: 5
---
## Description
<section id='description'>
A &nbsp; <a href="https://en.wikipedia.org/wiki/HardyRamanujan number" title="wp: HardyRamanujan number">taxicab number</a>
&nbsp; (the definition that is being used here) &nbsp; is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is &nbsp; 1729, &nbsp; which is:
1<sup>3</sup> &nbsp; + &nbsp; 12<sup>3</sup> &nbsp; &nbsp; &nbsp; and
9<sup>3</sup> &nbsp; + &nbsp; 10<sup>3</sup>.
Taxicab numbers are also known as:
* &nbsp; taxi numbers
* &nbsp; taxi-cab numbers
* &nbsp; taxi cab numbers
* &nbsp; Hardy-Ramanujan numbers
Task:
Write a function that returns the lowest N taxicab numbers.
For each of the taxicab numbers, show the number as well as it's constituent cubes.
See also:
[http://oeis.org/A001235 A001235 taxicab numbers] on The On-Line Encyclopedia of Integer Sequences.
<a href="http://mathworld.wolfram.com/Hardy-RamanujanNumber.html">Hardy-Ramanujan Number</a> on MathWorld.
<a href="http://mathworld.wolfram.com/TaxicabNumber.html">taxicab number</a> on MathWorld.
<a href="https://en.wikipedia.org/wiki/Taxicab_number">taxicab number</a> on Wikipedia.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>taxicabNumbers </code> is a function.
testString: 'assert(typeof taxicabNumbers === ''function'', ''<code>taxicabNumbers </code> is a function.'');'
- text: <code>taxicabNumbers </code> should return an array.
testString: 'assert(typeof taxicabNumbers(2) === ''object'', ''<code>taxicabNumbers </code> should return an array.'');'
- text: <code>taxicabNumbers </code> should return an array of numbers.
testString: 'assert(typeof taxicabNumbers(100)[0] === ''number'', ''<code>taxicabNumbers </code> should return an array of numbers.'');'
- text: '<code>taxicabNumbers(4) </code> must return [1729, 4104, 13832, 20683].'
testString: 'assert.deepEqual(taxicabNumbers(4), res4, ''<code>taxicabNumbers(4) </code> must return [1729, 4104, 13832, 20683].'');'
- text: '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]'
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) 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, ''taxicabNumbers(39) resulting numbers from 20 - 29 should be [314496,320264,327763,373464,402597,439101,443889,513000,513856].'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function taxicabNumbers (n) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,117 @@
---
title: Tokenize a string with escaping
id: 594faaab4e2a8626833e9c3d
challengeType: 5
---
## Description
<section id='description'>
<p>
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
</p>
<p>
It should accept three input parameters:
</p>
The <b>string</b>
The <b>separator character</b>
The <b>escape character</b>
<p>It should output a list of strings.</p>
<p>Rules for splitting:</p>
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
<p>Rules for escaping:</p>
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrences of the escape character that was used to escape something, should not become part of the output.
<p>Demonstrate that your function satisfies the following test-case:
Given string <pre>one^|uno||three^^^^|four^^^|^cuatro|</pre> and using
<pre>|</pre> as a separator and <pre>^</pre> as escape character, your
function should output the following array:
</p>
<pre>
['one|uno', '', 'three^^', 'four^|quatro', '']
</pre>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>tokenize</code> is a function.
testString: 'assert(typeof tokenize === ''function'', ''<code>tokenize</code> is a function.'');'
- text: <code>tokenize</code> should return an array.
testString: 'assert(typeof tokenize(''a'', ''b'', ''c'') === ''object'', ''<code>tokenize</code> should return an array.'');'
- text: '<code>tokenize(''one^|uno||three^^^^|four^^^|^cuatro|'', ''|'', ''^'') </code> should return [''one|uno'', '''', ''three^^'', ''four^|cuatro'', '''']")'
testString: 'assert.deepEqual(tokenize(testStr1, ''|'', ''^''), res1, "<code>tokenize(''one^|uno||three^^^^|four^^^|^cuatro|'', ''|'', ''^'') </code> should return [''one|uno'', '''', ''three^^'', ''four^|cuatro'', '''']");'
- text: '<code>tokenize(''a@&bcd&ef&&@@hi'', ''&'', ''@'')</code> should return <code>[''a&bcd'', ''ef'', '''', ''@hi'']</code>'
testString: 'assert.deepEqual(tokenize(testStr2, ''&'', ''@''), res2, ''<code>tokenize("a@&bcd&ef&&@@hi", "&", "@")</code> should return <code>["a&bcd", "ef", "", "@hi"]</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function tokenize(str, esc, sep) {
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,134 @@
---
title: Top rank per group
id: 595011cba5a81735713873bd
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Find the top N ranked data in each group, where N is provided as a parameter. Name of the rank and the group are also provided as parameter.</p>
Given the following data:
<pre>
[
{ 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' }
];
</pre>
one could rank top 10 employees in each department by calling
<code>topRankPerGroup(10, data, 'dept', 'salary')</code>
Given the following data:
<pre>
[
{ 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 }
];
</pre>
one could rank the top-rated movie in each genre by calling
<code>topRankPerGroup(1, data, 'genre', 'rating')</code>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>topRankPerGroup</code> is a function.
testString: 'assert(typeof topRankPerGroup === ''function'', ''<code>topRankPerGroup</code> is a function.'');'
- text: <code>topRankPerGroup</code> returns undefined on negative n values.
testString: 'assert(typeof topRankPerGroup(-1, []) === ''undefined'', ''<code>topRankPerGroup</code> returns undefined on negative n values.'');'
- text: First department must be D050
testString: 'assert.equal(res1[0][0].dept, ''D050'', ''First department must be D050'');'
- text: First department must be D050
testString: 'assert.equal(res1[0][1].salary, 21900, ''First department must be D050'');'
- text: The last department must be D202
testString: 'assert.equal(res1[3][3].dept, ''D202'', ''The last department must be D202'');'
- text: '<code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.'
testString: 'assert.equal(res2[2].length, 1, ''<code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.'');'
- text: '<code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.'
testString: 'assert.equal(res3[2][1].name, ''Maze Runner'', ''<code>topRankPerGroup(1, ...)</code> must return only top ranking result per group.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function topRankPerGroup(n, data, groupName, rankName) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,168 @@
---
title: Topological sort
id: 594fa2746886f41f7d8bf225
challengeType: 5
---
## Description
<section id='description'>
<p>
Given a mapping between items, and items they depend on, a
<a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: Topological sorting">topological sort</a> orders
items so that no item precedes an item it depends upon.
</p>
<p>
The compiling of a library in the
<a href="https://en.wikipedia.org/wiki/VHDL" title="wp: VHDL">VHDL</a> language
has the constraint that a library must be compiled after any library it depends on.
</p>
Task:
<p>
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
</p>
Assume library names are single words.
Items mentioned as only dependents have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be ignored.
<p>Use the following data as an example:</p>
<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>
<p>
<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>
</p>
C.f.:
<a href="http://rosettacode.org/wiki/Topological sort/Extracted top item" title="Topological sort/Extracted top item">Topological sort/Extracted top item</a>.
<p>There are two popular algorithms for topological sorting:</p>
<p>
Kahn's 1962 topological sort, and depth-first search:
<a href="https://en.wikipedia.org/wiki/Topological sorting" title="wp: Topological sorting">topological sort</a>
</p>
<p>
Jason Sachs:
<a href="http://www.embeddedrelated.com/showarticle/799.php" title="link: http://www.embeddedrelated.com/showarticle/799.php">
"Ten little algorithms, part 4: topological sort"
</a>.
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>topologicalSort</code> is a function.
testString: 'assert(typeof topologicalSort === ''function'', ''<code>topologicalSort</code> is a function.'');'
- text: <code>topologicalSort</code> must return correct library order..
testString: 'assert.deepEqual(topologicalSort(libsSimple), [''bbb'', ''aaa''], ''<code>topologicalSort</code> must return correct library order..'');'
- text: <code>topologicalSort</code> must return correct library order..
testString: 'assert.deepEqual(topologicalSort(libsVHDL), solutionVHDL, ''<code>topologicalSort</code> must return correct library order..'');'
- text: <code>topologicalSort</code> must return correct library order..
testString: 'assert.deepEqual(topologicalSort(libsCustom), solutionCustom, ''<code>topologicalSort</code> must return correct library order..'');'
- text: <code>topologicalSort</code> must ignore unorderable dependencies..
testString: 'assert.deepEqual(topologicalSort(libsUnorderable), solutionUnorderable, ''<code>topologicalSort</code> must ignore unorderable dependencies..'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function topologicalSort(libs) {
// Good luck!
return true;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,94 @@
---
title: Towers of Hanoi
id: 5951ed8945deab770972ae56
challengeType: 5
---
## Description
<section id='description'>
Task:
<p>Solve the <a href="https://en.wikipedia.org/wiki/Towers_of_Hanoi" title="wp: Towers_of_Hanoi">Towers of Hanoi</a> problem.</p>
<p>
Your solution should accept the number of discs as the first parameters, and
three string used to identify each of the three stacks of discs, for example
<code>towerOfHanoi(4, 'A', 'B', 'C')</code>. The function should return an
array of arrays containing the list of moves, source -> destination. For
example, the array <code>[['A', 'C'], ['B', 'A']]</code> indicates that the
1st move was to move a disc from stack A to C, and the 2nd move was to move a
disc from stack B to A.
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>towerOfHanoi</code> is a function.
testString: 'assert(typeof towerOfHanoi === ''function'', ''<code>towerOfHanoi</code> is a function.'');'
- text: '<code>towerOfHanoi(3, ...)</code> should return 7 moves.'
testString: 'assert(res3.length === 7, ''<code>towerOfHanoi(3, ...)</code> should return 7 moves.'');'
- text: '<code>towerOfHanoi(3, ''A'', ''B'', ''C'')</code> should return [[''A'',''B''],[''A'',''C''],[''B'',''C''],[''A'',''B''],[''C'',''A''],[''C'',''B''],[''A'',''B'']].")'
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, "X", "Y", "Z")</code> 10th move should be Y -> 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, ''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'']].")'
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'']].");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function towerOfHanoi (n, a, b, c) {
// Good luck!
return [[]];
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,90 @@
---
title: Vector cross product
id: 594810f028c0303b75339ad2
challengeType: 5
---
## Description
<section id='description'>
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: &nbsp; (X, Y, Z).
<p>
Task:
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 (ie vectors of different lengths).
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: dotProduct must be a function
testString: 'assert.equal(typeof crossProduct, ''function'', ''dotProduct must be a function'');'
- text: dotProduct() must return null
testString: 'assert.equal(crossProduct(), null, ''dotProduct() must return null'');'
- text: 'crossProduct([1, 2, 3], [4, 5, 6]) must return [-3, 6, -3].'
testString: 'assert.deepEqual(res12, exp12, ''crossProduct([1, 2, 3], [4, 5, 6]) must return [-3, 6, -3].'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function crossProduct() {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,107 @@
---
title: Vector dot product
id: 594810f028c0303b75339ad3
challengeType: 5
---
## Description
<section id='description'>
<p>
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: &nbsp; (X, Y, Z).
</p>
<p>
Task:
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 (ie vectors of different lengths).
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: dotProduct must be a function
testString: 'assert.equal(typeof dotProduct, ''function'', ''dotProduct must be a function'');'
- text: dotProduct() must return null
testString: 'assert.equal(dotProduct(), null, ''dotProduct() must return null'');'
- text: 'dotProduct([[1], [1]]) must return 1.'
testString: 'assert.equal(dotProduct([1], [1]), 1, ''dotProduct([[1], [1]]) must return 1.'');'
- text: 'dotProduct([[1], [1, 2]]) must return null.'
testString: 'assert.equal(dotProduct([1], [1, 2]), null, ''dotProduct([[1], [1, 2]]) must return null.'');'
- text: 'dotProduct([1, 3, -5], [4, -2, -1]) must return 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> 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, ''<code>dotProduct(...nVectors)</code> should return 156000'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function dotProduct() {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,109 @@
---
title: Word wrap
id: 594810f028c0303b75339ad4
challengeType: 5
---
## Description
<section id='description'>
<p>
Even today, with proportional fonts and complex layouts, there are still
cases where you need to wrap text at a specified
column. The basic task is to wrap a paragraph of text in a simple way.
Example text:
</p>
<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 minimimum length algorithm.
</pre>
<p>
Task:
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:
</p>
<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 minimimum length algorithm.
</pre>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: wrap must be a function.
testString: 'assert.equal(typeof wrap, ''function'', ''wrap must be a function.'');'
- text: wrap must return a string.
testString: 'assert.equal(typeof wrap(''abc'', 10), ''string'', ''wrap must return a string.'');'
- text: wrap(80) must return 4 lines.
testString: 'assert(wrapped80.split(''\n'').length === 4, ''wrap(80) must return 4 lines.'');'
- text: Your <code>wrap</code> function should return our expected text
testString: 'assert.equal(wrapped80.split(''\n'')[0], firstRow80, ''Your <code>wrap</code> function should return our expected text'');'
- text: wrap(42) must return 7 lines.
testString: 'assert(wrapped42.split(''\n'').length === 7, ''wrap(42) must return 7 lines.'');'
- text: Your <code>wrap</code> function should return our expected text
testString: 'assert.equal(wrapped42.split(''\n'')[0], firstRow42, ''Your <code>wrap</code> function should return our expected text'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function wrap (text, limit) {
return text;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,100 @@
---
title: Y combinator
id: 594810f028c0303b75339ad5
challengeType: 5
---
## Description
<section id='description'>
<p>
In strict
<a href="https://en.wikipedia.org/wiki/Functional programming" title="wp: functional programming">functional programming</a> and
the <a href="https://en.wikipedia.org/wiki/lambda calculus" title="wp: lambda calculus">lambda calculus</a>,
functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
</p>
<p>
The <a href="http://mvanier.livejournal.com/2897.html">Y combinator</a> is itself a stateless function that,
when applied to another stateless function, returns a recursive version of the function. The Y combinator is
the simplest of the class of such functions, called
<a href="https://en.wikipedia.org/wiki/Fixed-point combinator" title="wp: fixed-point combinator">fixed-point combinators</a>.
</p>
Task:
Define the stateless Y combinator function and use it to compute
<a href="https://en.wikipedia.org/wiki/Factorial" title="wp: factorial">factorial</a>.
<code>factorial(N)</code> function is already given to you.
See also <a href="http://vimeo.com/45140590">Jim Weirich: Adventures in Functional Programming</a>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Y must return a function
testString: 'assert.equal(typeof Y(f => n => n), ''function'', ''Y must return a function'');'
- text: factorial(1) must return 1.
testString: 'assert.equal(factorial(1), 1, ''factorial(1) must return 1.'');'
- text: factorial(2) must return 2.
testString: 'assert.equal(factorial(2), 2, ''factorial(2) must return 2.'');'
- text: factorial(3) must return 6.
testString: 'assert.equal(factorial(3), 6, ''factorial(3) must return 6.'');'
- text: factorial(4) must return 24.
testString: 'assert.equal(factorial(4), 24, ''factorial(4) must return 24.'');'
- text: factorial(10) must return 3628800.
testString: 'assert.equal(factorial(10), 3628800, ''factorial(10) must return 3628800.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Y(f) {
return function() {
// Good luck!
};
}
var factorial = Y(function(f) {
return function (n) {
return n > 1 ? n * f(n - 1) : 1;
};
});
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var Y = f => (x => x(x))(y => f(x => y(y)(x)));
```
</section>

View File

@ -0,0 +1,126 @@
---
title: Zeckendorf number representation
id: 594810f028c0303b75339ad6
challengeType: 5
---
## Description
<section id='description'>
<p>
Just as numbers can be represented in a
positional notation as sums of multiples of the powers of ten (decimal)
or two (binary); all the positive integers can be represented as the sum
of one or zero times the distinct members of the Fibonacci series.
</p>
<p>
Recall that the first six distinct Fibonacci
numbers are: <code>1, 2, 3, 5, 8, 13</code>. The decimal number eleven can
be written as <code>0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1</code> or
<code>010100</code> in positional notation where the columns represent
multiplication by a particular member of the sequence. Leading zeroes are
dropped so that 11 decimal becomes <code>10100</code>.
</p>
<p>
10100 is not the only way to make 11 from the Fibonacci numbers however
<code>0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1</code> or 010011 would also
represent decimal 11. For a true Zeckendorf number there is the added
restriction that ''no two consecutive Fibonacci numbers can be used''
which leads to the former unique solution.
</p>
<p>
Task:
Write a function that generates and returns an array of first N Zeckendorf numbers in order.
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: zeckendorf must be function
testString: 'assert.equal(typeof zeckendorf, ''function'', ''zeckendorf must be function'');'
- text: Your <code>zeckendorf</code> function should return the correct answer
testString: 'assert.deepEqual(answer, solution20, ''Your <code>zeckendorf</code> function should return the correct answer'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function zeckendorf(n) {
// good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// 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

@ -0,0 +1,271 @@
---
title: Zhang-Suen thinning algorithm
id: 594810f028c0303b75339ad7
challengeType: 5
---
## Description
<section id='description'>
This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
<pre>
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
</pre>
It produces the thinned output:
<pre>
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
</pre>
<h2>Algorithm</h2>
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:
<table border="1">
<tr><td>P9</td><td>P2</td><td>P3</td></tr>
<tr><td>P8</td><td><b>P1</b></td><td>P4</td></tr>
<tr><td>P7</td><td>P6</td><td>P5</td></tr>
</table>
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define $A(P1)$ = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define $B(P1)$ = the number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
<h3>Step 1:</h3>
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1) $2 <= B(P1) <= 6$
(2) $A(P1) = 1$
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
<h3>Step 2:</h3>
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1) $2 <= B(P1) <= 6$
(2) $A(P1) = 1$
(3) At least one of P2 and P4 and '''P8''' is white
(4) At least one of '''P2''' and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration:
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
<p>
Task:
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
</p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>thinImage</code> must be a function
testString: 'assert.equal(typeof thinImage, ''function'', ''<code>thinImage</code> must be a function'');'
- text: <code>thinImage</code> must return an array
testString: 'assert(Array.isArray(result), ''<code>thinImage</code> must return an array'');'
- text: <code>thinImage</code> must return an array of strings
testString: 'assert.equal(typeof result[0], ''string'', ''<code>thinImage</code> must return an array of strings'');'
- text: <code>thinImage</code> must return an array of strings
testString: 'assert.deepEqual(result, expected, ''<code>thinImage</code> must return an array of strings'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
const testImage = [
' ',
' ################# ############# ',
' ################## ################ ',
' ################### ################## ',
' ######## ####### ################### ',
' ###### ####### ####### ###### ',
' ###### ####### ####### ',
' ################# ####### ',
' ################ ####### ',
' ################# ####### ',
' ###### ####### ####### ',
' ###### ####### ####### ',
' ###### ####### ####### ###### ',
' ######## ####### ################### ',
' ######## ####### ###### ################## ###### ',
' ######## ####### ###### ################ ###### ',
' ######## ####### ###### ############# ###### ',
' '];
function thinImage(image) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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

@ -0,0 +1,110 @@
---
title: Zig-zag matrix
id: 594810f028c0303b75339ad8
challengeType: 5
---
## Description
<section id='description'>
A &nbsp; ''zig-zag'' &nbsp; array is a square arrangement of the first &nbsp;
$N^2$ &nbsp; integers, &nbsp; where the
numbers increase sequentially as you zig-zag along the array's &nbsp;
<a href="https://en.wiktionary.org/wiki/antidiagonal">anti-diagonals</a>.
For example, given &nbsp; '''5''', &nbsp; produce this array:
<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>
Write a function that takes the size of the zig-zag matrix, and returns the
corresponding matrix as two-dimensional array.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ZigZagMatrix must be a function
testString: 'assert.equal(typeof ZigZagMatrix, ''function'', ''ZigZagMatrix must be a function'');'
- text: ZigZagMatrix should return array
testString: 'assert.equal(typeof ZigZagMatrix(1), ''object'', ''ZigZagMatrix should return array'');'
- text: ZigZagMatrix should return an array of nestes arrays
testString: 'assert.equal(typeof ZigZagMatrix(1)[0], ''object'', ''ZigZagMatrix should return an array of nestes arrays'');'
- text: 'ZigZagMatrix(1) should return [[0]]'
testString: 'assert.deepEqual(ZigZagMatrix(1), zm1, ''ZigZagMatrix(1) should return [[0]]'');'
- text: 'ZigZagMatrix(2) should return [[0, 1], [2, 3]]'
testString: 'assert.deepEqual(ZigZagMatrix(2), zm2, ''ZigZagMatrix(2) should return [[0, 1], [2, 3]]'');'
- text: ZigZagMatrix(5) must return specified matrix
testString: 'assert.deepEqual(ZigZagMatrix(5), zm5, ''ZigZagMatrix(5) must return specified matrix'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function ZigZagMatrix(n) {
// Good luck!
return [[], []];
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
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>