feat(learn): python certification projects (#38216)

Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
Co-authored-by: Kristofer Koishigawa <scissorsneedfoodtoo@gmail.com>
Co-authored-by: Beau Carnes <beaucarnes@gmail.com>
This commit is contained in:
mrugesh
2020-02-25 00:10:32 +05:30
committed by Mrugesh Mohapatra
parent 3c3ceaa3f5
commit 22afc2a0ca
771 changed files with 1719 additions and 61 deletions

View File

@ -0,0 +1,79 @@
---
title: 100 doors
id: 594810f028c0303b75339acb
challengeType: 5
isHidden: false
forumTopicId: 302217
---
## Description
<section id='description'>
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.
</section>
## Instructions
<section id='instructions'>
Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getFinalOpenedDoors</code> should be a function.
testString: assert(typeof getFinalOpenedDoors === 'function');
- text: <code>getFinalOpenedDoors</code> should return an array.
testString: assert(Array.isArray(getFinalOpenedDoors(100)));
- text: <code>getFinalOpenedDoors</code> should produce the correct result.
testString: assert.deepEqual(getFinalOpenedDoors(100), solution);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getFinalOpenedDoors(numDoors) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const solution = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];
```
</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,175 @@
---
title: 24 game
id: 5951e88f64ebf159166a1176
challengeType: 5
isHidden: false
forumTopicId: 302218
---
## Description
<section id='description'>
The <a href="https://en.wikipedia.org/wiki/24_Game" target="_blank">24 Game</a> tests a person's mental arithmetic.
The aim of the game is to arrange four numbers in a way that when evaluated, the result is 24
</section>
## Instructions
<section id='instructions'>
Implement a function that takes a string of four digits as its argument, with each digit from 1 to 9 (inclusive) with repetitions allowed, and returns an arithmetic expression that evaluates to the number 24. If no such solution exists, return "no solution exists".
<h4><strong>Rules:</strong></h4>
<ul>
<li> Only the following operators/functions are allowed: multiplication, division, addition, subtraction. </li>
<li> Division should use floating point or rational arithmetic, etc, to preserve remainders. </li>
<li> Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). </li>
<li> The order of the digits when given does not have to be preserved. </li>
</ul>
| Example input | Example output |
| --- | --- |
| <code>solve24("4878");</code> | <code>(7-8/8)*4</code> |
| <code>solve24("1234");</code> | <code>3&ast;1&ast;4&ast;2</code> |
| <code>solve24("6789");</code> | <code>(6*8)/(9-7)</code> |
| <code>solve24("1127");</code> | <code>(1+7)*(2+1)</code> |
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>solve24</code> should be a function.
testString: assert(typeof solve24 === 'function');
- text: <code>solve24("4878")</code> should return <code>(7-8/8)*4</code> or <code>4*(7-8/8)</code>
testString: assert(include(answers[0], solve24(testCases[0])));
- text: <code>solve24("1234")</code> should return any arrangement of <code>1*2*3*4</code>
testString: assert(include(answers[1], solve24(testCases[1])));
- text: <code>solve24("6789")</code> should return <code>(6*8)/(9-7)</code> or <code>(8*6)/(9-7)</code>
testString: assert(include(answers[2], solve24(testCases[2])));
- text: <code>solve24("1127")</code> should return a permutation of <code>(1+7)*(1+2)</code>
testString: assert(include(answers[3], solve24(testCases[3])));
```
</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
const testCases = [
'4878',
'1234',
'6789',
'1127'
];
const answers = [
['(7-8/8)*4', '4*(7-8/8)', '(4-8+7)*8', '(4+7-8)*8', '(7+4-8)*8', '(7-8+4)*8', '8*(4-8+7)', '8*(4+7-8)', '8*(7+4-8)', '8*(7-8+4)'],
['1*2*3*4', '1*2*4*3', '1*3*2*4', '1*3*4*2', '1*4*2*3', '1*4*3*2', '2*1*3*4', '2*1*4*3', '2*3*1*4', '2*3*4*1', '2*4*3*1', '2*4*1*3', '3*1*2*4', '3*1*4*2', '3*2*1*4', '3*2*4*1', '3*4*1*2', '3*4*2*1', '4*1*2*3', '4*1*3*2', '4*2*1*3', '4*2*3*1', '4*3*1*2', '4*3*2*1', '(1+2+3)*4', '(1+3+2)*4', '(2+1+3)*4', '(2+3+1)*4', '(3+1+2)*4', '(3+2+1)*4', '4*(1+2+3)', '4*(2+1+3)', '4*(2+3+1)', '4*(3+1+2)', '4*(3+2+1)'],
['(6*8)/(9-7)', '(8*6)/(9-7)', '6*8/(9-7)', '8*6/(9-7)'],
['(1+7)*(2+1)', '(1+7)*(1+2)', '(1+2)*(1+7)', '(1+2)*(7+1)', '(2+1)*(1+7)', '(7+1)*(2+1)']
];
function include(ansArr, res) {
const index = ansArr.indexOf(res);
return index >= 0;
}
```
</div>
</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,104 @@
---
title: 9 billion names of God the integer
id: 5949b579404977fbaefcd736
challengeType: 5
isHidden: false
forumTopicId: 302219
---
## Description
<section id='description'>
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' target='_blank'>short story by Arthur C. Clarke</a>.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a "name":
<ul>
<li>The integer 1 has 1 name "1".</li>
<li>The integer 2 has 2 names "1+1" and "2".</li>
<li>The integer 3 has 3 names "1+1+1", "2+1", and "3".</li>
<li>The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".</li>
<li>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".</li>
</ul>
This can be visualized in the following form:
<pre>
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
</pre>
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$.
Optionally note that the sum of the $n$-th row $P(n)$ is the integer partition function.
</section>
## Instructions
<section id='instructions'>
Implement a function that returns the sum of the $n$-th row.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>numberOfNames</code> should be function.
testString: assert(typeof numberOfNames === 'function');
- text: <code>numberOfNames(5)</code> should equal 7.
testString: assert.equal(numberOfNames(5), 7);
- text: <code>numberOfNames(12)</code> should equal 77.
testString: assert.equal(numberOfNames(12), 77);
- text: <code>numberOfNames(18)</code> should equal 385.
testString: assert.equal(numberOfNames(18), 385);
- text: <code>numberOfNames(23)</code> should equal 1255.
testString: assert.equal(numberOfNames(23), 1255);
- text: <code>numberOfNames(42)</code> should equal 53174.
testString: assert.equal(numberOfNames(42), 53174);
- text: <code>numberOfNames(123)</code> should equal 2552338241.
testString: assert.equal(numberOfNames(123), 2552338241);
```
</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,126 @@
---
title: ABC Problem
id: 594810f028c0303b75339acc
challengeType: 5
isHidden: false
forumTopicId: 302220
---
## Description
<section id='description'>
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:
<pre>
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
</pre>
</section>
## Instructions
<section id='instructions'>
Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
Some rules to keep in mind:
<ul>
<li>Once a letter on a block is used, that block cannot be used again.</li>
<li>The function should be case-insensitive.</li>
</ul>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>canMakeWord</code> should be a function.
testString: assert(typeof canMakeWord === 'function');
- text: <code>canMakeWord</code> should return a boolean.
testString: assert(typeof canMakeWord('hi') === 'boolean');
- text: <code>canMakeWord("bark")</code> should return true.
testString: assert(canMakeWord(words[0]));
- text: <code>canMakeWord("BooK")</code> should return false.
testString: assert(!canMakeWord(words[1]));
- text: <code>canMakeWord("TReAT")</code> should return true.
testString: assert(canMakeWord(words[2]));
- text: <code>canMakeWord("COMMON")</code> should return false.
testString: assert(!canMakeWord(words[3]));
- text: <code>canMakeWord("squAD")</code> should return true.
testString: assert(canMakeWord(words[4]));
- text: <code>canMakeWord("conFUSE")</code> should return true.
testString: assert(canMakeWord(words[5]));
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function canMakeWord(word) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const words = ['bark', 'BooK', 'TReAT', 'COMMON', 'squAD', 'conFUSE'];
```
</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,98 @@
---
title: 'Abundant, deficient and perfect number classifications'
id: 594810f028c0303b75339acd
challengeType: 5
isHidden: false
forumTopicId: 302221
---
## Description
<section id='description'>
These define three classifications of positive integers based on their <a href='https://rosettacode.org/wiki/Proper divisors' title='Proper divisors' target='_blank'>proper divisors</a>.
Let $P(n)$ be the sum of the proper divisors of <code>n</code> where proper divisors are all positive integers <code>n</code> other than <code>n</code> itself.
If <code>P(n) < n</code> then <code>n</code> is classed as <code>deficient</code>
If <code>P(n) === n</code> then <code>n</code> is classed as <code>perfect</code>
If <code>P(n) > n</code> then <code>n</code> is classed as <code>abundant</code>
<strong>Example</strong>:
<code>6</code> has proper divisors of <code>1</code>, <code>2</code>, and <code>3</code>.
<code>1 + 2 + 3 = 6</code>, so <code>6</code> is classed as a perfect number.
</section>
## Instructions
<section id='instructions'>
Implement a function that calculates how many of the integers from <code>1</code> to <code>20,000</code> (inclusive) are in each of the three classes. Output the result as an array in the following format <code>[deficient, perfect, abundant]</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getDPA</code> should be a function.
testString: assert(typeof getDPA === 'function');
- text: <code>getDPA</code> should return an array.
testString: assert(Array.isArray(getDPA(100)));
- text: <code>getDPA</code> return value should have a length of 3.
testString: assert(getDPA(100).length === 3);
- text: <code>getDPA(20000)</code> should equal [15043, 4, 4953]
testString: assert.deepEqual(getDPA(20000), solution);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getDPA(num) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const solution = [15043, 4, 4953];
```
</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,83 @@
---
title: Accumulator factory
id: 594810f028c0303b75339ace
challengeType: 5
isHidden: false
forumTopicId: 302222
---
## Description
<section id='description'>
A problem posed by <a href='https://en.wikipedia.org/wiki/Paul_Graham_(programmer)' target='_blank'>Paul Graham</a> is that of creating a function that takes a single (numeric) argument and which 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).
</section>
## Instructions
<section id='instructions'>
Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them.
<strong>Rules:</strong>
Do not use global variables.
<strong>Hint:</strong>
Closures save outer state.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>accumulator</code> should be a function.
testString: assert(typeof accumulator === 'function');
- text: <code>accumulator(0)</code> should return a function.
testString: assert(typeof accumulator(0) === 'function');
- text: <code>accumulator(0)(2)</code> should return a number.
testString: assert(typeof accumulator(0)(2) === 'number');
- text: Passing in the values 3, -4, 1.5, and 5 should return 5.5.
testString: assert(testFn(5) === 5.5);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function accumulator(sum) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const testFn = typeof accumulator(3) === 'function' && accumulator(3);
if (testFn) {
testFn(-4);
testFn(1.5);
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function accumulator(sum) {
return function(n) {
return sum += n;
};
}
```
</section>

View File

@ -0,0 +1,70 @@
---
title: Ackermann function
id: 594810f028c0303b75339acf
challengeType: 5
isHidden: false
forumTopicId: 302223
---
## Description
<section id='description'>
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.
The Ackermann function is usually defined as follows:
$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}$
Its arguments are never negative and it always terminates.
</section>
## Instructions
<section id='instructions'>
Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>ack</code> should be a function.
testString: assert(typeof ack === 'function');
- text: <code>ack(0, 0)</code> should return 1.
testString: assert(ack(0, 0) === 1);
- text: <code>ack(1, 1)</code> should return 3.
testString: assert(ack(1, 1) === 3);
- text: <code>ack(2, 5)</code> should return 13.
testString: assert(ack(2, 5) === 13);
- text: <code>ack(3, 3)</code> should return 61.
testString: assert(ack(3, 3) === 61);
```
</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,201 @@
---
title: Align columns
id: 594810f028c0303b75339ad0
challengeType: 5
isHidden: false
forumTopicId: 302224
---
## Description
<section id='description'>
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.
</section>
## Instructions
<section id='instructions'>
Use the following text to test your programs:
<pre>
Given$a$text$file$of$many$lines
where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character
write$a$program
that$aligns$each$column$of$fields
by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified
or$center$justified$within$its$column.
</pre>
<strong>Note that:</strong>
<ul>
<li>The example input texts lines may, or may not, have trailing dollar characters.</li>
<li>All columns should share the same alignment.</li>
<li>Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.</li>
<li>Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.</li>
<li>The minimum space between columns should be computed from the text and not hard-coded.</li>
<li>It is not a requirement to add separating characters between or around columns.</li>
</ul>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>formatText</code> should be a function.
testString: assert(typeof formatText === 'function');
- text: '<code>formatText</code> with the above input and "right" justification should produce the following: '
testString: 'assert.strictEqual(formatText(testInput, ''right''), rightAligned);'
- text: '<code>formatText</code> with the above input and "left" justification should produce the following: '
testString: 'assert.strictEqual(formatText(testInput, ''left''), leftAligned);'
- text: '<code>formatText</code> with the above input and "center" justification should produce the following: '
testString: 'assert.strictEqual(formatText(testInput, ''center''), centerAligned);'
```
</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
const testInput = [
'Given$a$text$file$of$many$lines',
'where$fields$within$a$line$',
'are$delineated$by$a$single$\"dollar\"$character',
'write$a$program',
'that$aligns$each$column$of$fields$',
'by$ensuring$that$words$in$each$',
'column$are$separated$by$at$least$one$space.',
'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
'justified,$right$justified',
'or$center$justified$within$its$column.'
];
const rightAligned = ' Given a text file of many lines\n' +
' where fields within a line \n' +
' are delineated by a single "dollar" character\n' +
' write a program\n' +
' that aligns each column of fields \n' +
' by ensuring that words in each \n' +
' column are separated by at least one space.\n' +
' Further, allow for each word in a column to be either left \n' +
'justified, right justified\n' +
' or center justified within its column.';
const leftAligned = 'Given a text file of many lines \n' +
'where fields within a line \n' +
'are delineated by a single "dollar" character\n' +
'write a program \n' +
'that aligns each column of fields \n' +
'by ensuring that words in each \n' +
'column are separated by at least one space.\n' +
'Further, allow for each word in a column to be either left \n' +
'justified, right justified\n' +
'or center justified within its column. ';
const centerAligned = ' Given a text file of many lines \n' +
' where fields within a line \n' +
' are delineated by a single \"dollar\" character\n' +
' write a program \n' +
' that aligns each column of fields \n' +
' by ensuring that words in each \n' +
' column are separated by at least one space.\n' +
' Further, allow for each word in a column to be either left \n' +
'justified, right justified\n' +
' or center justified within its column. ';
```
</div>
</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,131 @@
---
title: Amicable pairs
id: 5949b579404977fbaefcd737
challengeType: 5
isHidden: false
forumTopicId: 302225
---
## 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' target='_blank'>amicable pairs</a> if $N \neq M$ and the sum of the <a href="https://rosettacode.org/wiki/Proper divisors" title="Proper divisors" target="_blank">proper divisors</a> of $N$ ($\mathrm{sum}(\mathrm{propDivs}(N))$) $= M$ as well as $\mathrm{sum}(\mathrm{propDivs}(M)) = N$.
<strong>Example:</strong>
<strong>1184</strong> and <strong>1210</strong> are an amicable pair, with proper divisors:
<ul>
<li>1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and</li>
<li>1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.</li>
</ul>
</section>
## Instructions
<section id='instructions'>
Calculate and show here the Amicable pairs below 20,000 (there are eight).
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>amicablePairsUpTo</code> should be a function.
testString: assert(typeof amicablePairsUpTo === 'function');
- text: <code>amicablePairsUpTo(300)</code> should return <code>[[220,284]]</code>.
testString: assert.deepEqual(amicablePairsUpTo(300), answer300);
- text: <code>amicablePairsUpTo(3000)</code> should return <code>[[220,284],[1184,1210],[2620,2924]]</code>.
testString: assert.deepEqual(amicablePairsUpTo(3000), answer3000);
- text: <code>amicablePairsUpTo(20000)</code> should return <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code>.
testString: assert.deepEqual(amicablePairsUpTo(20000), answer20000);
```
</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
const answer300 = [[220, 284]];
const answer3000 = [
[220, 284],
[1184, 1210],
[2620, 2924]
];
const answer20000 = [
[220, 284],
[1184, 1210],
[2620, 2924],
[5020, 5564],
[6232, 6368],
[10744, 10856],
[12285, 14595],
[17296, 18416]
];
```
</div>
</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,93 @@
---
title: Averages/Mode
id: 594d8d0ab97724821379b1e6
challengeType: 5
isHidden: false
forumTopicId: 302226
---
## Description
<section id='description'>
Write a program to find the <a href='https://en.wikipedia.org/wiki/Mode (statistics)' title='wp: Mode (statistics)' target='_blank'>mode</a> value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
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.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>mode</code> should be a function.
testString: assert(typeof mode === 'function');
- text: <code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>
testString: assert.deepEqual(mode(arr1), [6]);
- text: <code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.
testString: assert.deepEqual(mode(arr2).sort(), [1, 4]);
```
</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
const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
const arr2 = [1, 2, 4, 4, 1];
```
</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,159 @@
---
title: Averages/Pythagorean means
id: 594d966a1467eb84194f0086
challengeType: 5
isHidden: false
forumTopicId: 302227
---
## Description
<section id='description'>
Compute all three of the <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Pythagorean means' title='wp: Pythagorean means' target="_blank">Pythagorean means</a> of the set of integers <big>1</big> through <big>10</big> (inclusive).
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.
<ul>
<li>The most common of the three means, the <a class='rosetta__link--rosetta' href='https://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean' target='_blank'>arithmetic mean</a>, is the sum of the list divided by its length:<br>
<big>$ A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n}$</big></li>
<li>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean' target='_blank'>geometric mean</a> is the $n$th root of the product of the list:<br>
<big>$ G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n} $</big></li>
<li>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean' target='_blank'>harmonic mean</a> is $n$ divided by the sum of the reciprocal of each item in the list:<br>
<big>$ H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} $</big></li>
</ul>
</section>
## Instructions
<section id='instructions'>
When writing your function, assume the input is an ordered array of all inclusive numbers.
For the answer, please output an object in the following format:
```js
{
values: {
Arithmetic: 5.5,
Geometric: 4.528728688116765,
Harmonic: 3.414171521474055
},
test: 'is A >= G >= H ? yes'
}
```
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>pythagoreanMeans</code> should be a function.
testString: assert(typeof pythagoreanMeans === 'function');
- text: <code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.
testString: assert.deepEqual(pythagoreanMeans(range1), answer1);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function pythagoreanMeans(rangeArr) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const range1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const answer1 = {
values: {
Arithmetic: 5.5,
Geometric: 4.528728688116765,
Harmonic: 3.414171521474055
},
test: 'is A >= G >= H ? yes'
};
```
</div>
</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,74 @@
---
title: Averages/Root mean square
id: 594da033de4190850b893874
challengeType: 5
isHidden: false
forumTopicId: 302228
---
## Description
<section id='description'>
Compute the <a href="https://en.wikipedia.org/wiki/Root mean square" title="wp: Root mean square" target='_blank'>Root mean square</a> of the numbers 1 through 10 inclusive.
The <i>root mean square</i> is also known by its initials RMS (or rms), and as the <strong>quadratic mean</strong>.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
<big>$$x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}. $$</big>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>rms</code> should be a function.
testString: assert(typeof rms === 'function');
- text: <code>rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])</code> should equal <code>6.2048368229954285</code>.
testString: assert.equal(rms(arr1), answer1);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function rms(arr) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const answer1 = 6.2048368229954285;
```
</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,91 @@
---
title: Babbage problem
id: 594db4d0dedb4c06a2a4cefd
challengeType: 5
isHidden: false
forumTopicId: 302229
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Charles_Babbage" title="wp: Charles_Babbage" target='_blank'>Charles Babbage</a>, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
<blockquote>
What is the smallest positive integer whose square ends in the digits 269,696?
<footer style="margin-left: 2em;">Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, <i>Electronic Computers</i>, second edition, 1970, p. 125.</footer>
</blockquote>
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
The task is to find out if Babbage had the right answer.
</section>
## Instructions
<section id='instructions'>
Implement a function to return the lowest integer that satisfies the Babbage problem. If Babbage was right, return Babbage's number.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>babbage</code> should be a function.
testString: assert(typeof babbage === 'function');
- text: <code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).
testString: assert.equal(babbage(babbageAns, endDigits), answer);
```
</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
const babbageAns = 99736;
const endDigits = 269696;
const answer = 25264;
```
</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,140 @@
---
title: Balanced brackets
id: 594dc6c729e5700999302b45
challengeType: 5
isHidden: false
forumTopicId: 302230
---
## Description
<section id='description'>
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.
<h4><strong>Examples:</strong></h4>
| Input | Output |
| --- | --- |
| <code>[]</code> | true |
| <code>][</code> | false |
| <code>[][]</code> | true |
| <code>][][</code> | false |
| <code>[]][[]</code> | false |
| <code>[[[[]]]]</code> | true |
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isBalanced</code> should be a function.
testString: assert(typeof isBalanced === 'function');
- text: <code>isBalanced("[]")</code> should return true.
testString: assert(isBalanced(testCases[0]));
- text: <code>isBalanced("]][[[][][][]][")</code> should return false.
testString: assert(!isBalanced(testCases[1]));
- text: <code>isBalanced("[][[[[][][[[]]]]]]")</code> should return true.
testString: assert(isBalanced(testCases[2]));
- text: <code>isBalanced("][")</code> should return false.
testString: assert(!isBalanced(testCases[3]));
- text: <code>isBalanced("[[[]]]][[]")</code> should return false.
testString: assert(!isBalanced(testCases[4]));
- text: <code>isBalanced("][[]")</code> should return false.
testString: assert(!isBalanced(testCases[5]));
- text: <code>isBalanced("][[][]][[[]]")</code> should return false.
testString: assert(!isBalanced(testCases[6]));
- text: <code>isBalanced("[[][]]][")</code> should return false.
testString: assert(!isBalanced(testCases[7]));
- text: <code>isBalanced("[[[]]][[]]]][][[")</code> should return false.
testString: assert(!isBalanced(testCases[8]));
- text: <code>isBalanced("[]][[]]][[[[][]]")</code> should return false.
testString: assert(!isBalanced(testCases[9]));
- text: <code>isBalanced("][]][[][")</code> should return false.
testString: assert(!isBalanced(testCases[10]));
- text: <code>isBalanced("[[]][[][]]")</code> should return true.
testString: assert(isBalanced(testCases[11]));
- text: <code>isBalanced("[[]]")</code> should return true.
testString: assert(isBalanced(testCases[12]));
- text: <code>isBalanced("]][]][[]][[[")</code> should return false.
testString: assert(!isBalanced(testCases[13]));
- text: <code>isBalanced("][]][][[")</code> should return false.
testString: assert(!isBalanced(testCases[14]));
- text: <code>isBalanced("][][")</code> should return false.
testString: assert(!isBalanced(testCases[15]));
- text: <code>isBalanced("[]]]")</code> should return false.
testString: assert(!isBalanced(testCases[16]));
- text: <code>isBalanced("")</code> should return true.
testString: assert(isBalanced(testCases[17]));
```
</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
const testCases = [
'[]',
']][[[][][][]][',
'[][[[[][][[[]]]]]]',
'][',
'[[[]]]][[]',
'][[]',
'][[][]][[[]]',
'[[][]]][',
'[[[]]][[]]]][][[',
'[]][[]]][[[[][]]',
'][]][[][',
'[[]][[][]]',
'[[]]',
']][]][[]][[[',
'][]][][[',
'][][',
'[]]]',
''
];
```
</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,145 @@
---
title: Circles of given radius through two points
id: 5951815dd895584b06884620
challengeType: 5
isHidden: false
forumTopicId: 302231
---
## Description
<section id='description'>
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
<strong>Exceptions:</strong>
<ul>
<li>A radius of zero should be treated as never describing circles (except in the case where the points are coincident).</li>
<li>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.</li>
<li>If the points form a diameter then return a single circle.</li>
<li>If the points are too far apart then no circles can be drawn.</li>
</ul>
</section>
## Instructions
<section id='instructions'>
Implement a function that takes two points and a radius and returns the two circles through those points. For each resulting circle, provide the coordinates for the center of each circle rounded to four decimal digits. Return each coordinate as an array, and coordinates as an array of arrays.
<strong>For edge cases, return the following:</strong>
<ul>
<li>If points are on the diameter, return one point. If the radius is also zero however, return <code>"Radius Zero"</code>.</li>
<li>If points are coincident, return <code>"Coincident point. Infinite solutions"</code>.</li>
<li>If points are farther apart than the diameter, return <code>"No intersection. Points further apart than circle diameter"</code>.</li>
</ul>
<strong>Sample inputs:</strong>
<pre>
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
</pre>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getCircles</code> should be a function.
testString: assert(typeof getCircles === 'function');
- text: <code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)</code> should return <code>[[1.8631, 1.9742], [-0.8632, -0.7521]]</code>.
testString: assert.deepEqual(getCircles(...testCases[0]), answers[0]);
- text: <code>getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)</code> should return <code>[0, 1]</code>
testString: assert.deepEqual(getCircles(...testCases[1]), answers[1]);
- text: <code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)</code> should return <code>Coincident point. Infinite solutions</code>
testString: assert.deepEqual(getCircles(...testCases[2]), answers[2]);
- text: <code>getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)</code> should return <code>No intersection. Points further apart than circle diameter</code>
testString: assert.deepEqual(getCircles(...testCases[3]), answers[3]);
- text: <code>getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)</code> should return <code>Radius Zero</code>
testString: assert.deepEqual(getCircles(...testCases[4]), answers[4]);
```
</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
const testCases = [
[[0.1234, 0.9876], [0.8765, 0.2345], 2.0],
[[0.0000, 2.0000], [0.0000, 0.0000], 1.0],
[[0.1234, 0.9876], [0.1234, 0.9876], 2.0],
[[0.1234, 0.9876], [0.8765, 0.2345], 0.5],
[[0.1234, 0.9876], [0.1234, 0.9876], 0.0]
];
const answers = [
[[1.8631, 1.9742], [-0.8632, -0.7521]],
[0, 1],
'Coincident point. Infinite solutions',
'No intersection. Points further apart than circle diameter',
'Radius Zero'
];
```
</div>
</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,360 @@
---
title: Closest-pair problem
id: 5951a53863c8a34f02bf1bdc
challengeType: 5
isHidden: false
forumTopicId: 302232
---
## Description
<section id='description'>
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" target="blank">Closest pair of points problem</a> in the <i>planar</i> case.
The straightforward solution is a O(n<sup>2</sup>) algorithm (which we can call <i>brute-force algorithm</i>); the pseudo-code (using indexes) could be simply:
<pre>
<strong>bruteForceClosestPair</strong> of P(1), P(2), ... P(N)
<strong>if</strong> N < 2 <strong>then</strong>
<strong>return</strong>
<strong>else</strong>
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
<strong>foreach</strong> i ∈ [1, N-1]
<strong>foreach</strong> j ∈ [i+1, N]
<strong>if</strong> |P(i) - P(j)| < minDistance <strong>then</strong>
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
<strong>endif</strong>
<strong>endfor</strong>
<strong>endfor</strong>
<strong>return</strong> minDistance, minPoints
<strong>endif</strong>
</pre>
A better algorithm is based on the recursive divide and 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" target="_blank">Wikipedia's Closest pair of points problem</a>, which is <code>O(nlog(n))</code> a pseudo-code could be:
<pre>
<strong>closestPair</strong> 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)
<strong>if</strong> N ≤ 3 <strong>then</strong>
<strong>return</strong> closest points of xP using brute-force algorithm
<strong>else</strong>
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)
<strong>if</strong> dL < dR <strong>then</strong>
(dmin, pairMin) ← (dL, pairL)
<strong>endif</strong>
yS ← { p ∈ yP : |xm - p<sub>x</sub>| &lt; dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
<strong>for</strong> i <strong>from</strong> 1 <strong>to</strong> nS - 1
k ← i + 1
<strong>while</strong> k ≤ nS <strong>and</strong> yS(k)<sub>y</sub> - yS(i)<sub>y</sub> < dmin
<strong>if</strong> |yS(k) - yS(i)| < closest <strong>then</strong>
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
<strong>endif</strong>
k ← k + 1
<strong>endwhile</strong>
<strong>endfor</strong>
<strong>return</strong> closest, closestPair
<strong>endif</strong>
</pre>
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> (the pair of two closest points).
<strong>References and further readings:</strong>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Closest pair of points problem" title="wp: Closest pair of points problem" target="_blank">Closest pair of points problem</a></li>
<li><a href="https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html" target="_blank">Closest Pair (McGill)</a></li>
<li><a href="https://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf" target="_blank">Closest Pair (UCSB)</a></li>
<li><a href="https://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf" target="_blank">Closest pair (WUStL)</a></li>
</ul>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getClosestPair</code> should be a function.
testString: assert(typeof getClosestPair === 'function');
- text: Distance should be the following.
testString: assert.equal(getClosestPair(points1).distance, answer1.distance);
- text: Points should be the following.
testString: assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points1))).pair, answer1.pair);
- text: Distance should be the following.
testString: assert.equal(getClosestPair(points2).distance, answer2.distance);
- text: Points should be the following.
testString: assert.deepEqual(JSON.parse(JSON.stringify(getClosestPair(points2))).pair, answer2.pair);
```
</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
const points1 = [
new Point(0.748501, 4.09624),
new Point(3.00302, 5.26164),
new Point(3.61878, 9.52232),
new Point(7.46911, 4.71611),
new Point(5.7819, 2.69367),
new Point(2.34709, 8.74782),
new Point(2.87169, 5.97774),
new Point(6.33101, 0.463131),
new Point(7.46489, 4.6268),
new Point(1.45428, 0.087596)
];
const points2 = [
new Point(37100, 13118),
new Point(37134, 1963),
new Point(37181, 2008),
new Point(37276, 21611),
new Point(37307, 9320)
];
const answer1 = {
distance: 0.0894096443343775,
pair: [
{
x: 7.46489,
y: 4.6268
},
{
x: 7.46911,
y: 4.71611
}
]
};
const answer2 = {
distance: 65.06919393998976,
pair: [
{
x: 37134,
y: 1963
},
{
x: 37181,
y: 2008
}
]
};
const benchmarkPoints = [
new Point(16909, 54699),
new Point(14773, 61107),
new Point(95547, 45344),
new Point(95951, 17573),
new Point(5824, 41072),
new Point(8769, 52562),
new Point(21182, 41881),
new Point(53226, 45749),
new Point(68180, 887),
new Point(29322, 44017),
new Point(46817, 64975),
new Point(10501, 483),
new Point(57094, 60703),
new Point(23318, 35472),
new Point(72452, 88070),
new Point(67775, 28659),
new Point(19450, 20518),
new Point(17314, 26927),
new Point(98088, 11164),
new Point(25050, 56835),
new Point(8364, 6892),
new Point(37868, 18382),
new Point(23723, 7701),
new Point(55767, 11569),
new Point(70721, 66707),
new Point(31863, 9837),
new Point(49358, 30795),
new Point(13041, 39745),
new Point(59635, 26523),
new Point(25859, 1292),
new Point(1551, 53890),
new Point(70316, 94479),
new Point(48549, 86338),
new Point(46413, 92747),
new Point(27186, 50426),
new Point(27591, 22655),
new Point(10905, 46153),
new Point(40408, 84202),
new Point(52821, 73520),
new Point(84865, 77388),
new Point(99819, 32527),
new Point(34404, 75657),
new Point(78457, 96615),
new Point(42140, 5564),
new Point(62175, 92342),
new Point(54958, 67112),
new Point(4092, 19709),
new Point(99415, 60298),
new Point(51090, 52158),
new Point(48953, 58567)
];
```
</div>
</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,109 @@
---
title: Combinations
id: 5958469238c0d8d2632f46db
challengeType: 5
isHidden: false
forumTopicId: 302233
---
## Description
<section id='description'>
Given non-negative integers <code>m</code> and <code>n</code>, generate all size <code>m</code> combinations of the integers from <code>0</code> (zero) to <code>n-1</code> in sorted order (each combination is sorted and the entire table is sorted).
<strong>Example:</strong>
<code>3</code> comb <code>5</code> is:
<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> should be a function.
testString: assert(typeof combinations === 'function');
- text: <code>combinations(3, 5)</code> should return <code>[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]</code>.
testString: assert.deepEqual(combinations(testInput1[0], testInput1[1]), testOutput1);
- text: <code>combinations(4, 6)</code> should return <code>[[0,1,2,3], [0,1,2,4], [0,1,2,5], [0,1,3,4], [0,1,3,5], [0,1,4,5], [0,2,3,4], [0,2,3,5], [0,2,4,5], [0,3,4,5], [1,2,3,4], [1,2,3,5], [1,2,4,5], [1,3,4,5], [2,3,4,5]]</code>
testString: assert.deepEqual(combinations(testInput2[0], testInput2[1]), testOutput2);
```
</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
const testInput1 = [3, 5];
const testOutput1 = [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]];
const testInput2 = [4, 6];
const testOutput2 = [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]];
```
</div>
</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,97 @@
---
title: Comma quibbling
id: 596e414344c3b2872167f0fe
challengeType: 5
isHidden: false
forumTopicId: 302234
---
## Description
<section id='description'>
Comma quibbling is a task originally set by Eric Lippert in his <a href="https://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx" target="_blank">blog</a>.
</section>
## Instructions
<section id='instructions'>
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
<ol>
<li>An input of no words produces the output string of just the two brace characters (<code>"{}"</code>)</li>
<li>An input of just one word, e.g. <code>["ABC"]</code>, produces the output string of the word inside the two braces, e.g. <code>"{ABC}"</code></li>
<li>An input of two words, e.g. <code>["ABC", "DEF"]</code>, produces the output string of the two words inside the two braces with the words separated by the string <code>" and "</code>, e.g. <code>"{ABC and DEF}"</code></li>
<li>An input of three or more words, e.g. <code>["ABC", "DEF", "G", "H"]</code>, produces the output string of all but the last word separated by <code>", "</code> with the last word separated by <code>" and "</code> and all within braces; e.g. <code>"{ABC, DEF, G and H}"</code></li>
</ol>
Test your function with the following series of inputs showing your output here on this page:
<ul>
<li>[] # (No input words).</li>
<li>["ABC"]</li>
<li>["ABC", "DEF"]</li>
<li>["ABC", "DEF", "G", "H"]</li>
</ul>
<strong>Note:</strong> Assume words are non-empty strings of uppercase characters for this task.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>quibble</code> should be a function.
testString: assert(typeof quibble === 'function');
- text: <code>quibble(["ABC"])</code> should return a string.
testString: assert(typeof quibble(["ABC"]) === 'string');
- text: <code>quibble([])</code> should return "{}".
testString: assert.equal(quibble(testCases[0]), results[0]);
- text: <code>quibble(["ABC"])</code> should return "{ABC}".
testString: assert.equal(quibble(testCases[1]), results[1]);
- text: <code>quibble(["ABC", "DEF"])</code> should return "{ABC and DEF}".
testString: assert.equal(quibble(testCases[2]), results[2]);
- text: <code>quibble(["ABC", "DEF", "G", "H"])</code> should return "{ABC,DEF,G and H}".
testString: assert.equal(quibble(testCases[3]), results[3]);
```
</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
const testCases = [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]];
const results = ["{}", "{ABC}", "{ABC and DEF}", "{ABC,DEF,G and H}"];
```
</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,111 @@
---
title: Compare a list of strings
id: 596e457071c35c882915b3e4
challengeType: 5
isHidden: false
forumTopicId: 302235
---
## Description
<section id='description'>
Given a <a href="https://en.wikipedia.org/wiki/List_(abstract_data_type)" title="wp: List_(abstract_data_type)" target="_blank">list</a> of arbitrarily many strings, implement a function for each of the following conditions:
<ul>
<li>test if they are all lexically equal</li>
<li>test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)</li>
</ul>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>allEqual</code> should be a function.
testString: assert(typeof allEqual === 'function');
- text: <code>azSorted</code> should be a function.
testString: assert(typeof azSorted === 'function');
- text: <code>allEqual(["AA", "AA", "AA", "AA"])</code> should return true.
testString: assert(allEqual(testCases[0]));
- text: <code>azSorted(["AA", "AA", "AA", "AA"])</code> should return false.
testString: assert(!azSorted(testCases[0]));
- text: <code>allEqual(["AA", "ACB", "BB", "CC"])</code> should return false.
testString: assert(!allEqual(testCases[1]));
- text: <code>azSorted(["AA", "ACB", "BB", "CC"])</code> should return true.
testString: assert(azSorted(testCases[1]));
- text: <code>allEqual([])</code> should return true.
testString: assert(allEqual(testCases[2]));
- text: <code>azSorted([])</code> should return true.
testString: assert(azSorted(testCases[2]));
- text: <code>allEqual(["AA"])</code> should return true.
testString: assert(allEqual(testCases[3]));
- text: <code>azSorted(["AA"])</code> should return true.
testString: assert(azSorted(testCases[3]));
- text: <code>allEqual(["BB", "AA"])</code> should return false.
testString: assert(!allEqual(testCases[4]));
- text: <code>azSorted(["BB", "AA"])</code> should return false.
testString: assert(!azSorted(testCases[4]));
```
</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
const testCases = [['AA', 'AA', 'AA', 'AA'], ['AA', 'ACB', 'BB', 'CC'], [], ['AA'], ['BB', 'AA']];
```
</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,136 @@
---
title: Convert seconds to compound duration
id: 596fd036dc1ab896c5db98b1
challengeType: 5
isHidden: false
forumTopicId: 302236
---
## Description
<section id='description'>
Implement a function which:
<ul>
<li>takes a positive integer representing a duration in seconds as input (e.g., <code>100</code>), and</li>
<li>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>).</li>
</ul>
Demonstrate that it passes the following three test-cases:
<div style="font-size:115%; font-weight: bold;">Test Cases</div>
| Input number | Output number |
| --- | --- |
| 7259 | <code>2 hr, 59 sec</code> |
| 728640059 | <code>1 d</code> |
| 6000000 | <code>9 wk, 6 d, 10 hr, 40 min</code> |
<div style="font-size:115%; font-weight: bold;">Details</div>
<ul>
<li>
The following five units should be used:
| Unit | Suffix used in Output | Conversion |
| --- | --- | --- |
| week | <code>wk</code> | 1 week = 7 days |
| day | <code>d</code> | 1 day = 24 hours |
| hour | <code>hr</code> | 1 hour = 60 minutes |
| minute | <code>min</code> | 1 minute = 60 seconds |
| second | <code>sec</code> | --- |
</li>
<li>
However, <strong>only</strong> 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>).
</li>
<li>
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>).
</li>
<li>
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).
</li>
</ul>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>convertSeconds</code> should be a function.
testString: assert(typeof convertSeconds === 'function');
- text: <code>convertSeconds(7259)</code> should return <code>2 hr, 59 sec</code>.
testString: assert.equal(convertSeconds(testCases[0]), results[0]);
- text: <code>convertSeconds(86400)</code> should return <code>1 d</code>.
testString: assert.equal(convertSeconds(testCases[1]), results[1]);
- text: <code>convertSeconds(6000000)</code> should return <code>9 wk, 6 d, 10 hr, 40 min</code>.
testString: assert.equal(convertSeconds(testCases[2]), results[2]);
```
</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
const testCases = [7259, 86400, 6000000];
const results = ['2 hr, 59 sec', '1 d', '9 wk, 6 d, 10 hr, 40 min'];
```
</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,86 @@
---
title: Count occurrences of a substring
id: 596fda99c69f779975a1b67d
challengeType: 5
isHidden: false
forumTopicId: 302237
---
## Description
<section id='description'>
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
<ul>
<li>the first argument being the string to search, and</li>
<li>the second a substring to be searched for.</li>
</ul>
It should return an integer count.
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>countSubstring</code> should be a function.
testString: assert(typeof countSubstring === 'function');
- text: <code>countSubstring("the three truths", "th")</code> should return <code>3</code>.
testString: assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
- text: <code>countSubstring("ababababab", "abab")</code> should return <code>2</code>.
testString: assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
- text: <code>countSubstring("abaabba*bbaba*bbab", "a*b")</code> should return <code>2</code>.
testString: assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);
```
</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
const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];
```
</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,93 @@
---
title: Count the coins
id: 59713bd26bdeb8a594fb9413
challengeType: 5
isHidden: false
forumTopicId: 302238
---
## Description
<section id='description'>
There are four types of common coins in <a href="https://en.wikipedia.org/wiki/United_States" target="_blank">US</a> currency:
<ul>
<li>quarters (25 cents)</li>
<li>dimes (10 cents)</li>
<li>nickels (5 cents), and</li>
<li>pennies (1 cent)</li>
</ul>
<p>There are six ways to make change for 15 cents:</p>
<ul>
<li>A dime and a nickel</li>
<li>A dime and 5 pennies</li>
<li>3 nickels</li>
<li>2 nickels and 5 pennies</li>
<li>A nickel and 10 pennies</li>
<li>15 pennies</li>
</ul>
</section>
## Instructions
<section id='instructions'>
Implement a function to determine how many ways there are to make change for a dollar using these common coins (1 dollar = 100 cents)
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>countCoins</code> should be a function.
testString: assert(typeof countCoins === 'function');
- text: <code>countCoins()</code> should return 242.
testString: assert.equal(countCoins(), 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,184 @@
---
title: Cramer's rule
id: 59713da0a428c1a62d7db430
challengeType: 5
isHidden: false
forumTopicId: 302239
---
## Description
<section id='description'>
In <a href="https://en.wikipedia.org/wiki/linear algebra" title="wp: linear algebra" target="_blank">linear algebra</a>, <a href="https://en.wikipedia.org/wiki/Cramer's rule" title="wp: Cramer's rule" target="_blank">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" target="_blank">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.
Given
<big>
$\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.$
</big>
which in matrix format is
<big>
$\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}.$
</big>
Then the values of $x, y$ and $z$ can be found as follows:
<big>
$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} }.$
</big>
</section>
## Instructions
<section id='instructions'>
Given the following system of equations:
<big>
$\begin{cases}
2w-x+5y+z=-3 \\
3w+2x+2y-6z=-32 \\
w+3x+3y-z=-47 \\
5w-2x-3y+3z=49 \\
\end{cases}$
</big>
solve for <big>$w$, $x$, $y$</big> and <big>$z$</big>, using Cramer's rule.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>cramersRule</code> should be a function.
testString: assert(typeof cramersRule === 'function');
- text: <code>cramersRule([[2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3]], [-3, -32, -47, 49])</code> should return <code>[2, -12, -4, 1]</code>.
testString: assert.deepEqual(cramersRule(matrices[0], freeTerms[0]), answers[0]);
- text: <code>cramersRule([[3, 1, 1], [2, 2, 5], [1, -3, -4]], [3, -1, 2])</code> should return <code>[1, 1, -1]</code>.
testString: assert.deepEqual(cramersRule(matrices[1], freeTerms[1]), answers[1]);
```
</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
const matrices = [
[
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3]
],
[
[3, 1, 1],
[2, 2, 5],
[1, -3, -4]
]
];
const freeTerms = [[-3, -32, -47, 49], [3, -1, 2]];
const answers = [[2, -12, -4, 1], [1, 1, -1]];
```
</div>
</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 @@
---
id: 5a23c84252665b21eecc7e03
title: Cumulative standard deviation
challengeType: 5
isHidden: false
forumTopicId: 302240
---
## Description
<section id='description'>
Write a function that takes an array of numbers as parameter and returns the <a href="https://en.wikipedia.org/wiki/Standard Deviation">standard deviation</a> of the series.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>standardDeviation</code> should be a function.
testString: assert(typeof standardDeviation == 'function');
- text: <code>standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])</code> should return a number.
testString: assert(typeof standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]) == 'number');
- text: <code>standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])</code> should return <code>2</code>.
testString: assert.equal(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]), 2);
- text: <code>standardDeviation([600, 470, 170, 430, 300])</code> should return <code>147.323</code>.
testString: assert.equal(standardDeviation([600, 470, 170, 430, 300]), 147.323);
- text: <code>standardDeviation([75, 83, 96, 100, 121, 125])</code> should return <code>18.239</code>.
testString: assert.equal(standardDeviation([75, 83, 96, 100, 121, 125]), 18.239);
- text: <code>standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82])</code> should return <code>16.87</code>.
testString: assert.equal(standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82]), 16.87);
- text: <code>standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314])</code> should return <code>22.631</code>.
testString: assert.equal(standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314]), 22.631);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function standardDeviation(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function standardDeviation(arr) {
var sum = 0,
sum_sq = 0,
n = arr.length;
arr.forEach(function(e) {
sum += e;
sum_sq += e * e;
});
var std_dev = Math.sqrt(sum_sq / n - Math.pow(sum / n, 2));
return Math.round(std_dev * 1000) / 1000;
}
```
</section>

View File

@ -0,0 +1,101 @@
---
id: 5a23c84252665b21eecc7e05
title: CUSIP
challengeType: 5
isHidden: false
forumTopicId: 302241
---
## Description
<section id='description'>
A <b>CUSIP</b> is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
</section>
## Instructions
<section id='instructions'>
Write a function that takes a string as a parameter and checks if the string is valid CUSIP.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isCusip</code> should be a function.
testString: assert(typeof isCusip == 'function');
- text: <code>isCusip("037833100")</code> should return a boolean.
testString: assert(typeof isCusip("037833100") == 'boolean');
- text: <code>isCusip("037833100")</code> should return <code>true</code>.
testString: assert.equal(isCusip("037833100"), true);
- text: <code>isCusip("17275R102")</code> should return <code>true</code>.
testString: assert.equal(isCusip("17275R102"), true);
- text: <code>isCusip("38259P50a")</code> should return <code>false</code>.
testString: assert.equal(isCusip("38259P50a"), false);
- text: <code>isCusip("38259P508")</code> should return <code>true</code>.
testString: assert.equal(isCusip("38259P508"), true);
- text: <code>isCusip("38259P50#")</code> should return <code>false</code>.
testString: assert.equal(isCusip("38259P50#"), false);
- text: <code>isCusip("68389X105")</code> should return <code>true</code>.
testString: assert.equal(isCusip("68389X105"), true);
- text: <code>isCusip("68389X106")</code> should return <code>false</code>.
testString: assert.equal(isCusip("68389X106"), false);
- text: <code>isCusip("5949181")</code> should return <code>false</code>.
testString: assert.equal(isCusip("5949181"), false);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isCusip(s) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function isCusip(s) {
if (s.length != 9) return false;
var sum = 0;
var ASCII = x => x.charCodeAt(0);
for (var i = 0; i < 7; i++) {
var c = s.charCodeAt(i);
var v;
if (c >= ASCII('0') && c <= ASCII('9')) {
v = c - 48;
} else if (c >= ASCII('A') && c <= ASCII('Z')) {
v = c - 64; // lower case letters apparently invalid
} else if (c == ASCII('*')) {
v = 36;
} else if (c == ASCII('@')) {
v = 37;
} else if (c == ASCII('#')) {
v = 38;
} else {
return false;
}
if (i % 2 == 1) v *= 2; // check if odd as using 0-based indexing
sum += Math.floor(v / 10) + (v % 10);
}
return s.charCodeAt(8) - 48 == (10 - (sum % 10)) % 10;
}
```
</section>

View File

@ -0,0 +1,166 @@
---
id: 5a23c84252665b21eecc7e06
title: Cut a rectangle
challengeType: 5
isHidden: false
forumTopicId: 302242
---
## Description
<section id='description'>
A given rectangle is made from <i>m</i> × <i>n</i> squares. If <i>m</i> and <i>n</i> are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
<div style="width: 100%; text-align: center;">
<svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" width="520" height="170" aria-hidden="true" alt="Diagram showing the possible paths for 2 by 2 and 4 by 3 rectangles">
<style>
.g { fill: none; stroke: #ccc }
.s, .s2 { fill: #bff; stroke: black; fill-opacity: .4 }
.s2 { fill: #fbf }
.d { stroke:black; fill:none}
</style>
<defs> <g id="m">
<g id="h4"><g id="h2">
<path id="h" d="m0 10h 640" class="g"/>
<use xlink:href="#h" transform="translate(0,20)"/></g>
<use xlink:href="#h2" transform="translate(0, 40)"/></g>
<use xlink:href="#h4" transform="translate(0,80)"/>
<g id="v8"><g id="v4"><g id="v2">
<path id="v" d="m10 0v160 m 20 0 v-160" class="g"/>
<use xlink:href="#v" transform="translate(40,0)"/></g>
<use xlink:href="#v2" transform="translate(80,0)"/></g>
<use xlink:href="#v4" transform="translate(160,0)"/></g>
<use xlink:href="#v8" transform="translate(320,0)"/></g>
<path id="b" d="m0 0h80v60h-80z" class="s"/>
</defs>
<g transform="translate(.5,.5)">
<use xlink:href="#m"/>
<g transform="translate(10,10)">
<path d="m0 0v40h40v-40z" class="s2"/><path d="m20 0v40" class="d"/>
<path d="m60 0v40h40v-40z" class="s2"/><path d="m60 20h40" class="d"/>
<g transform="translate(120, 0)">
<use xlink:href="#b"/><path d="m0 20h40v20h40" class="d"/></g>
<g transform="translate(220, 0)">
<use xlink:href="#b"/><path d="m0 40h40v-20h40" class="d"/></g>
<g transform="translate(320, 0)">
<use xlink:href="#b"/><path d="m20 0v40h20v-20h20v40" class="d"/></g>
<g transform="translate(420, 0)">
<use xlink:href="#b"/><path d="m60 0v40h-20v-20h-20v40" class="d"/></g>
<g transform="translate(20, 80)">
<use xlink:href="#b"/><path d="m40 0v60" class="d"/></g>
<g transform="translate(120, 80)">
<use xlink:href="#b"/><path d="m60 0v20h-20v20h-20v20" class="d"/></g>
<g transform="translate(220, 80)">
<use xlink:href="#b"/><path d="m20 0v20h20v20h20v20" class="d"/></g>
<g transform="translate(320, 80)">
<use xlink:href="#b"/><path d="m0 20h20v20h20v-20h20v20h20" class="d"/></g>
<g transform="translate(420, 80)">
<use xlink:href="#b"/><path d="m0 40h20v-20h20v20h20v-20h20" class="d"/></g>
</g></g>
</svg>
</div>
</section>
## Instructions
<section id='instructions'>
Write a function that calculates the number of different ways to cut an <i>m</i> × <i>n</i> rectangle.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>cutRectangle</code> should be a function.
testString: assert(typeof cutRectangle == 'function');
- text: <code>cutRectangle(2, 2)</code> should return a number.
testString: assert(typeof cutRectangle(2, 2) == 'number');
- text: <code>cutRectangle(2, 2)</code> should return <code>2</code>.
testString: assert.equal(cutRectangle(2, 2), 2);
- text: <code>cutRectangle(4, 3)</code> should return <code>9</code>.
testString: assert.equal(cutRectangle(4, 3), 9);
- text: <code>cutRectangle(4, 4)</code> should return <code>22</code>.
testString: assert.equal(cutRectangle(4, 4), 22);
- text: <code>cutRectangle(8, 3)</code> should return <code>53</code>.
testString: assert.equal(cutRectangle(8, 3), 53);
- text: <code>cutRectangle(7, 4)</code> should return <code>151</code>.
testString: assert.equal(cutRectangle(7, 4), 151);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function cutRectangle(w, h) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function cutRectangle(w, h) {
if (w % 2 == 1 && h % 2 == 1) return;
var dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]];
var grid = new Array(h);
for (var i = 0; i < grid.length; i++) grid[i] = new Array(w);
var stack = [];
var half = Math.floor((w * h) / 2);
var bits = Math.pow(2, half) - 1;
var result = 0;
for (; bits > 0; bits -= 2) {
for (var i = 0; i < half; i++) {
var r = Math.floor(i / w);
var c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
var count = 1;
while (stack.length != 0) {
var pos = stack.pop();
var r = Math.floor(pos / w);
var c = pos % w;
for (var dir of dirs) {
var nextR = r + dir[0];
var nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
result++;
}
}
return result;
}
```
</section>

View File

@ -0,0 +1,94 @@
---
title: Date format
id: 59669d08d75b60482359409f
challengeType: 5
isHidden: false
forumTopicId: 302243
---
## Description
<section id='description'>
Return an array with the current date in the formats:
<ul>
<li>2007-11-23</li>
<li>Sunday, November 23, 2007</li>
</ul>
Example output: <code>['2007-11-23', 'Sunday, November 23, 2007']</code>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>getDateFormats</code> should be a function.
testString: assert(typeof getDateFormats === 'function');
- text: <code>getDateFormats</code> should return an object.
testString: assert(typeof getDateFormats() === 'object');
- text: <code>getDateFormats</code> should return an array with 2 elements.
testString: assert(getDateFormats().length === 2);
- text: <code>getDateFormats</code> 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
const getDateSolution = () => {
const date = new Date();
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const fmt1 = `${date.getFullYear()}-${(1 + date.getMonth())}-${date.getDate()}`;
const fmt2 = `${weekdays[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
return [fmt1, fmt2];
};
const dates = getDateSolution();
const equalsMessage = `message: <code>getDataFormats()</code> should return <code>["${dates[0]}", "${dates[1]}"]</code>.`;
```
</div>
</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,99 @@
---
title: Date manipulation
id: 5966c21cf732a95f1b67dd28
challengeType: 5
isHidden: false
forumTopicId: 302244
---
## Description
<section id='description'>
Given a date string in EST, output the given date as a string with 12 hours added to the time. Time zone should be preserved.
Example input: <code>"March 7 2009 7:30pm EST"</code>
Example output: <code>"March 8 2009 7:30am EST"</code>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>add12Hours</code> should be a function.
testString: assert(typeof add12Hours === 'function');
- text: <code>add12Hours(dateString)</code> should return a string.
testString: assert(typeof add12Hours('January 17 2017 11:43am EST') === 'string');
- text: <code>add12Hours("January 17 2017 11:43am EST")</code> should return <code>"January 17 2017 11:43pm EST"</code>
testString: assert(add12Hours('January 17 2017 11:43am EST') === 'January 17 2017 11:43pm EST');
- text: Should handle day change. <code>add12Hours("March 7 2009 7:30pm EST")</code> should return <code>"March 8 2009 7:30am EST"</code>
testString: assert(add12Hours('March 7 2009 7:30pm EST') === 'March 8 2009 7:30am EST');
- text: Should handle month change in a leap years. <code>add12Hours("February 29 2004 9:15pm EST")</code> should return <code>"March 1 2004 9:15am EST"</code>
testString: assert(add12Hours('February 29 2004 9:15pm EST') === 'March 1 2004 9:15am EST');
- text: Should handle month change in a common years. <code>add12Hours("February 28 1999 3:15pm EST")</code> should return <code>"March 1 1999 3:15am EST"</code>
testString: assert(add12Hours('February 28 1999 3:15pm EST') === 'March 1 1999 3:15am EST');
- text: Should handle year change. <code>add12Hours("December 31 2020 1:45pm EST")</code> should return <code>"January 1 2021 1:45am EST"</code>
testString: assert(add12Hours('December 31 2020 1:45pm EST') === 'January 1 2021 1:45am EST');
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function add12Hours(dateString) {
// Good luck!
return true;
}
```
</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,82 @@
---
title: Day of the week
id: 5966f99c45e8976909a85575
challengeType: 5
isHidden: false
forumTopicId: 302245
---
## Description
<section id='description'>
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).
</section>
## Instructions
<section id='instructions'>
Write a function that takes a start year and an end year and return an array of all the years where the 25th of December will be a Sunday.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>findXmasSunday</code> should be a function.
testString: assert(typeof findXmasSunday === 'function');
- text: <code>findChristmasSunday(2000, 2100)</code> should return an array.
testString: assert(typeof findXmasSunday(2000, 2100) === 'object');
- text: <code>findChristmasSunday(2008, 2121</code> should return [1977, 1983, 1988, 1994, 2005, 2011, 2016]
testString: assert.deepEqual(findXmasSunday(1970, 2017), firstSolution);
- text: <code>findChristmasSunday(2008, 2121</code> should return [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]
testString: assert.deepEqual(findXmasSunday(2008, 2121), secondSolution);
```
</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
const firstSolution = [1977, 1983, 1988, 1994, 2005, 2011, 2016];
const secondSolution = [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118];
```
</div>
</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,205 @@
---
title: Deal cards for FreeCell
id: 59694356a6e7011f7f1c5f4e
challengeType: 5
isHidden: false
forumTopicId: 302246
---
## Description
<section id='description'>
<i>FreeCell</i> 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="https://rosettacode.org/wiki/DOS" title="DOS" target="_blank">DOS</a>, then <a href="https://rosettacode.org/wiki/Windows" title="Windows" target="_blank">Windows</a>. This version introduced 32000 numbered deals.
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals. These deals are numbered from 1 to 32000. Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this <a href="https://rosettacode.org/wiki/linear congruential generator" title="linear congruential generator" target="_blank">linear congruential generator</a> from Microsoft C:
<ul>
<li>$state_{n + 1} \equiv 214013 \times state_n + 2531011 \pmod{2^{31}}$</li>
<li>$rand_n = state_n \div 2^{16}$</li>
<li>$rand_n$ is in range 0 to 32767.</li>
</ul>
The algorithm follows:
<ol>
<li>Seed the RNG with the number of the deal.
<li>Create an <a href="https://rosettacode.org/wiki/array" title="array" target="_blank">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.</li>
<li>Until the array is empty:</li>
<li>Choose a random card at index &equiv; next random number (mod array length).</li>
<ul>
<li>Swap this random card with the last card of the array.</li>
<li>Remove this random card from the array. (Array length goes down by 1.)</li>
<li>Deal this random card.</li>
</ul>
<li>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.</li>
</ol>
<strong>Example:</strong>
<strong>Order to deal cards</strong>
<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>
<strong>Game #1</strong>
```js
[
['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']
]
```
<strong>Game #617</strong>
```js
[
['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']
]
```
</section>
## Instructions
<section id='instructions'>
Write a function to take a deal number and deal cards in the same order as this algorithm. The function must return a two dimensional array representing the FreeCell board.
Deals can also be checked against <a href="https://freecellgamesolutions.com/" target="_blank">FreeCell solutions to 1000000 games</a>. (Summon a video solution, and it displays the initial deal.)
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>dealFreeCell</code> should be a function.
testString: assert(typeof dealFreeCell === 'function');
- text: <code>dealFreeCell(seed)</code> should return an object.
testString: assert(typeof dealFreeCell(1) === 'object');
- text: <code>dealFreeCell(seed)</code> should return an array of length 7.
testString: assert(dealFreeCell(1).length === 7);
- text: "<code>dealFreeCell(1)</code> should return an array identical to example \"Game #1\""
testString: "assert.deepEqual(dealFreeCell(1), game1);"
- text: "<code>dealFreeCell(617)</code> should return an array identical to example \"Game #617\""
testString: "assert.deepEqual(dealFreeCell(617), game617);"
```
</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
const replaceThis = 3;
const game1 = [
['JD', '2D', '9H', 'JC', '5D', '7H', '7C', '5H'],
['KD', 'KC', '9S', '5S', 'AD', 'QC', 'KH', '3H'],
['2S', 'KS', '9D', 'QD', 'JS', 'AS', 'AH', '3C'],
['4C', '5C', 'TS', 'QH', '4H', 'AC', '4D', '7S'],
['3S', 'TD', '4S', 'TH', '8H', '2C', 'JH', '7D'],
['6D', '8S', '8D', 'QS', '6C', '3D', '8C', 'TC'],
['6S', '9C', '2H', '6H']
];
const game617 = [
['7D', 'AD', '5C', '3S', '5S', '8C', '2D', 'AH'],
['TD', '7S', 'QD', 'AC', '6D', '8H', 'AS', 'KH'],
['TH', 'QC', '3H', '9D', '6S', '8D', '3D', 'TC'],
['KD', '5H', '9S', '3C', '8S', '7H', '4D', 'JS'],
['4C', 'QS', '9C', '9H', '7C', '6H', '2C', '2S'],
['4S', 'TS', '2H', '5D', 'JC', '6C', 'JH', 'QH'],
['JD', 'KS', 'KC', '4H']
];
```
</div>
</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,92 @@
---
title: Deepcopy
id: 596a8888ab7c01048de257d5
challengeType: 5
isHidden: false
forumTopicId: 302247
---
## Description
<section id='description'>
Write a function that returns a deep copy of a given object. The copy must not be the same object that was given.
This task will not test for:
<ul>
<li>Objects with properties that are functions</li>
<li>Date objects or object with properties that are Date objects</li>
<li>RegEx or object with properties that are RegEx objects</li>
<li>Prototype copying</li>
</ul>
</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');
- text: '<code>deepcopy({test: "test"})</code> should return an object.'
testString: 'assert(typeof deepcopy(obj1) === ''object'');'
- text: <code>deepcopy</code> should not return the same object that was provided.
testString: assert(deepcopy(obj2) != obj2);
- text: When passed an object containing an array, <code>deepcopy</code> should return a deep copy of the object.
testString: assert.deepEqual(deepcopy(obj2), obj2);
- text: When passed an object containing another object, <code>deepcopy</code> should return a deep copy of the object.
testString: assert.deepEqual(deepcopy(obj3), obj3);
```
</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
const obj1 = { test: 'test' };
const obj2 = {
t: 'test',
a: ['an', 'array']
};
const obj3 = {
t: 'try',
o: obj2
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
function deepcopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
```
</section>

View File

@ -0,0 +1,96 @@
---
title: Define a primitive data type
id: 597089c87eec450c68aa1643
challengeType: 5
isHidden: false
forumTopicId: 302248
---
## Description
<section id='description'>
Define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10.
Error handling:
<ul>
<li>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>.</li>
<li>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>.</li>
</ul>
</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');
- text: <code>new Num(4)</code> should return an object.
testString: assert(typeof (new Num(4)) === 'object');
- text: <code>new Num('test')</code> should throw a TypeError with message 'Not a Number'.
testString: assert.throws(() => new Num('test'), TypeError);
- text: <code>new Num(0)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(0), TypeError);
- text: <code>new Num(-5)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(-5), TypeError);
- text: <code>new Num(10)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(11), TypeError);
- text: <code>new Num(20)</code> should throw a TypeError with message 'Out of range'.
testString: assert.throws(() => new Num(20), TypeError);
- text: <code>new Num(3) + new Num(4)</code> should equal 7.
testString: assert.equal(new Num(3) + new Num(4), 7);
- text: <code>new Num(3) - new Num(4)</code> should equal -1.
testString: assert.equal(new Num(3) - new Num(4), -1);
- text: <code>new Num(3) * new Num(4)</code> should equal 12.
testString: assert.equal(new Num(3) * new Num(4), 12);
- text: <code>new Num(3) / new Num(4)</code> should equal 0.75.
testString: assert.equal(new Num(3) / new Num(4), 0.75);
- text: <code>new Num(3) < new Num(4)</code> should be true.
testString: assert(new Num(3) < new Num(4));
- text: <code>new Num(3) > new Num(4)</code> should be false.
testString: assert(!(new Num(3) > new Num(4)));
- text: <code>(new Num(5)).toString()</code> should return '5'
testString: assert.equal((new Num(5)).toString(), '5');
```
</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) {
if (isNaN(n)) {
throw new TypeError('Not a Number');
}
if (n < 1 || n > 10) {
throw new TypeError('Out of range');
}
this._value = +n;
}
Num.prototype.valueOf = function() { return this._value; };
Num.prototype.toString = function () { return this._value.toString(); };
```
</section>

View File

@ -0,0 +1,131 @@
---
title: Department Numbers
id: 59f40b17e79dbf1ab720ed7a
challengeType: 5
isHidden: false
forumTopicId: 302249
---
## Description
<section id='description'>
There is a highly organized city that has decided to assign a number to each of their departments:
<ul>
<li>Police department</li>
<li>Sanitation department</li>
<li>Fire department</li>
</ul>
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to the number 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
</section>
## Instructions
<section id='instructions'>
Write a program which outputs all valid combinations as an array.
```js
[2, 3, 7] [2, 4, 6] [2, 6, 4]
[2, 7, 3] [4, 1, 7] [4, 2, 6]
[4, 3, 5] [4, 5, 3] [4, 6, 2]
[4, 7, 1] [6, 1, 5] [6, 2, 4]
[6, 4, 2] [6, 5, 1]
```
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>combinations</code> should be a function.
testString: assert(typeof combinations === 'function');
- text: <code>combinations([1, 2, 3], 6)</code> should return an Array.
testString: assert(Array.isArray(combinations([1, 2, 3], 6)));
- text: <code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return an array of length 14.
testString: assert(combinations(nums, total).length === len);
- text: <code>combinations([1, 2, 3, 4, 5, 6, 7], 12)</code> should return all valid combinations.
testString: assert.deepEqual(combinations(nums, total), result);
```
</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
const nums = [1, 2, 3, 4, 5, 6, 7];
const total = 12;
const len = 14;
const result = [
[2, 3, 7],
[2, 4, 6],
[2, 6, 4],
[2, 7, 3],
[4, 1, 7],
[4, 2, 6],
[4, 3, 5],
[4, 5, 3],
[4, 6, 2],
[4, 7, 1],
[6, 1, 5],
[6, 2, 4],
[6, 4, 2],
[6, 5, 1]
];
```
</div>
</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,169 @@
---
title: Discordian date
id: 59f4eafba0343628bb682785
challengeType: 5
isHidden: false
forumTopicId: 302250
---
## Description
<section id='description'>
Convert a given date from the <a href="https://en.wikipedia.org/wiki/Gregorian calendar" title="wp: Gregorian calendar" target="_blank">Gregorian calendar</a> to the <a href="https://en.wikipedia.org/wiki/Discordian calendar" title="wp: Discordian calendar" target="_blank">Discordian calendar</a>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>discordianDate</code> should be a function.
testString: assert(typeof discordianDate === 'function');
- text: <code>discordianDate(new Date(2010, 6, 22))</code> should return <code>"Pungenday, the 57th day of Confusion in the YOLD 3176"</code>.
testString: assert(discordianDate(new Date(2010, 6, 22)) === 'Pungenday, the 57th day of Confusion in the YOLD 3176');
- text: <code>discordianDate(new Date(2012, 1, 28))</code> should return <code>"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"</code>.
testString: assert(discordianDate(new Date(2012, 1, 28)) === 'Prickle-Prickle, the 59th day of Chaos in the YOLD 3178');
- text: <code>discordianDate(new Date(2012, 1, 29))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!"</code>.
testString: assert(discordianDate(new Date(2012, 1, 29)) === 'Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!');
- text: <code>discordianDate(new Date(2012, 2, 1))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178"</code>.
testString: assert(discordianDate(new Date(2012, 2, 1)) === 'Setting Orange, the 60th day of Chaos in the YOLD 3178');
- text: <code>discordianDate(new Date(2010, 0, 5))</code> should return <code>"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"</code>.
testString: assert(discordianDate(new Date(2010, 0, 5)) === 'Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!');
- text: <code>discordianDate(new Date(2011, 4, 3))</code> should return <code>"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"</code>.
testString: assert(discordianDate(new Date(2011, 4, 3)) === 'Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!');
- text: <code>discordianDate(new Date(2015, 9, 19))</code> should return <code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code>.
testString: assert(discordianDate(new Date(2015, 9, 19)) === 'Boomtime, the 73rd day of Bureaucracy in the YOLD 3181');
```
</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,74 @@
---
id: 5a23c84252665b21eecc7e1e
title: Dot product
challengeType: 5
isHidden: false
forumTopicId: 302251
---
## Description
<section id='description'>
Create a function, to compute the <b><a href="https://en.wikipedia.org/wiki/Dot product">dot product</a></b>, also known as the <b>scalar product</b> of two vectors.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>dotProduct</code> should be a function.
testString: assert(typeof dotProduct == 'function');
- text: <code>dotProduct([1, 3, -5], [4, -2, -1])</code> should return a number.
testString: assert(typeof dotProduct([1, 3, -5], [4, -2, -1]) == 'number');
- text: <code>dotProduct([1, 3, -5], [4, -2, -1])</code> should return <code>3</code>.
testString: assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3);
- text: <code>dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])</code> should return <code>130</code>.
testString: assert.equal(dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]), 130);
- text: <code>dotProduct([5, 4, 3, 2], [7, 8, 9, 6])</code> should return <code>106</code>.
testString: assert.equal(dotProduct([5, 4, 3, 2], [7, 8, 9, 6]), 106);
- text: <code>dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6])</code> should return <code>-36</code>.
testString: assert.equal(dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6]), -36);
- text: <code>dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110])</code> should return <code>10392</code>.
testString: assert.equal(dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110]), 10392);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function dotProduct(ary1, ary2) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function dotProduct(ary1, ary2) {
var dotprod = 0;
for (var i = 0; i < ary1.length; i++) dotprod += ary1[i] * ary2[i];
return dotprod;
}
```
</section>

View File

@ -0,0 +1,96 @@
---
title: Element-wise operations
id: 599c333915e0ea32d04d4bec
challengeType: 5
isHidden: false
forumTopicId: 302252
---
## Description
<section id='description'>
Implement basic element-wise matrix-matrix and scalar-matrix operations.
<strong>Implement:</strong>
<ul>
<li>addition</li>
<li>subtraction</li>
<li>multiplication</li>
<li>division</li>
<li>exponentiation</li>
</ul>
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> should be a function.
testString: assert(typeof operation === 'function');
- text: <code>operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[2,4],[6,8]]</code>.
testString: assert.deepEqual(operation('m_add', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[2, 4], [6, 8]]);
- text: <code>operation("s_add",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[3,4],[5,6]]</code>.
testString: assert.deepEqual(operation('s_add', [[1, 2], [3, 4]], 2), [[3, 4], [5, 6]]);
- text: <code>operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[0,0],[0,0]]</code>.
testString: assert.deepEqual(operation('m_sub', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[0, 0], [0, 0]]);
- text: <code>operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[9,16]]</code>.
testString: assert.deepEqual(operation('m_mult', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 4], [9, 16]]);
- text: <code>operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,1],[1,1]]</code>.
testString: assert.deepEqual(operation('m_div', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 1], [1, 1]]);
- text: <code>operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])</code> should return <code>[[1,4],[27,256]]</code>.
testString: assert.deepEqual(operation('m_exp', [[1, 2], [3, 4]], [[1, 2], [3, 4]]), [[1, 4], [27, 256]]);
- text: <code>operation("m_add",[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])</code> should return <code>[[10,12,14,16],[18,20,22,24]]</code>.
testString: assert.deepEqual(operation('m_add', [[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]), [[10, 12, 14, 16], [18, 20, 22, 24]]);
```
</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,106 @@
---
title: Emirp primes
id: 599d0ba974141b0f508b37d5
challengeType: 5
isHidden: false
forumTopicId: 302253
---
## Description
<section id='description'>
An emirp (<strong>prime</strong> spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
</section>
## Instructions
<section id='instructions'>
Write a function that:
<ul>
<li>Shows the first <code>n</code> emirp numbers.</li>
<li>Shows the emirp numbers in a range.</li>
<li>Shows the number of emirps in a range.</li>
<li>Shows the <code>n<sup>th</sup></code> emirp number.</li>
</ul>
The function should accept two parameters. The first will receive <code>n</code> or the range as an array. The second will receive a boolean, that specifies if the function returns the emirps as an array or a single number (the number of primes in the range or the <code>n<sup>th</sup></code> prime). According to the parameters the function should return an array or a number.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>emirps</code> should be a function.
testString: assert(typeof emirps === 'function');
- text: <code>emirps(20,true)</code> should return <code>[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]</code>
testString: assert.deepEqual(emirps(20, true), [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389]);
- text: <code>emirps(1000)</code> should return <code>70529</code>
testString: assert.deepEqual(emirps(1000), 70529);
- text: <code>emirps([7700,8000],true)</code> should return <code>[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]</code>
testString: assert.deepEqual(emirps([7700, 8000], true), [7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963]);
- text: <code>emirps([7700,8000],true)</code> should return <code>11</code>
testString: assert.deepEqual(emirps([7700, 8000], false), 11);
```
</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,91 @@
---
title: Entropy
id: 599d15309e88c813a40baf58
challengeType: 5
isHidden: false
forumTopicId: 302254
---
## Description
<section id='description'>
Calculate the Shannon entropy H of a given input string.
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:
$H_2(X) = -\sum_{i=1}^n \frac{count_i}{N} \log_2 \left(\frac{count_i}{N}\right)$
where $count_i$ is the count of character $n_i$.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>entropy</code> should be a function.
testString: assert(typeof entropy === 'function');
- text: <code>entropy("0")</code> should return <code>0</code>
testString: assert.equal(entropy('0'), 0);
- text: <code>entropy("01")</code> should return <code>1</code>
testString: assert.equal(entropy('01'), 1);
- text: <code>entropy("0123")</code> should return <code>2</code>
testString: assert.equal(entropy('0123'), 2);
- text: <code>entropy("01234567")</code> should return <code>3</code>
testString: assert.equal(entropy('01234567'), 3);
- text: <code>entropy("0123456789abcdef")</code> should return <code>4</code>
testString: assert.equal(entropy('0123456789abcdef'), 4);
- text: <code>entropy("1223334444")</code> should return <code>1.8464393446710154</code>
testString: assert.equal(entropy('1223334444'), 1.8464393446710154);
```
</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,117 @@
---
title: Equilibrium index
id: 5987fd532b954e0f21b5d3f6
challengeType: 5
isHidden: false
forumTopicId: 302255
---
## Description
<section id='description'>
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.
For example, in a sequence <big>$A$</big>:
<ul style="list-style: none;">
<li><big>$A_0 = -7$</big></li>
<li><big>$A_1 = 1$</big></li>
<li><big>$A_2 = 5$</big></li>
<li><big>$A_3 = 2$</big></li>
<li><big>$A_4 = -4$</big></li>
<li><big>$A_5 = 3$</big></li>
<li><big>$A_6 = 0$</big></li>
</ul>
<code>3</code> is an equilibrium index, because:
<ul style="list-style: none;">
<li><big>$A_0 + A_1 + A_2 = A_4 + A_5 + A_6$</big></li>
</ul>
<code>6</code> is also an equilibrium index, because:
<ul style="list-style: none;">
<li><big>$A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0$</big></li>
</ul>
(sum of zero elements is zero)
<code>7</code> is not an equilibrium index, because it is not a valid index of sequence <big>$A$</big>.
</section>
## Instructions
<section id='instructions'>
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>equilibrium</code> should be a function.
testString: assert(typeof equilibrium === 'function');
- text: <code>equilibrium([-7, 1, 5, 2, -4, 3, 0])</code> should return <code>[3,6]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[0]), ans[0]);
- text: <code>equilibrium([2, 4, 6])</code> should return <code>[]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[1]), ans[1]);
- text: <code>equilibrium([2, 9, 2])</code> should return <code>[1]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[2]), ans[2]);
- text: <code>equilibrium([1, -1, 1, -1, 1, -1, 1])</code> should return <code>[0,1,2,3,4,5,6]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[3]), ans[3]);
- text: <code>equilibrium([1])</code> should return <code>[0]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[4]), ans[4]);
- text: <code>equilibrium([])</code> should return <code>[]</code>.
testString: assert.deepEqual(equilibrium(equilibriumTests[5]), ans[5]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function equilibrium(a) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const equilibriumTests =
[[-7, 1, 5, 2, -4, 3, 0], // 3, 6
[2, 4, 6], // empty
[2, 9, 2], // 1
[1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6
[1], // 0
[] // empty
];
const ans = [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []];
```
</div>
</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,137 @@
---
title: Ethiopian multiplication
id: 599d1566a02b571412643b84
challengeType: 5
isHidden: false
forumTopicId: 302257
---
## Description
<section id='description'>
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
<strong>Method:</strong>
<ol>
<li>Take two numbers to be multiplied and write them down at the top of two columns</li>
<li>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 <code>1</code></li>
<li>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 <code>1</code></li>
<li>Examine the table produced and discard any row where the value in the left column is even</li>
<li>Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together</li>
</ol>
<strong>For example:</strong> <code>17 &times; 34</code>
<pre>
17 34
</pre>
Halving the first column:
<pre>
17 34
8
4
2
1
</pre>
Doubling the second column:
<pre>
17 34
8 68
4 136
2 272
1 544
</pre>
Strike-out rows whose first cell is even:
<pre>
17 34
8 <strike>68</strike>
4 <strike>136</strike>
2 <strike>272</strike>
1 544
</pre>
Sum the remaining numbers in the right-hand column:
<pre>
17 34
8 --
4 ---
2 ---
1 544
====
578
</pre>
So <code>17</code> multiplied by <code>34</code>, by the Ethiopian method is <code>578</code>.
</section>
## Instructions
<section id='instructions'>
The task is to define three named functions/methods/procedures/subroutines:
<ol>
<li>one to halve an integer,</li>
<li>one to double an integer, and</li>
<li>one to state if an integer is even</li>
</ol>
Use these functions to create a function that does Ethiopian multiplication.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>eth_mult</code> should be a function.
testString: assert(typeof eth_mult === 'function');
- text: <code>eth_mult(17,34)</code> should return <code>578</code>.
testString: assert.equal(eth_mult(17, 34), 578);
- text: <code>eth_mult(23,46)</code> should return <code>1058</code>.
testString: assert.equal(eth_mult(23, 46), 1058);
- text: <code>eth_mult(12,27)</code> should return <code>324</code>.
testString: assert.equal(eth_mult(12, 27), 324);
- text: <code>eth_mult(56,98)</code> should return <code>5488</code>.
testString: assert.equal(eth_mult(56, 98), 5488);
- text: <code>eth_mult(63,74)</code> should return <code>4662</code>.
testString: assert.equal(eth_mult(63, 74), 4662);
```
</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,127 @@
---
title: Euler method
id: 59880443fb36441083c6c20e
challengeType: 5
isHidden: false
forumTopicId: 302258
---
## Description
<section id='description'>
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" target="_blank">the wikipedia page</a>.
The ODE has to be provided in the following form:
<ul style="list-style: none;">
<li><big>$\frac{dy(t)}{dt} = f(t,y(t))$</big></li>
</ul>
with an initial value
<ul style="list-style: none;">
<li><big>$y(t_0) = y_0$</big></li>
</ul>
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
<ul style="list-style: none;">
<li><big>$\frac{dy(t)}{dt} \approx \frac{y(t+h)-y(t)}{h}$</big></li>
</ul>
then solve for $y(t+h)$:
<ul style="list-style: none;">
<li><big>$y(t+h) \approx y(t) + h \, \frac{dy(t)}{dt}$</big></li>
</ul>
which is the same as
<ul style="list-style: none;">
<li><big>$y(t+h) \approx y(t) + h \, f(t,y(t))$</big></li>
</ul>
The iterative solution rule is then:
<ul style="list-style: none;">
<li><big>$y_{n+1} = y_n + h \, f(t_n, y_n)$</big></li>
</ul>
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.
<strong>Example: Newton's Cooling Law</strong>
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>:
<ul style="list-style: none;">
<li><big>$\frac{dT(t)}{dt} = -k \, \Delta T$</big></li>
</ul>
or
<ul style="list-style: none;">
<li><big>$\frac{dT(t)}{dt} = -k \, (T(t) - T_R)$</big></li>
</ul>
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.
The analytical solution, which we will compare to the numerical approximation, is
<ul style="list-style: none;">
<li><big>$T(t) = T_R + (T_0 - T_R) \; e^{-k t}$</big></li>
</ul>
</section>
## Instructions
<section id='instructions'>
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
<ul>
<li><code>2 s</code></li>
<li><code>5 s</code> and</li>
<li><code>10 s</code></li>
</ul>
and to compare with the analytical solution.
<strong>Initial values:</strong>
<ul>
<li>initial temperature <big>$T_0$</big> shall be <code>100 °C</code></li>
<li>room temperature <big>$T_R$</big> shall be <code>20 °C</code></li>
<li>cooling constant <big>$k$</big> shall be <code>0.07</code></li>
<li>time interval to calculate shall be from <code>0 s</code> to <code>100 s</code></li>
</ul>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>eulersMethod</code> should be a function.
testString: assert(typeof eulersMethod === 'function');
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return a number.
testString: assert(typeof eulersMethod(0, 100, 100, 10) === 'number');
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return 20.0424631833732.
testString: assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732);
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return 20.01449963666907.
testString: assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907);
- text: <code>eulersMethod(0, 100, 100, 10)</code> should return 20.000472392.
testString: assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392);
```
</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,74 @@
---
title: Evaluate binomial coefficients
id: 598de241872ef8353c58a7a2
challengeType: 5
isHidden: false
forumTopicId: 302259
---
## Description
<section id='description'>
Write a function to calculate the binomial coefficient for the given value of n and k.
This formula is recommended:
$\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> should be a function.
testString: assert(typeof binom === 'function');
- text: <code>binom(5,3)</code> should return 10.
testString: assert.equal(binom(5, 3), 10);
- text: <code>binom(7,2)</code> should return 21.
testString: assert.equal(binom(7, 2), 21);
- text: <code>binom(10,4)</code> should return 210.
testString: assert.equal(binom(10, 4), 210);
- text: <code>binom(6,1)</code> should return 6.
testString: assert.equal(binom(6, 1), 6);
- text: <code>binom(12,8)</code> should return 495.
testString: assert.equal(binom(12, 8), 495);
```
</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,231 @@
---
title: Execute a Markov algorithm
id: 59e09e6d412c5939baa02d16
challengeType: 5
isHidden: false
forumTopicId: 302260
---
## Description
<section id='description'>
Create an interpreter for a <a href="https://en.wikipedia.org/wiki/Markov algorithm" title="wp: Markov algorithm" target="_blank">Markov Algorithm</a>.
Rules have the syntax:
<pre>
[ruleset] ::= (([comment] | [rule]) [newline]+)*
[comment] ::= # {[any character]}
[rule] ::= [pattern] [whitespace] -> [whitespace] [.] [replacement]
[whitespace] ::= ([tab] | [space]) [[whitespace]]
</pre>
There is one rule per line.
If there is a <code>.</code> (period) present before the [replacement], then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
<span style="font-size: 1.5rem">Rulesets</span>
Use the following tests on entries:
<strong>Ruleset 1:</strong>
<pre>
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
</pre>
Sample text of:
<code>I bought a B of As from T S.</code>
Should generate the output:
<code>I bought a bag of apples from my brother.</code>
<strong>Ruleset 2:</strong>
A test of the terminating rule
<pre>
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
</pre>
Sample text of:
<code>I bought a B of As from T S.</code>
Should generate:
<code>I bought a bag of apples from T shop.</code>
<strong>Ruleset 3:</strong>
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
<pre>
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
</pre>
Sample text of:
<code>I bought a B of As W my Bgage from T S.</code>
Should generate:
<code>I bought a bag of apples with my money from T shop.</code>
<strong>Ruleset 4:</strong>
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.)
<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
# addition
1! -> !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>
Sample text of:
<code>_1111*11111_</code>
should generate the output:
<code>11111111111111111111</code>
<strong>Ruleset 5:</strong>
A simple <a href="http://en.wikipedia.org/wiki/Turing_machine" title="link: http://en.wikipedia.org/wiki/Turing_machine" target="_blank">Turing machine</a>, implementing a three-state <a href="http://en.wikipedia.org/wiki/Busy_beaver" title="link: http://en.wikipedia.org/wiki/Busy_beaver" target="_blank">busy beaver</a>.
The tape consists of <code>0</code>s and <code>1</code>s, the states are <code>A</code>, <code>B</code>, <code>C</code> and <code>H</code> (for <code>H</code>alt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input.
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.
<pre>
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
</pre>
This ruleset should turn
<code>000000A000000</code>
into
<code>00011H1111000</code>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>markov</code> should be a function.
testString: assert(typeof markov === 'function');
- text: <code>markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from my brother.".
testString: assert.deepEqual(markov(rules[0],tests[0]),outputs[0]);
- text: <code>markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from T shop.".
testString: assert.deepEqual(markov(rules[1],tests[1]),outputs[1]);
- text: <code>markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")</code> should return "I bought a bag of apples with my money from T shop.".
testString: assert.deepEqual(markov(rules[2],tests[2]),outputs[2]);
- text: <code>markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")</code> should return "11111111111111111111".
testString: assert.deepEqual(markov(rules[3],tests[3]),outputs[3]);
- text: <code>markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")</code> should return "00011H1111000".
testString: assert.deepEqual(markov(rules[4],tests[4]),outputs[4]);
```
</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,206 @@
---
title: Execute Brain****
id: 59e0a8df964e4540d5abe599
challengeType: 5
isHidden: false
forumTopicId: 302261
---
## Description
<section id='description'>
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:
RCBF is a set of <a href="https://rosettacode.org/wiki/Brainf***" title="Brainf***" target="_blank">Brainf***</a> compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
| Command | Description |
| --- | --- |
| <code>&gt;</code> | Move the pointer to the right |
| <code>&lt;</code> | Move the pointer to the left |
| <code>+</code> | Increment the memory cell under the pointer |
| <code>-</code> | Decrement the memory cell under the pointer |
| <code>.</code> | Output the character signified by the cell at the pointer |
| <code>,</code> | Input a character and store it in the cell at the pointer |
| <code>[</code> | Jump past the matching <code>]</code> if the cell under the pointer is 0 |
| <code>]</code> | Jump back to the matching <code>[</code> if the cell under the pointer is nonzero |
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.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>brain(bye)</code> should return a string
testString: assert(typeof brain(bye) === 'string');
- text: <code>brain("++++++[>++++++++++<-]>+++++.")</code should return "A"
testString: assert.equal(brain("++++++[>++++++++++<-]>+++++."),"A");
- text: <code>brain(bye)</code> should return <code>Goodbye, World!\\r\\n</code>
testString: assert.equal(brain(bye), 'Goodbye, World!\r\n');
- text: <code>brain(hello)</code> should return <code>Hello World!\\n</code>
testString: assert.equal(brain(hello), "Hello World!\n");
- text: <code>brain(fib)</code> should return <code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89</code>
testString: assert.equal(brain(fib), "1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89");
```
</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,111 @@
---
title: Extensible prime generator
id: 598ee8b91b410510ae82efef
challengeType: 5
isHidden: false
forumTopicId: 302262
---
## Description
<section id='description'>
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The generator should be able to:
<ul>
<li>Show the first <code>n</code> prime numbers</li>
<li>Show the prime numbers in a range</li>
<li>Show the number of primes in a range</li>
<li>Show the <code>n<sup>th</sup></code> prime number</li>
</ul>
The function should have two parameters. The first will receive <code>n</code> or the range as an array. The second will receive a boolean, that specifies if the function returns the prime numbers as an array or a single number(the number of primes in the range or the <code>n<sup>th</sup></code> prime). According to the parameters the function should return an array.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>primeGenerator</code> should be a function.
testString: assert(typeof primeGenerator === 'function');
- text: <code>primeGenerator</code> should be a function.
testString: assert.deepEqual(primeGenerator(20, true), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]);
- text: <code>primeGenerator</code> should be a function.
testString: assert.deepEqual(primeGenerator([100, 150], true), [101, 103, 107, 109, 113, 127, 131, 137, 139, 149]);
- text: <code>primeGenerator</code> should be a function.
testString: assert.equal(primeGenerator([7700, 8000], false), 30);
- text: <code>primeGenerator</code> should be a function.
testString: assert.equal(primeGenerator(10000, false), 104729);
```
</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,82 @@
---
title: Factorial
id: 597b2b2a2702b44414742771
challengeType: 5
isHidden: false
forumTopicId: 302263
---
## Description
<section id='description'>
Write a function to return the factorial of a number.
Factorial of a number is given by:
<pre>
<big>n! = n * (n-1) * (n-2) * ..... * 1</big>
</pre>
For example:
<ul>
<li><code>3! = 3 * 2 * 1 = 6</code></li>
<li><code>4! = 4 * 3 * 2 * 1 = 24</code></li>
</ul>
<strong>Note:</strong> <code>0! = 1</code>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>factorial</code> should be a function.
testString: assert(typeof factorial === 'function');
- text: <code>factorial(2)</code> should return a number.
testString: assert(typeof factorial(2) === 'number');
- text: <code>factorial(3)</code> should return 6.
testString: assert.equal(factorial(3), 6);
- text: <code>factorial(5)</code> should return 120.
testString: assert.equal(factorial(5), 120);
- text: <code>factorial(10)</code> should return 3,628,800.
testString: assert.equal(factorial(10), 3628800);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function factorial(n) {
// Good luck!
}
```
</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,132 @@
---
title: Factors of a Mersenne number
id: 598eea87e5cf4b116c3ff81a
challengeType: 5
isHidden: false
forumTopicId: 302264
---
## Description
<section id='description'>
A Mersenne number is a number in the form of <code>2<sup>P</sup>-1</code>.
If <code>P</code> is prime, the Mersenne number may be a Mersenne prime. (If <code>P</code> is not prime, the Mersenne number is also not prime.)
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="https://rosettacode.org/wiki/Lucas-Lehmer test" title="Lucas-Lehmer test" target="_blank">Lucas-Lehmer test</a>.
There are very efficient algorithms for determining if a number divides <code>2<sup>P</sup>-1</code> (or equivalently, if <code>2<sup>P</sup> mod (the number) = 1</code>).
Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).
The following is how to implement this modPow yourself:
For example, let's compute <code>2<sup>23</sup> mod 47</code>.
Convert the exponent 23 to binary, you get 10111. Starting with <code><tt>square</tt> = 1</code>, repeatedly square it.
Remove the top bit of the exponent, and if it's 1 multiply <code><tt>square</tt></code> by the base of the exponentiation (2), then compute <code><tt>square</tt> modulo 47</code>.
Use the result of the modulo from the last step as the initial value of <code><tt>square</tt></code> in the next step:
<pre>
Remove Optional
square top bit multiply by 2 mod 47
------------ ------- ------------- ------
1*1 = 1 1 0111 1*2 = 2 2
2*2 = 4 0 111 no 4
4*4 = 16 1 11 16*2 = 32 32
32*32 = 1024 1 1 1024*2 = 2048 27
27*27 = 729 1 729*2 = 1458 1
</pre>
Since <code>2<sup>23</sup> mod 47 = 1</code>, 47 is a factor of <code>2<sup>P</sup>-1</code>.
(To see this, subtract 1 from both sides: <code>2<sup>23</sup>-1 = 0 mod 47</code>.)
Since we've shown that 47 is a factor, <code>2<sup>23</sup>-1</code> is not prime.
Further properties of Mersenne numbers allow us to refine the process even more.
Any factor <code>q</code> of <code>2<sup>P</sup>-1</code> must be of the form <code>2kP+1</code>, <code>k</code> being a positive integer or zero. Furthermore, <code>q</code> must be <code>1</code> or <code>7 mod 8</code>.
Finally any potential factor <code>q</code> must be <a href="https://rosettacode.org/wiki/Primality by Trial Division" title="Primality by Trial Division" target="_blank">prime</a>.
As in other trial division algorithms, the algorithm stops when <code>2kP+1 > sqrt(N)</code>.These primarily tests only work on Mersenne numbers where <code>P</code> is prime. For example, <code>M<sub>4</sub>=15</code> yields no factors using these techniques, but factors into 3 and 5, neither of which fit <code>2kP+1</code>.
</section>
## Instructions
<section id='instructions'>
Using the above method find a factor of <code>2<sup>929</sup>-1</code> (aka M929)
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>check_mersenne</code> should be a function.
testString: assert(typeof check_mersenne === 'function');
- text: <code>check_mersenne(3)</code> should return a string.
testString: assert(typeof check_mersenne(3) == '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");
- 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");
- 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");
```
</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,85 @@
---
title: Factors of an integer
id: 597f1e7fbc206f0e9ba95dc4
challengeType: 5
isHidden: false
forumTopicId: 302265
---
## Description
<section id='description'>
Write a function that returns the factors of a positive integer as an array.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>factors</code> should be a function.
testString: assert(typeof factors === 'function');
- text: <code>factors(45)</code> should return <code>[1,3,5,9,15,45]</code>.
testString: assert.deepEqual(factors(45), ans[0]);
- text: <code>factors(53)</code> should return <code>[1,53]</code>.
testString: assert.deepEqual(factors(53), ans[1]);
- text: <code>factors(64)</code> should return <code>[1,2,4,8,16,32,64]</code>.
testString: assert.deepEqual(factors(64), ans[2]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function factors(num) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
const ans=[[1,3,5,9,15,45],[1,53],[1,2,4,8,16,32,64]];
```
</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,95 @@
---
title: Farey sequence
id: 59c3ec9f15068017c96eb8a3
challengeType: 5
isHidden: false
forumTopicId: 302266
---
## Description
<section id='description'>
The <a href="https://en.wikipedia.org/wiki/Farey sequence" title="wp: Farey sequence" target="_blank">Farey sequence</a> <code>F<sub>n</sub></code> of order <code>n</code> is the sequence of completely reduced fractions between <code>0</code> and <code>1</code> which, when in lowest terms, have denominators less than or equal to <code>n</code>, arranged in order of increasing size.
The <i>Farey sequence</i> is sometimes incorrectly called a <i>Farey series</i>.
Each Farey sequence:
<ul>
<li>starts with the value 0, denoted by the fraction $ \frac{0}{1} $</li>
<li>ends with the value 1, denoted by the fraction $ \frac{1}{1}$.</li>
</ul>
The Farey sequences of orders <code>1</code> to <code>5</code> are:
<ul>
<li style="list-style: none;">${\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}$</li>
<li style="list-style: none;">${\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}$</li>
<li style="list-style: none;">${\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}$</li>
<li style="list-style: none;">${\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}$</li>
<li style="list-style: none;">${\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}$</li>
</ul>
</section>
## Instructions
<section id='instructions'>
Write a function that returns the Farey sequence of order <code>n</code>. The function should have one parameter that is <code>n</code>. It should return the sequence as an array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>farey</code> should be a function.
testString: assert(typeof farey === 'function');
- text: <code>farey(3)</code> should return an array
testString: assert(Array.isArray(farey(3)));
- text: <code>farey(3)</code> should return <code>["1/3","1/2","2/3"]</code>
testString: assert.deepEqual(farey(3), ["1/3","1/2","2/3"]);
- text: <code>farey(4)</code> should return <code>["1/4","1/3","1/2","2/4","2/3","3/4"]</code>
testString: assert.deepEqual(farey(4), ["1/4","1/3","1/2","2/4","2/3","3/4"]);
- text: <code>farey(5)</code> should return <code>["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]</code>
testString: assert.deepEqual(farey(5), ["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]);
```
</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,122 @@
---
title: Fibonacci n-step number sequences
id: 598eef80ba501f1268170e1e
challengeType: 5
isHidden: false
forumTopicId: 302267
---
## Description
<section id='description'>
These number series are an expansion of the ordinary <a href="https://rosettacode.org/wiki/Fibonacci sequence" title="Fibonacci sequence" target="_blank">Fibonacci sequence</a> where:
<ol>
<li>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$</li>
<li>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$</li>
<li>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$...</li>
<li>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)}}$</li>
</ol>
For small values of $n$, <a href="https://en.wikipedia.org/wiki/Number prefix#Greek_series" title="wp: Number prefix#Greek_series" target="_blank">Greek numeric prefixes</a> are sometimes used to individually name each series.
Fibonacci $n$-step sequences:
| $n$ | Series name | Values |
| --- | --- | --- |
| 2 | fibonacci | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |
| 3 | tribonacci | 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |
| 4 | tetranacci | 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |
| 5 | pentanacci | 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |
| 6 | hexanacci | 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |
| 7 | heptanacci | 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |
| 8 | octonacci | 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |
| 9 | nonanacci | 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |
| 10 | decanacci | 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |
Allied sequences can be generated where the initial values are changed:
The <a href="https://en.wikipedia.org/wiki/Lucas number" title="wp: Lucas number" target="_blank">Lucas series</a> sums the two preceding values like the fibonacci series for $n=2$ but uses $[2, 1]$ as its initial values.
</section>
## Instructions
<section id='instructions'>
Write a function to generate Fibonacci $n$-step number sequences and Lucas sequences. The first parameter will be $n$. The second parameter will be the number of elements to be returned. The third parameter will specify whether to output the Fibonacci sequence or the Lucas sequence. If the parameter is <code>"f"</code> then return the Fibonacci sequence and if it is <code>"l"</code>, then return the Lucas sequence. The sequences must be returned as an array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fib_luc</code> should be a function.
testString: assert(typeof fib_luc === 'function');
- text: <code>fib_luc(2,10,"f")</code> should return <code>[1,1,2,3,5,8,13,21,34,55]</code>.
testString: assert.deepEqual(fib_luc(2,10,"f"),ans[0]);
- text: <code>fib_luc(3,15,"f")</code> should return <code>[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]</code>.
testString: assert.deepEqual(fib_luc(3,15,"f"),ans[1]);
- text: <code>fib_luc(4,15,"f")</code> should return <code>[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]</code>.
testString: assert.deepEqual(fib_luc(4,15,"f"),ans[2]);
- text: <code>fib_luc(2,10,"l")</code> should return <code>[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]</code>.
testString: assert.deepEqual(fib_luc(2,10,"l"),ans[3]);
- text: <code>fib_luc(3,15,"l")</code> should return <code>[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]</code>.
testString: assert.deepEqual(fib_luc(3,15,"l"),ans[4]);
- text: <code>fib_luc(4,15,"l")</code> should return <code>[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]</code>.
testString: assert.deepEqual(fib_luc(4,15,"l"),ans[5]);
- text: <code>fib_luc(5,15,"l")</code> should return <code>[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]</code>.
testString: assert.deepEqual(fib_luc(5,15,"l"),ans[6]);
```
</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
const ans = [[1,1,2,3,5,8,13,21,34,55],
[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136],
[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536],
[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76],
[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ],
[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ],
[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]];
```
</div>
</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,77 @@
---
title: Fibonacci sequence
id: 597f24c1dda4e70f53c79c81
challengeType: 5
isHidden: false
forumTopicId: 302268
---
## Description
<section id='description'>
Write a function to generate the <code>n<sup>th</sup></code> Fibonacci number.
The <code>n<sup>th</sup></code> Fibonacci number is given by:
<code>F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></code>
The first two terms of the series are 0 and 1.
Hence, the series is: 0, 1, 1, 2, 3, 5, 8, 13...
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fibonacci</code> should be a function.
testString: assert(typeof fibonacci === 'function');
- text: <code>fibonacci(2)</code> should return a number.
testString: assert(typeof fibonacci(2) == 'number');
- text: <code>fibonacci(3)</code> should return 2.
testString: assert.equal(fibonacci(3),2);
- text: <code>fibonacci(5)</code> should return 5.
testString: assert.equal(fibonacci(5),5);
- text: <code>fibonacci(10)</code> should return 55.
testString: assert.equal(fibonacci(10),55);
```
</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,133 @@
---
title: Fibonacci word
id: 5992e222d397f00d21122931
challengeType: 5
isHidden: false
forumTopicId: 302269
---
## Description
<section id='description'>
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence <a href="https://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf" target="_blank">as described here</a>:
<pre>
Define F_Word<sub>1</sub> as <strong>1</strong>
Define F_Word<sub>2</sub> as <strong>0</strong>
Form F_Word<sub>3</sub> as F_Word<sub>2</sub> concatenated with F_Word<sub>1</sub> i.e.: <strong>01</strong>
Form F_Word<sub>n</sub> as F_Word<sub>n-1</sub> concatenated with F_word<sub>n-2</sub>
</pre>
</section>
## Instructions
<section id='instructions'>
Write a function to return the Fibonacci Words up to <code>n</code>. <code>n</code> will be provided as a parameter to the function. The function should return an array of objects. The objects should be of the form: <code>{ N: 1, Length: 1, Entropy: 0, Word: '1' }</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fibWord</code> should be a function.
testString: assert(typeof fibWord === 'function');
- text: <code>fibWord(5)</code> should return an array.
testString: assert(Array.isArray(fibWord(5)));
- text: <code>fibWord(5)</code> should return <code>[{ N:1, Length:1, Entropy:0, Word:"1" },{ N:2, Length:1, Entropy:0, Word:"0" },{ N:3, Length:2, Entropy:1, Word:"01" },{ N:4, Length:3, Entropy:0.9182958340544896, Word:"010" },{ N:5, Length:5, Entropy:0.9709505944546688, Word:"01001" }]</code>.
testString: assert.deepEqual(fibWord(5),ans);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function fibWord(n) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
let ans=[ { N: 1, Length: 1, Entropy: 0, Word: '1' },
{ N: 2, Length: 1, Entropy: 0, Word: '0' },
{ N: 3, Length: 2, Entropy: 1, Word: '01' },
{ N: 4, Length: 3, Entropy: 0.9182958340544896, Word: '010' },
{ N: 5, Length: 5, Entropy: 0.9709505944546688, Word: '01001' }];
```
</div>
</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,116 @@
---
title: Fractran
id: 5a7dad05be01840e1778a0d1
challengeType: 5
isHidden: false
forumTopicId: 302270
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/FRACTRAN" title="wp: FRACTRAN" target="_blank">FRACTRAN</a> is a Turing-complete esoteric programming language invented by the mathematician <a href="https://en.wikipedia.org/wiki/John Horton Conway" title="wp: John Horton Conway" target="_blank">John Horton Conway</a>.
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$.
The program is run by updating the integer $n$ as follows:
<ul>
<li>for the first fraction, $f_i$, in the list for which $nf_i$ is an integer, replace $n$ with $nf_i$ ;</li>
<li>repeat this rule until no fraction in the list produces an integer when multiplied by $n$, then halt.</li>
</ul>
Conway gave a program for primes in FRACTRAN:
<span style="margin-left: 1em;">$\dfrac{17}{91}$, $\dfrac{78}{85}$, $\dfrac{19}{51}$, $\dfrac{23}{38}$, $\dfrac{29}{33}$, $\dfrac{77}{29}$, $\dfrac{95}{23}$, $\dfrac{77}{19}$, $\dfrac{1}{17}$, $\dfrac{11}{13}$, $\dfrac{13}{11}$, $\dfrac{15}{14}$, $\dfrac{15}{2}$, $\dfrac{55}{1}$</span>
Starting with $n=2$, this FRACTRAN program will change $n$ to $15=2\times (\frac{15}{2})$, then $825=15\times (\frac{55}{1})$, generating the following sequence of integers:
<span style="margin-left: 1em;">$2$, $15$, $825$, $725$, $1925$, $2275$, $425$, $390$, $330$, $290$, $770$, $\ldots$</span>
After 2, this sequence contains the following powers of 2:
<span style="margin-left: 1em;">$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>
which are the prime powers of 2.
</section>
## Instructions
<section id='instructions'>
Write a function that takes a fractran program as a string parameter and returns the first 10 numbers of the program as an array. If the result does not have 10 numbers then return the numbers as is.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>fractran</code> should be a function.
testString: assert(typeof fractran=='function');
- text: <code>fractran("3/2, 1/3")</code> should return an array.
testString: assert(Array.isArray(fractran('3/2, 1/3')));
- text: <code>fractran("3/2, 1/3")</code> should return <code>[ 2, 3, 1 ]</code>.
testString: assert.deepEqual(fractran('3/2, 1/3'), [ 2, 3, 1 ]);
- text: <code>fractran("3/2, 5/3, 1/5")</code> should return <code>[ 2, 3, 5, 1 ]</code>.
testString: assert.deepEqual(fractran('3/2, 5/3, 1/5'), [ 2, 3, 5, 1 ]);
- text: <code>fractran("3/2, 6/3")</code> should return <code>[ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]</code>.
testString: assert.deepEqual(fractran('3/2, 6/3'), [ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]);
- text: <code>fractran("2/7, 7/2")</code> should return <code>[ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]</code>.
testString: assert.deepEqual(fractran('2/7, 7/2'), [ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]);
- text: <code>fractran("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1")</code> should return <code>[ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]</code>.
testString: assert.deepEqual(fractran('17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1'), [ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function fractran(progStr) {
// Good luck!
}
```
</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,101 @@
---
title: Gamma function
id: 5a23c84252665b21eecc7e76
challengeType: 5
isHidden: false
forumTopicId: 302271
---
## 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')
- text: <code>gamma(.1)</code> should return a number.
testString: assert(typeof gamma(.1)=='number')
- text: <code>gamma(.1)</code> should return <code>9.513507698668736</code>.
testString: assert.equal(round(gamma(.1)), round(9.513507698668736))
- text: <code>gamma(.2)</code> should return <code>4.590843711998803</code>.
testString: assert.equal(round(gamma(.2)), round(4.590843711998803))
- text: <code>gamma(.3)</code> should return <code>2.9915689876875904</code>.
testString: assert.equal(round(gamma(.3)), round(2.9915689876875904))
- text: <code>gamma(.4)</code> should return <code>2.218159543757687</code>.
testString: assert.equal(round(gamma(.4)), round(2.218159543757687))
- text: <code>gamma(.5)</code> should return <code>1.7724538509055159</code>.
testString: assert.equal(round(gamma(.5)), round(1.7724538509055159))
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gamma(x) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
function round(x) {
return Number(x).toPrecision(13);
}
```
</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,170 @@
---
title: Gaussian elimination
id: 5a23c84252665b21eecc7e77
challengeType: 5
isHidden: false
forumTopicId: 302272
---
## Description
<section id='description'>
Write a function to solve \(Ax = 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');
- text: <code>gaussianElimination([[1,1],[1,-1]], [5,1])</code> should return an array.
testString: assert(Array.isArray(gaussianElimination([[1,1],[1,-1]], [5,1])));
- text: <code>gaussianElimination([[1,1],[1,-1]], [5,1])</code> should return <code>[ 3, 2 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,1],[1,-1]], [5,1]), [ 3, 2 ]);
- text: <code>gaussianElimination([[2,3],[2,1]] , [8,4])</code> should return <code>[ 1, 2 ]</code>.
testString: assert.deepEqual(gaussianElimination([[2,3],[2,1]] , [8,4]), [ 1, 2 ]);
- text: <code>gaussianElimination([[1,3],[5,-2]], [14,19])</code> should return <code>[ 5, 3 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,3],[5,-2]], [14,19]), [ 5, 3 ]);
- text: <code>gaussianElimination([[1,1],[5,-1]] , [10,14])</code> should return <code>[ 4, 6 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,1],[5,-1]] , [10,14]), [ 4, 6 ]);
- text: <code>gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23])</code> should return <code>[ 1, 1, 1 ]</code>.
testString: assert.deepEqual(gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23]), [ 1, 1, 1 ]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gaussianElimination(A,b) {
// Good luck!
}
```
</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,90 @@
---
title: General FizzBuzz
id: 5a23c84252665b21eecc7e78
challengeType: 5
isHidden: false
forumTopicId: 302273
---
## Description
<section id='description'>
Write a generalized version of <a href="https://rosettacode.org/wiki/FizzBuzz" target="_blank">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 indicates 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');
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)</code> should return a string.
testString: assert(typeof genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)=='string');
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)</code> should return <code>"Fizz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6), "Fizz");
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10)</code> should return <code>"Buzz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10), "Buzz");
- text: <code>genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12)</code> should return <code>"Buzz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12), "Buzz");
- text: <code>genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13)</code> should return <code>"13"</code>.
testString: assert.equal(genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13), '13');
- text: <code>genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15)</code> should return <code>"BuzzFizz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15), "BuzzFizz");
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15)</code> should return <code>"FizzBuzz"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15), "FizzBuzz");
- text: <code>genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105)</code> should return <code>"FizzBuzzBaxx"</code>.
testString: assert.equal(genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105), "FizzBuzzBaxx");
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function genFizzBuzz(rules, num) {
// Good luck!
}
```
</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,99 @@
---
title: Generate lower case ASCII alphabet
id: 5a23c84252665b21eecc7e7a
challengeType: 5
isHidden: false
forumTopicId: 302274
---
## Description
<section id='description'>
Write a function to generate an array of lower case ASCII characters for a given range. For example, given the range <code>['a', 'd']</code>, 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');
- text: <code>lascii("a","d")</code> should return an array.
testString: assert(Array.isArray(lascii('a','d')));
- text: "<code>lascii('a','d')</code> should return <code>[ 'a', 'b', 'c', 'd' ]</code>."
testString: assert.deepEqual(lascii("a","d"),results[0]);
- text: <code>lascii('c','i')</code> should return <code>[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]</code>.
testString: assert.deepEqual(lascii("c","i"),results[1]);
- text: <code>lascii('m','q')</code> should return <code>[ 'm', 'n', 'o', 'p', 'q' ]</code>.
testString: assert.deepEqual(lascii("m","q"),results[2]);
- text: <code>lascii('k','n')</code> should return <code>[ 'k', 'l', 'm', 'n' ]</code>.
testString: assert.deepEqual(lascii("k","n"),results[3]);
- text: <code>lascii('t','z')</code> should return <code>[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]</code>.
testString: assert.deepEqual(lascii("t","z"),results[4]);
```
</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
let results=[
[ 'a', 'b', 'c', 'd' ],
[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ],
[ 'm', 'n', 'o', 'p', 'q' ],
[ 'k', 'l', 'm', 'n' ],
[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]
]
```
</div>
</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,107 @@
---
title: Generator/Exponential
id: 5a23c84252665b21eecc7e7b
challengeType: 5
isHidden: false
forumTopicId: 302275
---
## 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.
</section>
## Instructions
<section id='instructions'>
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>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>exponentialGenerator</code> should be a function.
testString: assert(typeof exponentialGenerator=='function');
- text: <code>exponentialGenerator()</code> should return a number.
testString: assert(typeof exponentialGenerator(10)=='number');
- text: <code>exponentialGenerator(10)</code> should return <code>144</code>.
testString: assert.equal(exponentialGenerator(10),144);
- text: <code>exponentialGenerator(12)</code> should return <code>196</code>.
testString: assert.equal(exponentialGenerator(12),196);
- text: <code>exponentialGenerator(14)</code> should return <code>256</code>.
testString: assert.equal(exponentialGenerator(14),256);
- text: <code>exponentialGenerator(20)</code> should return <code>484</code>.
testString: assert.equal(exponentialGenerator(20),484);
- text: <code>exponentialGenerator(25)</code> should return <code>784</code>.
testString: assert.equal(exponentialGenerator(25),784);
```
</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,104 @@
---
title: Gray code
id: 5a23c84252665b21eecc7e80
challengeType: 5
isHidden: false
forumTopicId: 302276
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Gray code" target="_blank">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" target="_blank">Karnaugh maps</a> in order from left to right or top to bottom.
</section>
## Instructions
<section id='instructions'>
Create a function to encode a number to and decode a number from Gray code. The function should will have 2 parameters.
The first would be a boolean. The function should encode for true and decode for false. The second parameter would be the number to be encoded/decoded.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
<pre>
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
</pre>
Or:
<pre>
g = b xor (b logically right shifted 1 time)
</pre>
Decoding (MSB is bit 0, b is binary, g is Gray code):
<pre>
b[0] = g[0]<br>
for other bits:
b[i] = g[i] xor b[i-1]
</pre>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>gray</code> should be a function.
testString: assert(typeof gray=='function');
- text: <code>gray(true,177)</code> should return a number.
testString: assert(typeof gray(true,177)=='number');
- text: <code>gray(true,177)</code> should return <code>233</code>.
testString: assert.equal(gray(true,177),233);
- text: <code>gray(true,425)</code> should return <code>381</code>.
testString: assert.equal(gray(true,425),381);
- text: <code>gray(true,870)</code> should return <code>725</code>.
testString: assert.equal(gray(true,870),725);
- text: <code>gray(false,233)</code> should return <code>177</code>.
testString: assert.equal(gray(false,233),177);
- text: <code>gray(false,381)</code> should return <code>425</code>.
testString: assert.equal(gray(false,381),425);
- text: <code>gray(false,725)</code> should return <code>870</code>.
testString: assert.equal(gray(false,725),870);
```
</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,73 @@
---
title: Greatest common divisor
id: 5a23c84252665b21eecc7e82
challengeType: 5
isHidden: false
forumTopicId: 302277
---
## 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');
- text: <code>gcd(24,36)</code> should return a number.
testString: assert(typeof gcd(24,36)=='number');
- text: <code>gcd(24,36)</code> should return <code>12</code>.
testString: assert.equal(gcd(24,36),12);
- text: <code>gcd(30,48)</code> should return <code>6</code>.
testString: assert.equal(gcd(30,48),6);
- text: <code>gcd(10,15)</code> should return <code>5</code>.
testString: assert.equal(gcd(10,15),5);
- text: <code>gcd(100,25)</code> should return <code>25</code>.
testString: assert.equal(gcd(100,25),25);
- text: <code>gcd(13,250)</code> should return <code>1</code>.
testString: assert.equal(gcd(13,250),1);
- text: <code>gcd(1300,250)</code> should return <code>50</code>.
testString: assert.equal(gcd(1300,250),50);
```
</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,94 @@
---
title: Greatest subsequential sum
id: 5a23c84252665b21eecc7e84
challengeType: 5
isHidden: false
forumTopicId: 302278
---
## 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');
- text: <code>maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])</code> should return an array.
testString: assert(Array.isArray(maximumSubsequence([ 1, 2,-1, 3, 10, -10 ])));
- text: <code>maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])</code> should return <code>[ 1, 2, -1, 3, 10 ]</code>.
testString: assert.deepEqual(maximumSubsequence([1,2,-1,3,10,-10]), [ 1, 2, -1, 3, 10 ]);
- text: <code>maximumSubsequence([ 0, 8, 10, -2, -4, -1, -5, -3 ])</code> should return <code>[ 0, 8, 10 ]</code>.
testString: assert.deepEqual(maximumSubsequence([0, 8, 10, -2, -4, -1, -5, -3]), [ 0, 8, 10 ]);
- text: <code>maximumSubsequence([ 9, 9, -10, 1 ])</code> should return <code>[ 9, 9 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ 9, 9, -10, 1 ]), [ 9, 9 ]);
- text: <code>maximumSubsequence([ 7, 1, -5, -3, -8, 1 ]</code> should return <code>[ 7, 1 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ 7, 1, -5, -3, -8, 1 ]), [ 7, 1 ]);
- text: <code>maximumSubsequence([ -3, 6, -1, 4, -4, -6 ])</code> should return <code>[ 6, -1, 4 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ -3, 6, -1, 4, -4, -6 ]), [ 6, -1, 4 ]);
- text: <code>maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ])</code> should return <code>[ 3, 5, 6, -2, -1, 4 ]</code>.
testString: assert.deepEqual(maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ]), [ 3, 5, 6, -2, -1, 4 ]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function maximumSubsequence(population) {
// Good luck!
}
```
</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,117 @@
---
title: Hailstone sequence
id: 595608ff8bcd7a50bd490181
challengeType: 5
isHidden: false
forumTopicId: 302279
---
## Description
<section id='description'>
The Hailstone sequence of numbers can be generated from a starting positive integer, <code>n</code> by:
<ul>
<li>If <code>n</code> is <code>1</code> then the sequence ends</li>
<li>If <code>n</code> is <code>even</code> then the next <code>n</code> of the sequence <code>= n/2</code></li>
<li>If <code>n</code> is <code>odd</code> then the next <code>n</code> of the sequence <code>= (3 * n) + 1</code></li>
</ul>
The (unproven) <a href="https://en.wikipedia.org/wiki/Collatz conjecture" title="wp: Collatz conjecture" target="_blank">Collatz conjecture</a> is that the hailstone sequence for any starting number always terminates.
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.
</section>
## Instructions
<section id='instructions'>
<ol>
<li>Create a routine to generate the hailstone sequence for a number</li>
<li>Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with <code>27, 82, 41, 124</code> and ending with <code>8, 4, 2, 1</code></li>
<li>Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)</li>
</ol>
<strong>See also:</strong>
<ul>
<li><a href="https://xkcd.com/710" target="_blank">xkcd</a> (humourous).</li>
</ul>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hailstoneSequence</code> should be a function.
testString: assert(typeof hailstoneSequence === 'function');
- text: <code>hailstoneSequence()</code> should return <code>[[27,82,41,124,8,4,2,1], [351, 77031]]</code>
testString: assert.deepEqual(hailstoneSequence(), res);
```
</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
const res = [[27, 82, 41, 124, 8, 4, 2, 1], [351, 77031]];
```
</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,98 @@
---
title: Happy numbers
id: 594810f028c0303b75339ad1
challengeType: 5
isHidden: false
forumTopicId: 302280
---
## Description
<section id='description'>
A <a href="https://en.wikipedia.org/wiki/Happy_number" target="_blank">happy number</a> is defined by the following process:
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 <code>1</code> (where it will stay), or it loops endlessly in a cycle which does not include <code>1</code>. Those numbers for which this process ends in <code>1</code> are happy numbers, while those that do not end in <code>1</code> are unhappy numbers.
</section>
## Instructions
<section id='instructions'>
Implement a function that returns true if the number is happy, or false if not.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>happy</code> should be a function.
testString: assert(typeof happy === 'function');
- text: <code>happy(1)</code> should return a boolean.
testString: assert(typeof happy(1) === 'boolean');
- text: <code>happy(1)</code> should return true.
testString: assert(happy(1));
- text: <code>happy(2)</code> should return false.
testString: assert(!happy(2));
- text: <code>happy(7)</code> should return true.
testString: assert(happy(7));
- text: <code>happy(10)</code> should return true.
testString: assert(happy(10));
- text: <code>happy(13)</code> should return true.
testString: assert(happy(13));
- text: <code>happy(19)</code> should return true.
testString: assert(happy(19));
- text: <code>happy(23)</code> should return true.
testString: assert(happy(23));
- text: <code>happy(28)</code> should return true.
testString: assert(happy(28));
- text: <code>happy(31)</code> should return true.
testString: assert(happy(31));
- text: <code>happy(32)</code> should return true:.
testString: assert(happy(32));
- text: <code>happy(33)</code> should return false.
testString: assert(!happy(33));
```
</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,111 @@
---
title: Harshad or Niven series
id: 595668ca4cfe1af2fb9818d4
challengeType: 5
isHidden: false
forumTopicId: 302281
---
## Description
<section id='description'>
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, <code>42</code> is a <a href="https://rosettacode.org/wiki/Harshad_or_Niven_series" title="Harshad or Niven series" target="_blank">Harshad number</a> as <code>42</code> is divisible by <code>(4 + 2)</code> without remainder.
Assume that the series is defined as the numbers in increasing order.
</section>
## Instructions
<section id='instructions'>
Implement a function to generate successive members of the Harshad sequence.
Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isHarshadOrNiven</code> should be a function.
testString: assert(typeof isHarshadOrNiven === 'function');
- text: '<code>isHarshadOrNiven()</code> should return <code>{"firstTwenty": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],"firstOver1000": 1002}</code>'
testString: assert.deepEqual(isHarshadOrNiven(), res);
```
</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
const res = {
firstTwenty: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],
firstOver1000: 1002
};
```
</div>
</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,102 @@
---
title: Hash from two arrays
id: 595671d4d2cdc305f0d5b36f
challengeType: 5
isHidden: false
forumTopicId: 302283
---
## Description
<section id='description'>
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).
<strong>Related task:</strong>
<ul>
<li><a href="https://rosettacode.org/wiki/Associative arrays/Creation" title="Associative arrays/Creation" target="_blank">Associative arrays/Creation</a></li>
</ul>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>arrToObj</code> should be a function.
testString: assert(typeof arrToObj === 'function');
- text: '<code>arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }</code>'
testString: assert.deepEqual(arrToObj(...testCases[0]), res[0]);
- text: '<code>arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"])</code> should return <code>{ 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }</code>'
testString: assert.deepEqual(arrToObj(...testCases[1]), res[1]);
- text: '<code>arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"])</code> should return <code>{ 1: "a", 2: "b", 3: "c" }</code>'
testString: assert.deepEqual(arrToObj(...testCases[2]), res[2]);
- text: '<code>arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }</code>'
testString: assert.deepEqual(arrToObj(...testCases[3]), res[3]);
- text: '<code>arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4])</code> should return <code>{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }</code>'
testString: assert.deepEqual(arrToObj(...testCases[4]), res[4]);
- text: '<code>arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])</code> should return <code>{ "a": 1, "b": 2, "c": 3 }</code>'
testString: assert.deepEqual(arrToObj(...testCases[5]), res[5]);
```
</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
const testCases = [
[[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd', 'e']],
[[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd']],
[[1, 2, 3], ['a', 'b', 'c', 'd', 'e']],
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]],
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4]],
[['a', 'b', 'c'], [1, 2, 3, 4, 5]]
];
const res = [
{ 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e' },
{ 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: undefined },
{ 1: 'a', 2: 'b', 3: 'c' },
{ a: 1, b: 2, c: 3, d: 4, e: 5 },
{ a: 1, b: 2, c: 3, d: 4, e: undefined },
{ a: 1, b: 2, c: 3 }
];
```
</div>
</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,253 @@
---
title: Hash join
id: 5956795bc9e2c415eb244de1
challengeType: 5
isHidden: false
forumTopicId: 302284
---
## Description
<section id='description'>
An <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join" title="wp: Join_(SQL)#Inner_join" target="_blank">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" target="_blank">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" target="_blank">hash join</a> algorithm.
The "hash join" algorithm consists of two steps:
<ol>
<li><strong>Hash phase:</strong> Create a <a href="https://en.wikipedia.org/wiki/Multimap" title="wp: Multimap" target="_blank">multimap</a> from one of the two tables, mapping from each join column value to all the rows that contain it.</li>
<ul>
<li>The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.</li>
<li>Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.</li>
</ul>
<li><strong>Join phase:</strong> Scan the other table, and find matching rows by looking in the multimap created before.</li>
</ol>
In pseudo-code, the algorithm could be expressed as follows:
<pre>
<strong>let</strong> <i>A</i> = the first input table (or ideally, the larger one)
<strong>let</strong> <i>B</i> = the second input table (or ideally, the smaller one)
<strong>let</strong> <i>j<sub>A</sub></i> = the join column ID of table <i>A</i>
<strong>let</strong> <i>j<sub>B</sub></i> = the join column ID of table <i>B</i>
<strong>let</strong> <i>M<sub>B</sub></i> = a multimap for mapping from single values to multiple rows of table <i>B</i> (starts out empty)
<strong>let</strong> <i>C</i> = the output table (starts out empty)
<strong>for each</strong> row <i>b</i> in table <i>B</i>:
<strong>place</strong> <i>b</i> in multimap <i>M<sub>B</sub></i> under key <i>b(j<sub>B</sub>)</i>
<strong>for each</strong> row <i>a</i> in table <i>A</i>:
<strong>for each</strong> row <i>b</i> in multimap <i>M<sub>B</sub></i> under key <i>a(j<sub>A</sub>)</i>:
<strong>let</strong> <i>c</i> = the concatenation of row <i>a</i> and row <i>b</i>
<strong>place</strong> row <i>c</i> in table <i>C</i>
</pre>
</section>
## Instructions
<section id='instructions'>
Implement the "hash join" algorithm as a function and demonstrate that it passes the test-case listed below. The function should accept two arrays of objects and return an array of combined objects.
<h4><strong>Input</strong></h4>
<table>
<tr>
<td style="padding: 4px; margin: 5px;">
<table style="border:none; border-collapse:collapse;">
<tr>
<td style="border:none"><i>A =</i></td>
<td style="border:none">
<table>
<tr>
<th style="padding: 4px; margin: 5px;">Age</th>
<th style="padding: 4px; margin: 5px;">Name</th>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">27</td>
<td style="padding: 4px; margin: 5px;">Jonah</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">18</td>
<td style="padding: 4px; margin: 5px;">Alan</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">28</td>
<td style="padding: 4px; margin: 5px;">Glory</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">18</td>
<td style="padding: 4px; margin: 5px;">Popeye</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">28</td>
<td style="padding: 4px; margin: 5px;">Alan</td>
</tr>
</table>
</td>
<td style="border:none; padding-left:1.5em;" rowspan="2"></td>
<td style="border:none"><i>B =</i></td>
<td style="border:none">
<table>
<tr>
<th style="padding: 4px; margin: 5px;">Character</th>
<th style="padding: 4px; margin: 5px;">Nemesis</th>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">Jonah</td>
<td style="padding: 4px; margin: 5px;">Whales</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">Jonah</td>
<td style="padding: 4px; margin: 5px;">Spiders</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">Alan</td>
<td style="padding: 4px; margin: 5px;">Ghosts</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">Alan</td>
<td style="padding: 4px; margin: 5px;">Zombies</td>
</tr>
<tr>
<td style="padding: 4px; margin: 5px;">Glory</td>
<td style="padding: 4px; margin: 5px;">Buffy</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="border:none">
<i>j<sub>A</sub> =</i>
</td>
<td style="border:none">
<i><code>Name</code> (i.e. column 1)</i>
</td>
<td style="border:none">
<i>j<sub>B</sub> =</i>
</td>
<td style="border:none">
<i><code>Character</code> (i.e. column 0)</i>
</td>
</tr>
</table>
</td>
</tr>
</table>
<h4><strong>Output</strong></h4>
|A_age|A_name|B_character|B_nemesis|
|--- |--- |--- |--- |
|27|Jonah|Jonah|Whales|
|27|Jonah|Jonah|Spiders|
|18|Alan|Alan|Ghosts|
|18|Alan|Alan|Zombies|
|28|Glory|Glory|Buffy|
|28|Alan|Alan|Ghosts|
|28|Alan|Alan|Zombies|
The order of the rows in the output table is not significant.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hashJoin</code> should be a function.
testString: assert(typeof hashJoin === 'function');
- text: '<code>hashJoin([{ age: 27, name: "Jonah" }, { age: 18, name: "Alan" }, { age: 28, name: "Glory" }, { age: 18, name: "Popeye" }, { age: 28, name: "Alan" }], [{ character: "Jonah", nemesis: "Whales" }, { character: "Jonah", nemesis: "Spiders" }, { character: "Alan", nemesis: "Ghosts" }, { character:"Alan", nemesis: "Zombies" }, { character: "Glory", nemesis: "Buffy" }, { character: "Bob", nemesis: "foo" }])</code> should return <code>[{"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Whales"}, {"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Spiders"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}, {"A_age": 28,"A_name": "Glory", "B_character": "Glory", "B_nemesis": "Buffy"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}]</code>'
testString: assert.deepEqual(hashJoin(hash1, hash2), res);
```
</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
const hash1 = [
{ age: 27, name: 'Jonah' },
{ age: 18, name: 'Alan' },
{ age: 28, name: 'Glory' },
{ age: 18, name: 'Popeye' },
{ age: 28, name: 'Alan' }
];
const hash2 = [
{ character: 'Jonah', nemesis: 'Whales' },
{ character: 'Jonah', nemesis: 'Spiders' },
{ character: 'Alan', nemesis: 'Ghosts' },
{ character: 'Alan', nemesis: 'Zombies' },
{ character: 'Glory', nemesis: 'Buffy' },
{ character: 'Bob', nemesis: 'foo' }
];
const res = [
{ A_age: 27, A_name: 'Jonah', B_character: 'Jonah', B_nemesis: 'Whales' },
{ A_age: 27, A_name: 'Jonah', B_character: 'Jonah', B_nemesis: 'Spiders' },
{ A_age: 18, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Ghosts' },
{ A_age: 18, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Zombies' },
{ A_age: 28, A_name: 'Glory', B_character: 'Glory', B_nemesis: 'Buffy' },
{ A_age: 28, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Ghosts' },
{ A_age: 28, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Zombies' }
];
const bench1 = [{ name: 'u2v7v', num: 1 }, { name: 'n53c8', num: 10 }, { name: 'oysce', num: 9 }, { name: '0mto2s', num: 1 }, { name: 'vkh5id', num: 4 }, { name: '5od0cf', num: 8 }, { name: 'uuulue', num: 10 }, { name: '3rgsbi', num: 9 }, { name: 'kccv35r', num: 4 }, { name: '80un74', num: 9 }, { name: 'h4pp3', num: 6 }, { name: '51bit', num: 7 }, { name: 'j9ndf', num: 8 }, { name: 'vf3u1', num: 10 }, { name: 'g0bw0om', num: 10 }, { name: 'j031x', num: 7 }, { name: 'ij3asc', num: 9 }, { name: 'byv83y', num: 8 }, { name: 'bjzp4k', num: 4 }, { name: 'f3kbnm', num: 10 }];
const bench2 = [{ friend: 'o8b', num: 8 }, { friend: 'ye', num: 2 }, { friend: '32i', num: 5 }, { friend: 'uz', num: 3 }, { friend: 'a5k', num: 4 }, { friend: 'uad', num: 7 }, { friend: '3w5', num: 10 }, { friend: 'vw', num: 10 }, { friend: 'ah', num: 4 }, { friend: 'qv', num: 7 }, { friend: 'ozv', num: 2 }, { friend: '9ri', num: 10 }, { friend: '7nu', num: 4 }, { friend: 'w3', num: 9 }, { friend: 'tgp', num: 8 }, { friend: 'ibs', num: 1 }, { friend: 'ss7', num: 6 }, { friend: 'g44', num: 9 }, { friend: 'tab', num: 9 }, { friend: 'zem', num: 10 }];
```
</div>
</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,152 @@
---
title: Heronian triangles
id: 595b98f8b5a2245e243aa831
challengeType: 5
isHidden: false
forumTopicId: 302285
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Heron's formula" title="wp: Heron's formula" target="_blank">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:
<span style="margin-left: 2em;"><big>$A = \sqrt{s(s-a)(s-b)(s-c)},$</big></span>
where <big>s</big> is half the perimeter of the triangle; that is,
<span style="margin-left: 2em;"><big>$s=\frac{a+b+c}{2}.$</big></span>
Heronian triangles are triangles whose sides and area are all integers.
An example is the triangle with sides <code>3, 4, 5</code> whose area is <code>6</code> (and whose perimeter is <code>12</code>).
Note that any triangle whose sides are all an integer multiple of <code>3, 4, 5</code>; such as <code>6, 8, 10,</code> will also be a Heronian triangle.
Define a Primitive Heronian triangle as a Heronian triangle where the greatest common divisor
of all three sides is <code>1</code> (unity).
This will exclude, for example, triangle <code>6, 8, 10.</code>
</section>
## Instructions
<section id='instructions'>
Implement a function based on Hero's formula that returns the first <code>n<sub>th</sub></code> ordered triangles in an array of arrays.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>heronianTriangle</code> should be a function.
testString: assert(typeof heronianTriangle === 'function');
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]</code>
testString: assert.deepEqual(heronianTriangle(testCases[0]), res[0]);
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],</code>
testString: assert.deepEqual(heronianTriangle(testCases[1]), res[1]);
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],</code>
testString: assert.deepEqual(heronianTriangle(testCases[2]), res[2]);
- text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]</code>
testString: assert.deepEqual(heronianTriangle(testCases[3]), res[3]);
```
</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
const testCases = [10, 15, 20, 25];
const res = [
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]],
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37], [16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]
];
```
</div>
</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,136 @@
---
title: Hofstadter Figure-Figure sequences
id: 59622f89e4e137560018a40e
challengeType: 5
isHidden: false
forumTopicId: 302286
---
## Description
<section id='description'>
These two sequences of positive integers are defined as:
<span style="margin-left: 2em;"><big>$R(1)=1\ ;\ S(1)=2 \\R(n)=R(n-1)+S(n-1), \quad n>1.$</big></span>
The sequence <big>$S(n)$</big> is further defined as the sequence of positive integers not present in <big>$R(n)$</big>.
Sequence <big>$R$</big> starts:
<pre>1, 3, 7, 12, 18, ...</pre>
Sequence <big>$S$</big> starts:
<pre>2, 4, 5, 6, 8, ...</pre>
</section>
## Instructions
<section id='instructions'>
Create two functions named <code>ffr</code> and <code>ffs</code> that when given <code>n</code> return <code>R(n)</code> or <code>S(n)</code> respectively. (Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
No maximum value for <code>n</code> should be assumed.
<strong>References</strong>
<ul>
<li>
Sloane's <a href="https://oeis.org/A005228" target="_blank">A005228</a> and <a href="https://oeis.org/A030124" target="_blank">A030124</a>.
</li>
<li>
Wikipedia: <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences" title="wp: Hofstadter_sequence#Hofstadter_Figure-Figure_sequences" target="_blank">Hofstadter Figure-Figure sequences</a>.
</li>
</ul>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>ffr</code> should be a function.
testString: assert(typeof ffr === 'function');
- text: <code>ffs</code> should be a function.
testString: assert(typeof ffs === 'function');
- text: <code>ffr</code> should return integer.
testString: assert(Number.isInteger(ffr(1)));
- text: <code>ffs</code> should return integer.
testString: assert(Number.isInteger(ffs(1)));
- text: <code>ffr()</code> should return <code>69</code>
testString: assert.equal(ffr(ffrParamRes[0][0]), ffrParamRes[0][1]);
- text: <code>ffr()</code> should return <code>1509</code>
testString: assert.equal(ffr(ffrParamRes[1][0]), ffrParamRes[1][1]);
- text: <code>ffr()</code> should return <code>5764</code>
testString: assert.equal(ffr(ffrParamRes[2][0]), ffrParamRes[2][1]);
- text: <code>ffr()</code> should return <code>526334</code>
testString: assert.equal(ffr(ffrParamRes[3][0]), ffrParamRes[3][1]);
- text: <code>ffs()</code> should return <code>14</code>
testString: assert.equal(ffs(ffsParamRes[0][0]), ffsParamRes[0][1]);
- text: <code>ffs()</code> should return <code>59</code>
testString: assert.equal(ffs(ffsParamRes[1][0]), ffsParamRes[1][1]);
- text: <code>ffs()</code> should return <code>112</code>
testString: assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1]);
- text: <code>ffs()</code> should return <code>1041</code>
testString: assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1]);
```
</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
const ffrParamRes = [[10, 69], [50, 1509], [100, 5764], [1000, 526334]];
const ffsParamRes = [[10, 14], [50, 59], [100, 112], [1000, 1041]];
```
</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,90 @@
---
title: Hofstadter Q sequence
id: 59637c4d89f6786115efd814
challengeType: 5
isHidden: false
forumTopicId: 302287
---
## Description
<section id='description'>
The <a href="https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence" title="wp: Hofstadter_sequence#Hofstadter_Q_sequence" target="_blank">Hofstadter Q sequence</a> is defined as:
<span style="left-margin: 2em;">$Q(1)=Q(2)=1, \\ Q(n)=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)), \quad n>2.$</span>
It is defined like the <a href="https://rosettacode.org/wiki/Fibonacci sequence" title="Fibonacci sequence" target="_blank">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.
</section>
## Instructions
<section id='instructions'>
Implement the Hofstadter Q Sequence equation as a function. The function should accept number, <code>n</code>, and return an integer.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hofstadterQ</code> should be a function.
testString: assert(typeof hofstadterQ === 'function');
- text: <code>hofstadterQ()</code> should return <code>integer</code>
testString: assert(Number.isInteger(hofstadterQ(1000)));
- text: <code>hofstadterQ(1000)</code> should return <code>502</code>
testString: assert.equal(hofstadterQ(testCase[0]), res[0]);
- text: <code>hofstadterQ(1500)</code> should return <code>755</code>
testString: assert.equal(hofstadterQ(testCase[1]), res[1]);
- text: <code>hofstadterQ(2000)</code> should return <code>1005</code>
testString: assert.equal(hofstadterQ(testCase[2]), res[2]);
- text: <code>hofstadterQ(2500)</code> should return <code>1261</code>
testString: assert.equal(hofstadterQ(testCase[3]), res[3]);
```
</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
const testCase = [1000, 1500, 2000, 2500];
const res = [502, 755, 1005, 1261];
```
</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,88 @@
---
title: I before E except after C
id: 5a23c84252665b21eecc7eb0
challengeType: 5
isHidden: false
forumTopicId: 302288
---
## Description
<section id='description'>
The phrase <a href="https://en.wikipedia.org/wiki/I before E except after C" target="_blank"> "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>
<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.
</section>
## Instructions
<section id='instructions'>
Write a function that accepts a word and check if the word follows this rule. The function should return true if the word follows the rule and false if it does not.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>IBeforeExceptC</code> should be a function.
testString: assert(typeof IBeforeExceptC=='function');
- text: <code>IBeforeExceptC("receive")</code> should return a boolean.
testString: assert(typeof IBeforeExceptC("receive")=='boolean');
- text: <code>IBeforeExceptC("receive")</code> should return <code>true</code>.
testString: assert.equal(IBeforeExceptC("receive"),true);
- text: <code>IBeforeExceptC("science")</code> should return <code>false</code>.
testString: assert.equal(IBeforeExceptC("science"),false);
- text: <code>IBeforeExceptC("imperceivable")</code> should return <code>true</code>.
testString: assert.equal(IBeforeExceptC("imperceivable"),true);
- text: <code>IBeforeExceptC("inconceivable")</code> should return <code>true</code>.
testString: assert.equal(IBeforeExceptC("inconceivable"),true);
- text: <code>IBeforeExceptC("insufficient")</code> should return <code>false</code>.
testString: assert.equal(IBeforeExceptC("insufficient"),false);
- text: <code>IBeforeExceptC("omniscient")</code> should return <code>false</code>.
testString: assert.equal(IBeforeExceptC("omniscient"),false);
```
</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,93 @@
---
title: IBAN
id: 5a23c84252665b21eecc7eaf
challengeType: 5
isHidden: false
forumTopicId: 302289
---
## Description
<section id='description'>
The <a href="https://en.wikipedia.org/wiki/International_Bank_Account_Number" target="_blank">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" target="_blank">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.
</section>
## Instructions
<section id='instructions'>
Write a function that takes IBAN string as parameter. If it is valid return true. Otherwise, return false.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isValid</code> should be a function.
testString: assert(typeof isValid=='function');
- text: <code>isValid("GB82 WEST 1234 5698 7654 32")</code> should return a boolean.
testString: assert(typeof isValid('GB82 WEST 1234 5698 7654 32')=='boolean');
- text: <code>isValid("GB82 WEST 1234 5698 7654 32")</code> should return <code>true</code>.
testString: assert.equal(isValid('GB82 WEST 1234 5698 7654 32'),true);
- text: <code>isValid("GB82 WEST 1.34 5698 7654 32")</code> should return <code>false</code>.
testString: assert.equal(isValid('GB82 WEST 1.34 5698 7654 32'),false);
- text: <code>isValid("GB82 WEST 1234 5698 7654 325")</code> should return <code>false</code>.
testString: assert.equal(isValid('GB82 WEST 1234 5698 7654 325'),false);
- text: <code>isValid("GB82 TEST 1234 5698 7654 32")</code> should return <code>false</code>.
testString: assert.equal(isValid('GB82 TEST 1234 5698 7654 32'),false);
- text: <code>isValid("SA03 8000 0000 6080 1016 7519")</code> should return <code>true</code>.
testString: assert.equal(isValid('SA03 8000 0000 6080 1016 7519'),true);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isValid(iban) {
// Good luck!
}
```
</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,87 @@
---
title: Identity matrix
id: 5a23c84252665b21eecc7eb1
challengeType: 5
isHidden: false
forumTopicId: 302290
---
## Description
<section id='description'>
An <i>identity matrix</i> is a square matrix of size \( n \times n \), where the diagonal elements are all <code>1</code>s (ones), and all the other elements are all <code>0</code>s (zeroes).
<ul>
<li style="list-style: none;">\(\displaystyle I_{n}=\begin{bmatrix} 1 & 0 & 0 \cr 0 & 1 & 0 \cr 0 & 0 & 1 \cr \end{bmatrix}\)</li>
</ul>
</section>
## Instructions
<section id='instructions'>
Write a function that takes a number <code>n</code> as a parameter and returns the identity matrix of order \( n \times n \).
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>idMatrix</code> should be a function.
testString: assert(typeof idMatrix=='function');
- text: <code>idMatrix(1)</code> should return an array.
testString: assert(Array.isArray(idMatrix(1)));
- text: <code>idMatrix(1)</code> should return <code>[ [ 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(1),results[0]);
- text: <code>idMatrix(2)</code> should return <code>[ [ 1, 0 ], [ 0, 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(2),results[1]);
- text: <code>idMatrix(3)</code> should return <code>[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(3),results[2]);
- text: <code>idMatrix(4)</code> should return <code>[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]</code>.
testString: assert.deepEqual(idMatrix(4),results[3]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function idMatrix(n) {
// Good luck!
}
```
</div>
### After Test
<div id='js-teardown'>
```js
let results=[[ [ 1 ] ],
[ [ 1, 0 ], [ 0, 1 ] ],
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ],
[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]]
```
</div>
</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,86 @@
---
title: Iterated digits squaring
id: 5a23c84252665b21eecc7ec1
challengeType: 5
isHidden: false
forumTopicId: 302291
---
## 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>
</section>
## Instructions
<section id='instructions'>
Write a function that takes a number as a parameter and returns 1 or 89 after performing the mentioned process.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>iteratedSquare</code> should be a function.
testString: assert(typeof iteratedSquare=='function');
- text: <code>iteratedSquare(4)</code> should return a number.
testString: assert(typeof iteratedSquare(4)=='number');
- text: <code>iteratedSquare(4)</code> should return <code>89</code>.
testString: assert.equal(iteratedSquare(4),89);
- text: <code>iteratedSquare(7)</code> should return <code>1</code>.
testString: assert.equal(iteratedSquare(7),1);
- text: <code>iteratedSquare(15)</code> should return <code>89</code>.
testString: assert.equal(iteratedSquare(15),89);
- text: <code>iteratedSquare(20)</code> should return <code>89</code>.
testString: assert.equal(iteratedSquare(20),89);
- text: <code>iteratedSquare(70)</code> should return <code>1</code>.
testString: assert.equal(iteratedSquare(70),1);
- text: <code>iteratedSquare(100)</code> should return <code>1</code>.
testString: assert.equal(iteratedSquare(100),1);
```
</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,127 @@
---
title: Jaro distance
id: 5a23c84252665b21eecc7ec2
challengeType: 5
isHidden: false
forumTopicId: 302292
---
## 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 <code>0</code> equates to no similarity and <code>1</code> is an exact match.
<strong>Definition</strong>
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>.
<strong>Example</strong>
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\).
</section>
## Instructions
<section id='instructions'>
Write a function a that takes two strings as parameters and returns the associated Jaro distance.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>jaro</code> should be a function.
testString: assert(typeof jaro=='function');
- text: <code>jaro("MARTHA", "MARHTA")</code> should return a number.
testString: assert(typeof jaro('MARTHA', 'MARHTA')=='number');
- text: <code>jaro("MARTHA", "MARHTA")</code> should return <code>0.9444444444444445</code>.
testString: assert.equal(jaro('MARTHA', 'MARHTA'), 0.9444444444444445);
- text: <code>jaro("DIXON", "DICKSONX")</code> should return <code>0.7666666666666666</code>.
testString: assert.equal(jaro('DIXON', 'DICKSONX'), 0.7666666666666666);
- text: <code>jaro("JELLYFISH", "SMELLYFISH")</code> should return <code>0.8962962962962964</code>.
testString: assert.equal(jaro('JELLYFISH', 'SMELLYFISH'), 0.8962962962962964);
- text: <code>jaro("HELLOS", "CHELLO")</code> should return <code>0.888888888888889</code>.
testString: assert.equal(jaro('HELLOS', 'CHELLO'), 0.888888888888889);
- text: <code>jaro("ABCD", "BCDA")</code> should return <code>0.8333333333333334</code>.
testString: assert.equal(jaro('ABCD', 'BCDA'), 0.8333333333333334);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function jaro(s, t) {
// Good luck!
}
```
</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,81 @@
---
title: JortSort
id: 5a23c84252665b21eecc7ec4
challengeType: 5
isHidden: false
forumTopicId: 302293
---
## 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" target="_blank">JSConf</a>.
jortSort should be 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');
- text: <code>jortsort([1,2,3,4,5])</code> should return a boolean.
testString: assert(typeof jortsort([1,2,3,4,5])=='boolean');
- text: <code>jortsort([1,2,3,4,5])</code> should return <code>true</code>.
testString: assert.equal(jortsort([1,2,3,4,5]),true);
- text: <code>jortsort([1,2,13,4,5])</code> should return <code>false</code>.
testString: assert.equal(jortsort([1,2,13,4,5]),false);
- text: <code>jortsort([12,4,51,2,4])</code> should return <code>false</code>.
testString: assert.equal(jortsort([12,4,51,2,4]),false);
- text: <code>jortsort([1,2])</code> should return <code>true</code>.
testString: assert.equal(jortsort([1,2]),true);
- text: <code>jortsort([5,4,3,2,1])</code> should return <code>false</code>.
testString: assert.equal(jortsort([5,4,3,2,1]),false);
- text: <code>jortsort([1,1,1,1,1])</code> should return <code>true</code>.
testString: assert.equal(jortsort([1,1,1,1,1]),true);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function jortsort(array) {
// Good luck!
}
```
</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,109 @@
---
title: Josephus problem
id: 5a23c84252665b21eecc7ec5
challengeType: 5
isHidden: false
forumTopicId: 302294
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Josephus problem" target="_blank">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?
</section>
## Instructions
<section id='instructions'>
Write a function that takes the initial number of prisoners and 'k' as parameter and returns the number of the prisoner that survives.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>josephus</code> should be a function.
testString: assert(typeof josephus=='function');
- text: <code>josephus(30,3)</code> should return a number.
testString: assert(typeof josephus(30,3)=='number');
- text: <code>josephus(30,3)</code> should return <code>29</code>.
testString: assert.equal(josephus(30,3),29);
- text: <code>josephus(30,5)</code> should return <code>3</code>.
testString: assert.equal(josephus(30,5),3);
- text: <code>josephus(20,2)</code> should return <code>9</code>.
testString: assert.equal(josephus(20,2),9);
- text: <code>josephus(17,6)</code> should return <code>2</code>.
testString: assert.equal(josephus(17,6),2);
- text: <code>josephus(29,4)</code> should return <code>2</code>.
testString: assert.equal(josephus(29,4),2);
```
</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,373 @@
---
id: 5a23c84252665b21eecc7ecb
title: K-d tree
challengeType: 5
isHidden: false
forumTopicId: 302295
---
## Description
<section id='description'>
A k-d tree (short for <i>k</i>-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space.
k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches).
k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is <i>k</i>, the number of points in the data, <i>N</i>, should be <i>N</i>2<sup><i>k</i></sup>.
Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.
</section>
## Instructions
<section id='instructions'>
Write a function to perform a nearest neighbour search using k-d tree. The function takes two parameters: an array of k-dimensional points, and a single k-dimensional point whose nearest neighbour should be returned by the function. A k-dimensional point will be given as an array of k elements.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>kdNN</code> should be a function.
testString: assert(typeof kdNN == 'function');
- text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])</code> should return an array.
testString: assert(Array.isArray(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])));
- text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])</code> should return <code>[ 8, 1 ]</code>.
testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2]), [8, 1]);
- text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1])</code> should return <code>[ 8, 1 ]</code>.
testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1]), [8, 1]);
- text: <code>kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2])</code> should return <code>[ 2, 3 ]</code>.
testString: assert.deepEqual(kdNN([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2]), [2, 3]);
- text: <code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3])</code> should return <code>[ 1, 2, 5 ]</code>.
testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3]), [1, 2, 5]);
- text: <code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6])</code> should return <code>[ 4, 6, 7 ]</code>.
testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6]), [4, 6, 7]);
- text: <code>kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8])</code> should return <code>[ 7, 8, 9 ]</code>.
testString: assert.deepEqual(kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8]), [7, 8, 9]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function kdNN(fpoints, fpoint) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function kdNN(fpoints, fpoint) {
function Node(obj, dimension, parent) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.dimension = dimension;
}
function kdTree(points, metric, dimensions) {
var self = this;
function buildTree(points, depth, parent) {
var dim = depth % dimensions.length,
median,
node;
if (points.length === 0) {
return null;
}
if (points.length === 1) {
return new Node(points[0], dim, parent);
}
points.sort(function(a, b) {
return a[dimensions[dim]] - b[dimensions[dim]];
});
median = Math.floor(points.length / 2);
node = new Node(points[median], dim, parent);
node.left = buildTree(points.slice(0, median), depth + 1, node);
node.right = buildTree(points.slice(median + 1), depth + 1, node);
return node;
}
this.root = buildTree(points, 0, null);
this.insert = function(point) {
function innerSearch(node, parent) {
if (node === null) {
return parent;
}
var dimension = dimensions[node.dimension];
if (point[dimension] < node.obj[dimension]) {
return innerSearch(node.left, node);
} else {
return innerSearch(node.right, node);
}
}
var insertPosition = innerSearch(this.root, null),
newNode,
dimension;
if (insertPosition === null) {
this.root = new Node(point, 0, null);
return;
}
newNode = new Node(
point,
(insertPosition.dimension + 1) % dimensions.length,
insertPosition
);
dimension = dimensions[insertPosition.dimension];
if (point[dimension] < insertPosition.obj[dimension]) {
insertPosition.left = newNode;
} else {
insertPosition.right = newNode;
}
};
this.nearest = function(point, maxNodes, maxDistance) {
var i, result, bestNodes;
bestNodes = new BinaryHeap(function(e) {
return -e[1];
});
function nearestSearch(node) {
var bestChild,
dimension = dimensions[node.dimension],
ownDistance = metric(point, node.obj),
linearPoint = {},
linearDistance,
otherChild,
i;
function saveNode(node, distance) {
bestNodes.push([node, distance]);
if (bestNodes.size() > maxNodes) {
bestNodes.pop();
}
}
for (i = 0; i < dimensions.length; i += 1) {
if (i === node.dimension) {
linearPoint[dimensions[i]] = point[dimensions[i]];
} else {
linearPoint[dimensions[i]] = node.obj[dimensions[i]];
}
}
linearDistance = metric(linearPoint, node.obj);
if (node.right === null && node.left === null) {
if (
bestNodes.size() < maxNodes ||
ownDistance < bestNodes.peek()[1]
) {
saveNode(node, ownDistance);
}
return;
}
if (node.right === null) {
bestChild = node.left;
} else if (node.left === null) {
bestChild = node.right;
} else {
if (point[dimension] < node.obj[dimension]) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
nearestSearch(bestChild);
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
if (
bestNodes.size() < maxNodes ||
Math.abs(linearDistance) < bestNodes.peek()[1]
) {
if (bestChild === node.left) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if (otherChild !== null) {
nearestSearch(otherChild);
}
}
}
if (maxDistance) {
for (i = 0; i < maxNodes; i += 1) {
bestNodes.push([null, maxDistance]);
}
}
if (self.root) nearestSearch(self.root);
result = [];
for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {
if (bestNodes.content[i][0]) {
result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);
}
}
return result;
};
}
function BinaryHeap(scoreFunction) {
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to bubble up.
this.bubbleUp(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it sink down.
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
},
peek: function() {
return this.content[0];
},
size: function() {
return this.content.length;
},
bubbleUp: function(n) {
// Fetch the element that has to be moved.
var element = this.content[n];
// When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to move it further.
else {
break;
}
}
},
sinkDown: function(n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while (true) {
// Compute the indices of the child elements.
var child2N = (n + 1) * 2,
child1N = child2N - 1;
// This is used to store the new position of the element,
// if any.
var swap = null;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N],
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore) swap = child1N;
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score)) {
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap != null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
var dims = [];
for (var i = 0; i < fpoint.length; i++) dims.push(i);
var tree = new kdTree(
fpoints,
function(e1, e2) {
var d = 0;
var e3 = e1;
if (!Array.isArray(e1)) {
e3 = [];
for (var key in e1) e3.push(e1[key]);
e1 = e3;
}
e1.forEach(function(e, i) {
var sqd = e1[i] - e2[i];
d += sqd * sqd;
});
return d;
},
dims
);
return tree.nearest(fpoint, 1, 1000)[0][0];
}
```
</section>

View File

@ -0,0 +1,90 @@
---
id: 5a23c84252665b21eecc7eca
title: Kaprekar numbers
challengeType: 5
isHidden: false
forumTopicId: 302296
---
## Description
<section id='description'>
A positive integer is a <a href="https://en.wikipedia.org/wiki/Kaprekar number">Kaprekar number</a> if:
<ul>
<li>It is 1, or,</li>
<li>The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. </li>
</ul>
Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.Example
Kaprekar numbers:
<ul>
<li><code>2223</code> is a Kaprekar number, as <code>2223 * 2223 = 4941729</code>, <code>4941729</code> may be split to <code>494</code> and <code>1729</code>, and <code>494 + 1729 = 2223</code></li>
<li>The series of Kaprekar numbers is known as <a href="https://oeis.org/A006886" target="_blank">A006886</a>, and begins as <code>1, 9, 45, 55, ...</code></li>
</ul>
</section>
## Instructions
<section id='instructions'>
Write a function that takes a number $n$, a base $bs$, and returns true if the number is a Kaprekar number for the given base. Otherwise, the function returns false.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isKaprekar</code> should be a function.
testString: assert(typeof isKaprekar == 'function');
- text: <code>isKaprekar(1, 10)</code> should return a boolean.
testString: assert(typeof isKaprekar(1, 10) == 'boolean');
- text: <code>isKaprekar(1, 10)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(1, 10), true);
- text: <code>isKaprekar(9, 10)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(9, 10), true);
- text: <code>isKaprekar(2223, 10)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(2223, 10), true);
- text: <code>isKaprekar(22823, 10)</code> should return <code>false</code>.
testString: assert.equal(isKaprekar(22823, 10), false);
- text: <code>isKaprekar(9, 17)</code> should return <code>false</code>.
testString: assert.equal(isKaprekar(9, 17), false);
- text: <code>isKaprekar(225, 17)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(225, 17), true);
- text: <code>isKaprekar(999, 17)</code> should return <code>false</code>.
testString: assert.equal(isKaprekar(999, 17), false);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isKaprekar(n, bs) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function isKaprekar(n, bs) {
if (n < 1) return false;
if (n == 1) return true;
for (var a = n * n, b = 0, s = 1; a; s *= bs) {
b += (a % bs) * s;
a = Math.floor(a / bs);
if (b && a + b == n) return true;
}
return false;
}
```
</section>

View File

@ -0,0 +1,164 @@
---
id: 5a23c84252665b21eecc7ed1
title: Knapsack problem/0-1
challengeType: 5
isHidden: false
forumTopicId: 323649
---
## Description
<section id='description'>
The 0-1 knapsack problem is defined as follows:
You are given an array of objects representing items to be put in a knapsack. The objects have 3 attributes: name, weight, and value. The items need to be selected so that the total weight does not exceed the maximum weight and the value is maximized.
</section>
## Instructions
<section id='instructions'>
Write a function to solve the knapsack problem. The function is given the array of objects and the maximum weight as parameters. It should return the maximum total value possible.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100)</code> should return <code>405</code>.
testString: assert.equal(knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100), 405);
- text: <code>knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200)</code> should return <code>510</code>.
testString: assert.equal(knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200), 510);
- text: <code>knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100)</code> should return <code>145</code>.
testString: assert.equal(knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100), 145);
- text: <code>knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200)</code> should return <code>185</code>.
testString: assert.equal(knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200), 185);
- text: <code>knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100)</code> should return <code>237</code>.
testString: assert.equal(knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100), 237);
- text: <code>knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200)</code> should return <code>317</code>.'
testString: assert.equal(knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200), 317);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function knapsack(items, maxweight) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function knapsack(items, maxweight) {
var _ = {
max: function(e) {
var mx = e[0];
e.forEach(function(f) {
if (mx < f) mx = f;
});
return mx;
},
map: function(array, func) {
return array.map(func);
},
isUndefined: function(a) {
if (a) {
return false;
}
return true;
},
range: function(start, end, step) {
var a = [];
var f = (f = (i, end) => i < end);
if (start > end) f = (i, end) => i > end;
for (var i = start; f(i, end); i += step) a.push(i);
return a;
}
};
var valuefn = e => e.value;
var weightfn = e => e.weight;
var _epsilon = 0.01;
var _p = _.max(_.map(items, valuefn));
var _k = (_epsilon * _p) / items.length;
var _memo = (function() {
var _mem = {};
var _key = function(i, w) {
return i + '::' + w;
};
return {
get: function(i, w) {
return _mem[_key(i, w)];
},
put: function(i, w, r) {
_mem[_key(i, w)] = r;
return r;
}
};
})();
var _m = function(i, w) {
i = Math.round(i);
w = Math.round(w);
if (i < 0 || w === 0) {
// empty base case
return { items: [], totalWeight: 0, totalValue: 0 };
}
var mm = _memo.get(i, w);
if (!_.isUndefined(mm)) {
return mm;
}
var item = items[i];
if (weightfn(item) > w) {
//item does not fit, try the next item
return _memo.put(i, w, _m(i - 1, w));
}
// this item could fit.
// are we better off excluding it?
var excluded = _m(i - 1, w);
// or including it?
var included = _m(i - 1, w - weightfn(item));
if (
included.totalValue + Math.floor(valuefn(item) / _k) >
excluded.totalValue
) {
// better off including it
// make a copy of the list
var i1 = included.items.slice();
i1.push(item);
return _memo.put(i, w, {
items: i1,
totalWeight: included.totalWeight + weightfn(item),
totalValue: included.totalValue + Math.floor(valuefn(item) / _k)
});
}
//better off excluding it
return _memo.put(i, w, excluded);
};
var scaled = _m(items.length - 1, maxweight);
var val = 0;
scaled.items.forEach(function(e) {
val += e.value;
});
return val;
}
```
</section>

View File

@ -0,0 +1,111 @@
---
id: 5a23c84252665b21eecc7ed2
title: Knapsack problem/Bounded
challengeType: 5
isHidden: false
forumTopicId: 323652
---
## Description
<section id='description'>
The bounded knapsack problem is defined as follows:
You are given an array of objects representing items to be put in a knapsack. The objects have 4 attributes: name, pieces (the number of the particular item), weight, and value. The items need to be selected so that the total weight does not exceed the maximum weight and the value is maximized. Keep in mind that each item can appear between 0 and <code>pieces</code> times.
</section>
## Instructions
<section id='instructions'>
Write a function to solve the knapsack problem. The function is given the array of objects and the maximum weight as parameters. It should return the maximum total value possible.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300)</code> should return <code>755</code>.
testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300), 755);
- text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400)</code> should return <code>875</code>.
testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400), 875);
- text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500)</code> should return <code>1015</code>.
testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500), 1015);
- text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600)</code> should return <code>1120</code>.
testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600), 1120);
- text: <code>findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700)</code> should return <code>1225</code>.
testString: assert.equal(findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700), 1225);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function findBestPack(data, maxweight) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function findBestPack(data, maxweight) {
var m = [[0]]; // maximum pack value found so far
var b = [[0]]; // best combination found so far
var opts = [0]; // item index for 0 of item 0
var P = [1]; // item encoding for 0 of item 0
var choose = 0;
for (var j = 0; j < data.length; j++) {
opts[j + 1] = opts[j] + data[j].pieces; // item index for 0 of item j+1
P[j + 1] = P[j] * (1 + data[j].pieces); // item encoding for 0 of item j+1
}
for (var j = 0; j < opts[data.length]; j++) {
m[0][j + 1] = b[0][j + 1] = 0; // best values and combos for empty pack: nothing
}
for (var w = 1; w <= maxweight; w++) {
m[w] = [0];
b[w] = [0];
for (var j = 0; j < data.length; j++) {
var N = data[j].pieces; // how many of these can we have?
var base = opts[j]; // what is the item index for 0 of these?
for (var n = 1; n <= N; n++) {
var W = n * data[j].weight; // how much do these items weigh?
var s = w >= W ? 1 : 0; // can we carry this many?
var v = s * n * data[j].value; // how much are they worth?
var I = base + n; // what is the item number for this many?
var wN = w - s * W; // how much other stuff can we be carrying?
var C = n * P[j] + b[wN][base]; // encoded combination
m[w][I] = Math.max(m[w][I - 1], v + m[wN][base]); // best value
choose = b[w][I] = m[w][I] > m[w][I - 1] ? C : b[w][I - 1];
}
}
}
var best = [];
for (var j = data.length - 1; j >= 0; j--) {
best[j] = Math.floor(choose / P[j]);
choose -= best[j] * P[j];
}
var wgt = 0;
var val = 0;
for (var i = 0; i < best.length; i++) {
if (0 == best[i]) continue;
wgt += best[i] * data[i].weight;
val += best[i] * data[i].value;
}
return val;
}
```
</section>

View File

@ -0,0 +1,88 @@
---
id: 5a23c84252665b21eecc7ed3
title: Knapsack problem/Continuous
challengeType: 5
isHidden: false
forumTopicId: 323654
---
## Description
<section id='description'>
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with a limit on the maximum weight that it can carry, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after cutting that is proportional to the original price by the ratio of masses. That means: half of an item has half the price of the original.
</section>
## Instructions
<section id='instructions'>
Write a function that takes an array of objects representing the items available in the shop. Each object has 3 attributes: name, weight, and value. The function also takes the maximum weight as a parameter. The function should return the maximum value possible, and the total weight of the selected items should not exceed the maximum weight.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10)</code> should return <code>257.875</code>.
testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10), 257.875);
- text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12)</code> should return <code>295.05405405405406</code>.
testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12), 295.05405405405406);
- text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15)</code> should return <code>349.3783783783784</code>.
testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15), 349.3783783783784);
- text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22)</code> should return <code>459.5263157894737</code>.
testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22), 459.5263157894737);
- text: <code>knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24)</code> should return <code>478.4736842105263</code>.
testString: assert.equal(knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24), 478.4736842105263);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function knapContinuous(items, maxweight) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function knapContinuous(items, maxweight) {
function item_cmp(a, b) {
const ua = a.unitVal,
ub = b.unitVal;
return ua < ub ? 1 : ua > ub ? -1 : 0;
}
items = items.map(({ value, weight }) => ({
unitVal: value / weight,
weight
}));
items.sort(item_cmp);
let val = 0;
let wt = 0;
for (let { unitVal, weight } of items) {
var portion = Math.min(maxweight - wt, weight);
wt += portion;
var addVal = portion * unitVal;
val += addVal;
if (wt >= maxweight) {
break;
}
}
return val;
}
```
</section>

View File

@ -0,0 +1,97 @@
---
id: 5a23c84252665b21eecc7ed4
title: Knapsack problem/Unbounded
challengeType: 5
isHidden: false
forumTopicId: 323655
---
## Description
<section id='description'>
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri-La. Opting to leave, he is allowed to take as much as he likes of the items available there, so long as it will fit in his knapsack, and he can carry it.
He knows that he can carry no more than a particular value of maximum weight in total; and that the capacity of his knapsack has a limited volume.
Looking just above the bar codes on the items he finds their weights and volumes. He digs out his recent copy of a financial paper and gets the value of each item.
He can only take whole units of any item, but there is much more of any item than he could ever carry.
</section>
## Instructions
<section id='instructions'>
Write a function that takes an array of objects, maximum weight, and maximum volume as parameters. Each object has 4 attributes: name, value, weight, and volume. The function should return the maximum value of items the traveller can take with him.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25)</code> should return <code>54500</code>.
testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25), 54500);
- text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25)</code> should return <code>88400</code>.
testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25), 88400);
- text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15)</code> should return <code>42500</code>.
testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15), 42500);
- text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35)</code> should return <code>75300</code>.
testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35), 75300);
- text: <code>knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25)</code> should return <code>43200</code>.
testString: assert.equal(knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25), 43200);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function knapsackUnbounded(items, maxweight, maxvolume) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function knapsackUnbounded(items, maxweight, maxvolume) {
var n = items.length;
var best_value = 0;
var count = new Array(n);
var best = new Array(n);
function recurseKnapsack(i, value, weight, volume) {
var j, m1, m2, m;
if (i == n) {
if (value > best_value) {
best_value = value;
for (j = 0; j < n; j++) {
best[j] = count[j];
}
}
return;
}
m1 = Math.floor(weight / items[i].weight);
m2 = Math.floor(volume / items[i].volume);
m = m1 < m2 ? m1 : m2;
for (count[i] = m; count[i] >= 0; count[i]--) {
recurseKnapsack(
i + 1,
value + count[i] * items[i].value,
weight - count[i] * items[i].weight,
volume - count[i] * items[i].volume
);
}
}
recurseKnapsack(0, 0, maxweight, maxvolume);
return best_value;
}
```
</section>

View File

@ -0,0 +1,146 @@
---
id: 5a23c84252665b21eecc7ed5
title: Knight's tour
challengeType: 5
isHidden: false
forumTopicId: 302297
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Knight%27s_tour">Knight's Tour</a>Problem: You have an empty <code>w</code> * <code>h</code> chessboard, but for a single knight on some square. The knight must perform a sequence of legal moves that result in the knight visiting every square on the chessboard exactly once. Note that it is <i>not</i> a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.
</section>
## Instructions
<section id='instructions'>
Write a function that takes <code>w</code> and <code>h</code> as parameters and returns the number of initial positions from where it is possible to achieve the task stated above.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>knightTour</code> should be a function.
testString: assert(typeof knightTour == 'function');
- text: <code>knightTour(6, 6)</code> should return a number.
testString: assert(typeof knightTour(6, 6) == 'number');
- text: <code>knightTour(6, 6)</code> should return <code>35</code>.
testString: assert.equal(knightTour(6, 6), 35);
- text: <code>knightTour(5, 6)</code> should return <code>20</code>.
testString: assert.equal(knightTour(5, 6), 20);
- text: <code>knightTour(4, 6)</code> should return <code>10</code>.
testString: assert.equal(knightTour(4, 6), 10);
- text: <code>knightTour(7, 3)</code> should return <code>4</code>.
testString: assert.equal(knightTour(7, 3), 4);
- text: <code>knightTour(8, 6)</code> should return <code>47</code>.
testString: assert.equal(knightTour(8, 6), 47);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function knightTour(w, h) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function knightTour(w, h) {
var b,
cnt = 0;
var dx = [-2, -2, -1, 1, 2, 2, 1, -1];
var dy = [-1, 1, 2, 2, 1, -1, -2, -2];
function init_board() {
var i, j, k, x, y;
// * b is board; a is board with 2 rows padded at each side
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
b[i][j] = 255;
}
}
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
for (k = 0; k < 8; k++) {
(x = j + dx[k]), (y = i + dy[k]);
if (b[i][j] == 255) b[i][j] = 0;
if (x >= 0 && x < w && y >= 0 && y < h) b[i][j]++;
}
}
}
}
function walk_board(x, y) {
var i, nx, ny, least;
var steps = 0;
// printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x);
while (1) {
// * occupy cell
b[y][x] = 255;
// * reduce all neighbors' neighbor count
for (i = 0; i < 8; i++)
if (y + dy[i] >= 0 && x + dx[i] >= 0 && y + dy[i] < h && x + dx[i] < w)
b[y + dy[i]][x + dx[i]]--;
// find neighbor with lowest neighbor count
least = 255;
for (i = 0; i < 8; i++) {
if (y + dy[i] >= 0 && x + dx[i] >= 0 && y + dy[i] < h && x + dx[i] < w)
if (b[y + dy[i]][x + dx[i]] < least) {
nx = x + dx[i];
ny = y + dy[i];
least = b[ny][nx];
}
}
if (least > 7) {
return steps == w * h - 1;
}
steps++;
(x = nx), (y = ny);
}
}
function solve(x, y) {
b = new Array(h);
for (var i = 0; i < h; i++) b[i] = new Array(w);
init_board();
if (walk_board(x, y)) {
cnt++;
}
}
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
solve(j, i);
}
}
return cnt;
}
```
</section>

View File

@ -0,0 +1,84 @@
---
id: 5a23c84252665b21eecc7edb
title: Largest int from concatenated ints
challengeType: 5
isHidden: false
forumTopicId: 302298
---
## Description
<section id='description'>
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>maxCombine</code> should be a function.
testString: assert(typeof maxCombine == 'function');
- text: <code>maxCombine([1, 3, 3, 4, 55])</code> should return a number.
testString: assert(typeof maxCombine([1, 3, 3, 4, 55]) == 'number');
- text: <code>maxCombine([1, 3, 3, 4, 55])</code> should return <code>554331</code>.
testString: assert.equal(maxCombine([1, 3, 3, 4, 55]), 554331);
- text: <code>maxCombine([71, 45, 23, 4, 5])</code> should return <code>71545423</code>.
testString: assert.equal(maxCombine([71, 45, 23, 4, 5]), 71545423);
- text: <code>maxCombine([14, 43, 53, 114, 55])</code> should return <code>55534314114</code>.
testString: assert.equal(maxCombine([14, 43, 53, 114, 55]), 55534314114);
- text: <code>maxCombine([1, 34, 3, 98, 9, 76, 45, 4])</code> should return <code>998764543431</code>.
testString: assert.equal(maxCombine([1, 34, 3, 98, 9, 76, 45, 4]), 998764543431);
- text: <code>maxCombine([54, 546, 548, 60])</code> should return <code>6054854654</code>.
testString: assert.equal(maxCombine([54, 546, 548, 60]), 6054854654);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function maxCombine(xs) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function maxCombine(xs) {
return parseInt(
xs
.sort(function(x, y) {
var a = x.toString(),
b = y.toString(),
ab = parseInt(a + b),
ba = parseInt(b + a);
return ab > ba ? -1 : ab < ba ? 1 : 0;
})
.join(''),
10
);
}
```
</section>

View File

@ -0,0 +1,86 @@
---
id: 5a23c84252665b21eecc7edc
title: Last Friday of each month
challengeType: 5
isHidden: false
forumTopicId: 302299
---
## Description
<section id='description'>
Write a function that returns the date of the last Friday of a given month for a given year.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>lastFriday</code> should be a function.
testString: assert(typeof lastFriday == 'function');
- text: <code>lastFriday(2018, 1)</code> should return a number.
testString: assert(typeof lastFriday(2018, 1) == 'number');
- text: <code>lastFriday(2018, 1)</code> should return <code>26</code>.
testString: assert.equal(lastFriday(2018, 1), 26);
- text: <code>lastFriday(2017, 2)</code> should return <code>24</code>.
testString: assert.equal(lastFriday(2017, 2), 24);
- text: <code>lastFriday(2012, 3)</code> should return <code>30</code>.
testString: assert.equal(lastFriday(2012, 3), 30);
- text: <code>lastFriday(1900, 4)</code> should return <code>27</code>.
testString: assert.equal(lastFriday(1900, 4), 27);
- text: <code>lastFriday(2000, 5)</code> should return <code>26</code>.
testString: assert.equal(lastFriday(2000, 5), 26);
- text: <code>lastFriday(2006, 6)</code> should return <code>30</code>.
testString: assert.equal(lastFriday(2006, 6), 30);
- text: <code>lastFriday(2010, 7)</code> should return <code>30</code>.
testString: assert.equal(lastFriday(2010, 7), 30);
- text: <code>lastFriday(2005, 8)</code> should return <code>26</code>.
testString: assert.equal(lastFriday(2005, 8), 26);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function lastFriday(year, month) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function lastFriday(year, month) {
var i, last_day;
i = 0;
while (true) {
last_day = new Date(year, month, i);
if (last_day.getDay() === 5) {
return last_day.getDate();
}
i -= 1;
}
}
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 5a23c84252665b21eecc7ede
title: Leap year
challengeType: 5
isHidden: false
forumTopicId: 302300
---
## Description
<section id='description'>
Determine whether a given year is a leap year in the Gregorian calendar.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>isLeapYear</code> should be a function.
testString: assert(typeof isLeapYear == 'function');
- text: <code>isLeapYear()</code> should return a boolean.
testString: assert(typeof isLeapYear(2018) == 'boolean');
- text: <code>isLeapYear(2018)</code> should return <code>false</code>.
testString: assert.equal(isLeapYear(2018), false);
- text: <code>isLeapYear(2016)</code> should return <code>true</code>.
testString: assert.equal(isLeapYear(2016), true);
- text: <code>isLeapYear(2000)</code> should return <code>true</code>.
testString: assert.equal(isLeapYear(2000), true);
- text: <code>isLeapYear(1900)</code> should return <code>false</code>.
testString: assert.equal(isLeapYear(1900), false);
- text: <code>isLeapYear(1996)</code> should return <code>true</code>.
testString: assert.equal(isLeapYear(1996), true);
- text: <code>isLeapYear(1800)</code> should return <code>false</code>.
testString: assert.equal(isLeapYear(1800), false);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function isLeapYear(year) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function isLeapYear(year) {
return year % 100 === 0 ? year % 400 === 0 : year % 4 === 0;
}
```
</section>

View File

@ -0,0 +1,88 @@
---
id: 5a23c84252665b21eecc7edf
title: Least common multiple
challengeType: 5
isHidden: false
forumTopicId: 302301
---
## Description
<section id='description'>
The least common multiple of 12 and 18 is 36, because 12 is a factor (12 &times; 3 = 36), and 18 is a factor (18 &times; 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either <i>m</i> or <i>n</i> is zero, then the least common multiple is zero.
One way to calculate the least common multiple is to iterate all the multiples of <i>m</i>, until you find one that is also a multiple of <i>n</i>.
If you already have <i>gcd</i> for <a href="https://rosettacode.org/wiki/greatest common divisor" target="_blank">greatest common divisor</a>, then this formula calculates <i>lcm</i>.
\( \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} \)
</section>
## Instructions
<section id='instructions'>
Compute the least common multiple of an array of integers.
Given <i>m</i> and <i>n</i>, the least common multiple is the smallest positive integer that has both <i>m</i> and <i>n</i> as factors.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>LCM</code> should be a function.
testString: assert(typeof LCM == 'function');
- text: <code>LCM([2, 4, 8])</code> should return a number.
testString: assert(typeof LCM([2, 4, 8]) == 'number');
- text: <code>LCM([2, 4, 8])</code> should return <code>8</code>.
testString: assert.equal(LCM([2, 4, 8]), 8);
- text: <code>LCM([4, 8, 12])</code> should return <code>24</code>.
testString: assert.equal(LCM([4, 8, 12]), 24);
- text: <code>LCM([3, 4, 5, 12, 40])</code> should return <code>120</code>.
testString: assert.equal(LCM([3, 4, 5, 12, 40]), 120);
- text: <code>LCM([11, 33, 90])</code> should return <code>990</code>.
testString: assert.equal(LCM([11, 33, 90]), 990);
- text: <code>LCM([-50, 25, -45, -18, 90, 447])</code> should return <code>67050</code>.
testString: assert.equal(LCM([-50, 25, -45, -18, 90, 447]), 67050);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LCM(A) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function LCM(A) {
var n = A.length,
a = Math.abs(A[0]);
for (var i = 1; i < n; i++) {
var b = Math.abs(A[i]),
c = a;
while (a && b) {
a > b ? (a %= b) : (b %= a);
}
a = Math.abs(c * A[i]) / (a + b);
}
return a;
}
```
</section>

View File

@ -0,0 +1,95 @@
---
id: 5a23c84252665b21eecc7ee0
title: Left factorials
challengeType: 5
isHidden: false
forumTopicId: 302302
---
## Description
<section id='description'>
<b>Left factorials</b>, $ !n $, may refer to either <i>subfactorials</i> or to <i>factorial sums</i>. The same notation can be confusingly seen used for the two different definitions. Sometimes, <i>subfactorials</i> (also known as <i>derangements</i>) may use any of the notations:
<ul>
<li>$!n`$</li>
<li>$!n$</li>
<li>$n¡$</li>
</ul>
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This task will be using this formula for <b>left factorial</b>:
$ !n = \sum_{k=0}^{n-1} k! $
where $!0 = 0$
</section>
## Instructions
<section id='instructions'>
Write a function to calculate the left factorial of a given number.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>leftFactorial</code> should be a function.
testString: assert(typeof leftFactorial == 'function');
- text: <code>leftFactorial(0)</code> should return a number.
testString: assert(typeof leftFactorial(0) == 'number');
- text: <code>leftFactorial(0)</code> should return <code>0</code>.
testString: assert.equal(leftFactorial(0), 0);
- text: <code>leftFactorial(1)</code> should return <code>1</code>.
testString: assert.equal(leftFactorial(1), 1);
- text: <code>leftFactorial(2)</code> should return <code>2</code>.
testString: assert.equal(leftFactorial(2), 2);
- text: <code>leftFactorial(3)</code> should return <code>4</code>.
testString: assert.equal(leftFactorial(3), 4);
- text: <code>leftFactorial(10)</code> should return <code>409114</code>.
testString: assert.equal(leftFactorial(10), 409114);
- text: <code>leftFactorial(17)</code> should return <code>22324392524314</code>.
testString: assert.equal(leftFactorial(17), 22324392524314);
- text: <code>leftFactorial(19)</code> should return <code>6780385526348314</code>.
testString: assert.equal(leftFactorial(19), 6780385526348314);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function leftFactorial(n) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function leftFactorial(n) {
if (n == 0) return 0;
if (n == 1) return 1;
// Note: for n>=20, the result may not be correct.
// This is because JavaScript uses 53 bit integers and
// for n>=20 result becomes too large.
let res = 2,
fact = 2;
for (var i = 2; i < n; i++) {
res += fact;
fact *= i + 1;
}
return res;
}
```
</section>

View File

@ -0,0 +1,100 @@
---
title: S-Expressions
id: 59667989bf71cf555dd5d2ff
challengeType: 5
isHidden: false
forumTopicId: 302303
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/S-Expression" title="wp: S-Expression" target="_blank">S-Expressions</a> are one convenient way to parse and store data.
</section>
## Instructions
<section id='instructions'>
Write a simple reader/parser for S-Expressions that handles quoted and unquoted strings, integers and floats.
The function should read a single but nested S-Expression from a string and return it as a (nested) array.
Newlines and other whitespace may be ignored unless contained within a quoted string.
"<tt>()</tt>" inside quoted strings are not interpreted, but treated as part of the string.
Handling escaped quotes inside a string is optional; thus "<tt>(foo"bar)</tt>" may be treated as a string "<tt>foo"bar</tt>", or as an error.
For this, the reader need not recognize "<tt>\</tt>" for escaping, but should, in addition, recognize numbers if the language has appropriate data types.
Note that with the exception of "<tt>()"</tt>" ("<tt>\</tt>" if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.
The reader should be able to read the following input
<pre>
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
</pre>
and turn it into a native data structure. (See the <a href="https://rosettacode.org/wiki/S-Expressions#Pike" title="#Pike" target="_blank">Pike</a>, <a href="https://rosettacode.org/wiki/S-Expressions#Python" title="#Python" target="_blank">Python</a> and <a href="https://rosettacode.org/wiki/S-Expressions#Ruby" title="#Ruby" target="_blank">Ruby</a> implementations for examples of native data structures.)
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>parseSexpr</code> should be a function.
testString: assert(typeof parseSexpr === 'function');
- text: <code>parseSexpr('(data1 data2 data3)')</code> should return <code>['data1', 'data2', 'data3']</code>
testString: assert.deepEqual(parseSexpr(simpleSExpr), simpleSolution);
- text: <code>parseSexpr('(data1 data2 data3)')</code> should return an array with 3 elements.
testString: assert.deepEqual(parseSexpr(basicSExpr), basicSolution);
```
</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
const simpleSExpr = '(data1 data2 data3)';
const simpleSolution = ['data1', 'data2', 'data3'];
const basicSExpr = '((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))';
const basicSolution = [["data","\"quoted data\"",123,4.5],["data",["!@#",[4.5],"\"(more\"","\"data)\""]]];
```
</div>
</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,105 @@
---
title: 'Sailors, coconuts and a monkey problem'
id: 59da22823d04c95919d46269
challengeType: 5
isHidden: false
forumTopicId: 302304
---
## Description
<section id='description'>
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
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.
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.
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.)
</section>
## Instructions
<section id='instructions'>
Create a function that returns the minimum possible size of the initial pile of coconuts collected during the day for <code>N</code> sailors.
<strong>Note:</strong>
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc. can occur in time fitting the story line, so as not to affect the mathematics.
<strong>C.f:</strong>
<ul>
<li><a href="https://www.youtube.com/watch?v=U9qU20VmvaU" target="_blank"> Monkeys and Coconuts - Numberphile</a> (Video) Analytical solution.</li>
<li><a href="https://oeis.org/A002021" target="_blank">A002021 Pile of coconuts problem</a> The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).</li>
</ul>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>splitCoconuts</code> should be a function.
testString: assert(typeof splitCoconuts === 'function');
- text: <code>splitCoconuts(5)</code> should return 3121.
testString: assert(splitCoconuts(5) === 3121);
- text: <code>splitCoconuts(6)</code> should return 233275.
testString: assert(splitCoconuts(6) === 233275);
- text: <code>splitCoconuts(7)</code> should return 823537.
testString: assert(splitCoconuts(7) === 823537);
```
</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,102 @@
---
title: SEDOLs
id: 59d9c6bc214c613ba73ff012
challengeType: 5
isHidden: false
forumTopicId: 302305
---
## Description
<section id='description'>
For each number list of 6-digit <a href="https://en.wikipedia.org/wiki/SEDOL" title="wp: SEDOL" target="_blank">SEDOL</a>s, calculate and append the checksum digit.
That is, given the input string on the left, your function should return the corresponding string on the right:
<pre>
710889 => 7108899
B0YBKJ => B0YBKJ7
406566 => 4065663
B0YBLH => B0YBLH2
228276 => 2282765
B0YBKL => B0YBKL9
557910 => 5579107
B0YBKR => B0YBKR5
585284 => 5852842
B0YBKT => B0YBKT7
B00030 => B000300
</pre>
Check 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 an invalid input.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>sedol</code> should be a function.
testString: assert(typeof sedol === 'function');
- text: <code>sedol('a')</code> should return null.
testString: assert(sedol('a') === null);
- text: <code>sedol('710889')</code> should return '7108899'.
testString: assert(sedol('710889') === '7108899');
- text: <code>sedol('BOATER')</code> should return null.
testString: assert(sedol('BOATER') === null);
- text: <code>sedol('228276')</code> should return '2282765'.
testString: assert(sedol('228276') === '2282765');
```
</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,66 @@
---
title: Sort an array of composite structures
id: 5a23c84252665b21eecc7ffe
challengeType: 5
isHidden: false
forumTopicId: 302306
---
## Description
<section id='description'>
Write a function that takes an array of objects as a parameter. The function should sort the array according to the 'key' attribute of the objects and return the sorted array.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>sortByKey</code> should be a function.
testString: assert(typeof sortByKey == 'function');
- text: '<code>sortByKey([{key: 3, value: "foo"}, {key: 2, value: "bar"}, {key: 4, value: "baz"}, {key: 1, value: 42}, {key: 5, value: "another string"}])</code> should return an array.'
testString: assert(Array.isArray(sortByKey([{key:3, value:"foo"}, {key:2, value:"bar"}, {key:4, value:"baz"}, {key:1, value:42}, {key:5, value:"another string"}])));
- text: '<code>sortByKey([{key: 3, value: "foo"}, {key: 2, value: "bar"}, {key: 4, value: "baz"}, {key: 1, value: 42}, {key: 5, value: "another string"}])</code> should return <code>[{key: 1, value: 42}, {key: 2, value: "bar"}, {key: 3, value: "foo"}, {key: 4, value: "baz"}, {key: 5, value: "another string"}]</code>.'
testString: assert.deepEqual(sortByKey([{key:3, value:"foo"}, {key:2, value:"bar"}, {key:4, value:"baz"}, {key:1, value:42}, {key:5, value:"another string"}]), [{key:1, value:42}, {key:2, value:"bar"}, {key:3, value:"foo"}, {key:4, value:"baz"}, {key:5, value:"another string"}]);
- text: '<code>sortByKey([{key: 3, name: "Joe"}, {key: 4, name: "Bill"}, {key: 20, name: "Alice"}, {key: 5, name: "Harry"}])</code> should return <code>[{key: 3, name: "Joe"}, {key: 4, name: "Bill"}, {key: 5, name: "Harry"}, {key: 20, name: "Alice"}]</code>.'
testString: assert.deepEqual(sortByKey([{key:3, name:"Joe"}, {key:4, name:"Bill"}, {key:20, name:"Alice"}, {key:5, name:"Harry"}]), [{key:3, name:"Joe"}, {key:4, name:"Bill"}, {key:5, name:"Harry"}, {key:20, name:"Alice"}]);
- text: '<code>sortByKey([{key: 2341, name: "Adam"}, {key: 122, name: "Bernie"}, {key: 19, name: "David"}, {key: 5531, name: "Joe"}, {key: 1234, name: "Walter"}])</code> should return <code>[{key: 19, name: "David"}, {key: 122, name: "Bernie"}, {key: 1234, name: "Walter"}, {key: 2341, name: "Adam"}, {key: 5531, name: "Joe"}]</code>.'
testString: assert.deepEqual(sortByKey([{key:2341, name:"Adam"}, {key:122, name:"Bernie"}, {key:19, name:"David"}, {key:5531, name:"Joe"}, {key:1234, name:"Walter"}]), [{key:19, name:"David"}, {key:122, name:"Bernie"}, {key:1234, name:"Walter"}, {key:2341, name:"Adam"}, {key:5531, name:"Joe"}]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function sortByKey(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function sortByKey (arr) {
return arr.sort(function(a, b) {
return a.key - b.key
});
}
```
</section>

View File

@ -0,0 +1,93 @@
---
id: 5a23c84252665b21eecc8000
title: Sort disjoint sublist
challengeType: 5
isHidden: false
forumTopicId: 302307
---
## Description
<section id='description'>
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the set of those to be sorted.
Make your function work with the following list of values and set of indices:
<code> values: [7, <b>6</b>, 5, 4, 3, 2, <b>1</b>, <b>0</b>]</code>
<code> indices(0-based): {6, 1, 7}</code>
Where the correct result would be:
<code>[7, <b>0</b>, 5, 4, 3, 2, <b>1</b>, <b>6</b>]</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>sortDisjoint</code> should be a function.
testString: assert(typeof sortDisjoint == 'function');
- text: <code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])</code> should return an array.
testString: assert(Array.isArray(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])));
- text: <code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])</code> should return <code>[7, 0, 5, 4, 3, 2, 1, 6]</code>.
testString: assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7]), [7, 0, 5, 4, 3, 2, 1, 6]);
- text: <code>sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6])</code> should return <code>[7, 1, 2, 4, 3, 5, 6, 0]</code>.
testString: assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6]), [7, 1, 2, 4, 3, 5, 6, 0]);
- text: <code>sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7])</code> should return <code>[8, 1, 6, 5, 4, 3, 2, 7]</code>.
testString: assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7]), [8, 1, 6, 5, 4, 3, 2, 7]);
- text: <code>sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6])</code> should return <code>[8, 2, 6, 3, 4, 5, 7, 1]</code>.
testString: assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6]), [8, 2, 6, 3, 4, 5, 7, 1]);
- text: <code>sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4])</code> should return <code>[6, 1, 7, 1, 3, 5, 6]</code>.
testString: assert.deepEqual(sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4]), [6, 1, 7, 1, 3, 5, 6]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function sortDisjoint(values, indices) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function sortDisjoint(values, indices) {
let sublist = [];
indices.sort(function(a, b) {
return a - b;
});
for (let i = 0; i < indices.length; i++) {
sublist.push(values[indices[i]]);
}
sublist.sort((a, b) => {
return a - b;
});
for (let i = 0; i < indices.length; i++) {
values[indices[i]] = sublist[i];
}
return values;
}
```
</section>

View File

@ -0,0 +1,81 @@
---
id: 5a23c84252665b21eecc8014
title: Sort stability
challengeType: 5
isHidden: false
forumTopicId: 302308
---
## Description
<section id='description'>
When sorting records in a table by a particular column or field, a <a href="https://en.wikipedia.org/wiki/Stable_sort#Stability" target="_blank">stable sort</a> will always retain the relative order of records that have the same key.
For example, in this table of countries and cities, a stable sort on the <b>second</b> column, the cities, would keep the US Birmingham above the UK Birmingham. (Although an unstable sort <i>might</i>, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would <i>guarantee</i> it).
<pre>
UK London
US New York
US Birmingham
UK Birmingham
</pre>
Similarly, stable sorting on just the first column would generate "UK London" as the first item and "US Birmingham" as the last item (since the order of the elements having the same first word "UK" or "US" would be maintained).
</section>
## Instructions
<section id='instructions'>
Write a function that takes a 2D array as a parameter. Each element has 2 elements similar to the above example. The function should sort the array as mentioned previously and return the sorted array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>stableSort</code> should be a function.
testString: assert(typeof stableSort == 'function');
- text: <code>stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])</code> should return an array.
testString: assert(Array.isArray(stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])));
- text: <code>stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])</code> should return <code>[["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</code>.
testString: assert.deepEqual(stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]), [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]);
- text: <code>stableSort([[2, 2], [1, 2], [1, 4], [1, 5]])</code> should return <code>[[2, 2], [1, 2], [1, 4], [1, 5]]</code>.
testString: assert.deepEqual(stableSort([[2, 2], [1, 2], [1, 4], [1, 5]]), [[2, 2], [1, 2], [1, 4], [1, 5]]);
- text: <code>stableSort([[11, 55], [12, 45], [11, 45], [32, 45]])</code> should return <code>[[12, 45], [11, 45], [32, 45], [11, 55]]</code>.
testString: assert.deepEqual(stableSort([[11, 55], [12, 45], [11, 45], [32, 45]]), [[12, 45], [11, 45], [32, 45], [11, 55]]);
- text: <code>stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]])</code> should return <code>[[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]</code>.
testString: assert.deepEqual(stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]]), [[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]);
- text: <code>stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]])</code> should return <code>[[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]</code>.
testString: assert.deepEqual(stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]]), [[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function stableSort(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function stableSort(arr) {
arr.sort(function(a, b) {
return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;
});
return arr;
}
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 5a23c84252665b21eecc8016
title: Sort using a custom comparator
challengeType: 5
isHidden: false
forumTopicId: 302309
---
## Description
<section id='description'>
Write a function to sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>lengthSorter</code> should be a function.
testString: assert(typeof lengthSorter == 'function');
- text: <code>lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])</code> should return an array.
testString: assert(Array.isArray(lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])));
- text: <code>lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])</code> should return <code>["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]</code>.
testString: assert.deepEqual(lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]), ["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]);
- text: <code>lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"])</code> should return <code>["going", "good", "hope", "your", "day", "is", "?","I"]</code>.
testString: assert.deepEqual(lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"]), ["going", "good", "hope", "your", "day", "is", "?","I"]);
- text: <code>lengthSorter(["Mine", "is", "going", "great"])</code> should return <code>["going", "great", "Mine", "is"]</code>.
testString: assert.deepEqual(lengthSorter(["Mine", "is", "going", "great"]), ["going", "great", "Mine", "is"]);
- text: <code>lengthSorter(["Have", "fun", "sorting", "!!"])</code> should return <code>["sorting", "Have", "fun", "!!"]</code>.
testString: assert.deepEqual(lengthSorter(["Have", "fun", "sorting", "!!"]), ["sorting", "Have", "fun", "!!"]);
- text: <code>lengthSorter(["Everything", "is", "good", "!!"])</code> should return <code>["Everything", "good", "!!", "is"]</code>.
testString: assert.deepEqual(lengthSorter(["Everything", "is", "good", "!!"]), ["Everything", "good", "!!", "is"]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function lengthSorter(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function lengthSorter(arr) {
arr.sort(function(a, b) {
var result = b.length - a.length;
if (result == 0) result = a.localeCompare(b);
return result;
});
return arr;
}
```
</section>

View File

@ -0,0 +1,106 @@
---
id: 5a23c84252665b21eecc8001
title: Sorting algorithms/Bead sort
challengeType: 5
isHidden: false
forumTopicId: 302310
---
## Description
<section id='description'>
Sort an array of positive integers using the <a href="https://en.wikipedia.org/wiki/Bead_sort" target="_blank">Bead Sort Algorithm</a>.
A <i>bead sort</i> is also known as a <i>gravity sort</i>.
The algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>beadSort</code> should be a function.
testString: assert(typeof beadSort == 'function');
- text: <code>beadSort([25, 32, 12, 7, 20])</code> should return an array.
testString: assert(Array.isArray(beadSort([25, 32, 12, 7, 20])));
- text: <code>beadSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
testString: assert.deepEqual(beadSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
- text: <code>beadSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
testString: assert.deepEqual(beadSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
- text: <code>beadSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
testString: assert.deepEqual(beadSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
- text: <code>beadSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
testString: assert.deepEqual(beadSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
- text: <code>beadSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
testString: assert.deepEqual(beadSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function beadSort(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function beadSort(arr) {
var max = 0;
for (var i = 0; i < arr.length; i++) if (arr[i] > max) max = arr[i];
var grid = new Array(arr.length);
for (var i = 0; i < grid.length; i++) {
grid[i] = new Array(max);
}
var levelcount = new Array(max);
levelcount.fill(0);
for (var i = 0; i < max; i++) {
levelcount[i] = 0;
for (var j = 0; j < arr.length; j++) grid[j][i] = '_';
}
for (var i = 0; i < arr.length; i++) {
var num = arr[i];
for (var j = 0; num > 0; j++) {
grid[levelcount[j]++][j] = '*';
num--;
}
}
var sorted = new Array(arr.length);
sorted.fill(0);
for (var i = 0; i < arr.length; i++) {
var putt = 0;
for (
var j = 0;
j < max &&
(function(c) {
return c.charCodeAt == null ? c : c.charCodeAt(0);
})(grid[arr.length - 1 - i][j]) == '*'.charCodeAt(0);
j++
)
putt++;
sorted[i] = putt;
}
return sorted;
}
```
</section>

View File

@ -0,0 +1,101 @@
---
id: 5a23c84252665b21eecc8002
title: Sorting algorithms/Bogosort
challengeType: 5
isHidden: false
forumTopicId: 302311
---
## Description
<section id='description'>
<a href="https://en.wikipedia.org/wiki/Bogosort" target="_blank">Bogosort</a> a list of numbers.
Bogosort simply shuffles a collection randomly until it is sorted.
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in <i>n</i> factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
Its best case is O(n) since a single pass through the elements may suffice to order them.
Pseudocode:
<pre>
<b>while not</b> InOrder(list) <b>do</b>
Shuffle(list)
<b>done</b>
</pre>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>bogosort</code> should be a function.
testString: assert(typeof bogosort == 'function');
- text: <code>bogosort([25, 32, 12, 7, 20])</code> should return an array.
testString: assert(Array.isArray(bogosort([25, 32, 12, 7, 20])));
- text: <code>bogosort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
testString: assert.deepEqual(bogosort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
- text: <code>bogosort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
testString: assert.deepEqual(bogosort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
- text: <code>bogosort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
testString: assert.deepEqual(bogosort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
- text: <code>bogosort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
testString: assert.deepEqual(bogosort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
- text: <code>bogosort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
testString: assert.deepEqual(bogosort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function bogosort(v) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function bogosort(v) {
function shuffle(v) {
for (
var j, x, i = v.length;
i;
j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x
);
return v;
}
function isSorted(v) {
for (var i = 1; i < v.length; i++) {
if (v[i - 1] > v[i]) {
return false;
}
}
return true;
}
var sorted = false;
while (sorted == false) {
v = shuffle(v);
sorted = isSorted(v);
}
return v;
}
```
</section>

View File

@ -0,0 +1,116 @@
---
id: 5a23c84252665b21eecc8004
title: Sorting algorithms/Cocktail sort
challengeType: 5
isHidden: false
forumTopicId: 302312
---
## Description
<section id='description'>
The cocktail shaker sort is an improvement on the <a href="https://rosettacode.org/wiki/Bubble Sort" target="_blank">Bubble Sort</a>. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from <a href="https://en.wikipedia.org/wiki/Cocktail sort" target="_blank">wikipedia</a>):</p>
<pre>
<b>function</b> <i>cocktailSort</i>( A : list of sortable items )
<b>do</b>
swapped := false
<b>for each</b> i <b>in</b> 0 <b>to</b> length( A ) - 2 <b>do</b>
<b>if</b> A[ i ] > A[ i+1 ] <b>then</b> <i>// test whether the two</i>
<i>// elements are in the wrong</i>
<i>// order</i>
swap( A[ i ], A[ i+1 ] ) <i>// let the two elements</i>
<i>// change places</i>
swapped := true;
<b>if</b> swapped = false <b>then</b>
<i>// we can exit the outer loop here if no swaps occurred.</i>
<b>break do-while loop</b>;
swapped := false
<b>for each</b> i <b>in</b> length( A ) - 2 <b>down to</b> 0 <b>do</b>
<b>if</b> A[ i ] > A[ i+1 ] <b>then</b>
swap( A[ i ], A[ i+1 ] )
swapped := true;
<b>while</b> swapped; <i>// if no elements have been swapped,</i>
<i>// then the list is sorted</i>
</pre>
</section>
## Instructions
<section id='instructions'>
Write a function that sorts a given array using cocktail sort.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>cocktailSort</code> should be a function.
testString: assert(typeof cocktailSort == 'function');
- text: <code>cocktailSort([25, 32, 12, 7, 20])</code> should return an array.
testString: assert(Array.isArray(cocktailSort([25, 32, 12, 7, 20])));
- text: <code>cocktailSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
testString: assert.deepEqual(cocktailSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
- text: <code>cocktailSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
testString: assert.deepEqual(cocktailSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
- text: <code>cocktailSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
testString: assert.deepEqual(cocktailSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
- text: <code>cocktailSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
testString: assert.deepEqual(cocktailSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
- text: <code>cocktailSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
testString: assert.deepEqual(cocktailSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function cocktailSort(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function cocktailSort(arr) {
let isSorted = true;
while (isSorted) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
isSorted = true;
}
}
if (!isSorted) break;
isSorted = false;
for (let j = arr.length - 1; j > 0; j--) {
if (arr[j - 1] > arr[j]) {
let temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
isSorted = true;
}
}
}
return arr;
}
```
</section>

View File

@ -0,0 +1,146 @@
---
id: 5a23c84252665b21eecc8005
title: Sorting algorithms/Comb sort
challengeType: 5
isHidden: false
forumTopicId: 302313
---
## Description
<section id='description'>
Implement a <i>comb sort</i>.
The <b>Comb Sort</b> is a variant of the <a href="https://rosettacode.org/wiki/Bubble Sort" target="_blank">Bubble Sort</a>.
Like the <a href="https://rosettacode.org/wiki/Shell sort" target="_blank">Shell sort</a>, the Comb Sort increases the gap used in comparisons and exchanges.
Dividing the gap by $(1-e^{-\varphi})^{-1} \approx 1.247330950103979$ works best, but 1.3 may be more practical.
Some implementations use the insertion sort once the gap is less than a certain amount.
<b>Also see</b>
<ul>
<li>the Wikipedia article: <a href="https://en.wikipedia.org/wiki/Comb sort" target="_blank">Comb sort</a>.</li>
</ul>
Variants:
<ul>
<li>Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings.</li>
<li>Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small). Comb sort with a low gap isn't much better than the Bubble Sort.</li>
</ul>
Pseudocode:
<pre>
<b>function</b> combsort(<b>array</b> input)
gap := input<b>.size</b> <i>//initialize gap size</i>
<b>loop until</b> gap = 1 <b>and</b> swaps = 0
<i>//update the gap value for a next comb. Below is an example</i>
gap := int(gap / 1.25)
<b>if</b> gap < 1
<i>//minimum gap is 1</i>
gap := 1
<b>end if</b>
i := 0
swaps := 0 <i>//see <a href="https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort" target="_blank">Bubble Sort</a> for an explanation</i>
<i>//a single "comb" over the input list</i>
<b>loop until</b> i + gap >= input<b>.size</b> <i>//see <a href="https://rosettacode.org/wiki/Sorting_algorithms/Shell_sort" target="_blank">Shell sort</a> for similar idea</i>
<b>if</b> input[i] > input[i+gap]
<b>swap</b>(input[i], input[i+gap])
swaps := 1 <i>// Flag a swap has occurred, so the</i>
<i>// list is not guaranteed sorted</i>
<b>end if</b>
i := i + 1
<b>end loop</b>
<b>end loop</b>
<b>end function</b>
</pre>
</section>
## Instructions
<section id='instructions'>
Write a function that sorts a given array using Comb sort.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>combSort</code> should be a function.
testString: assert(typeof combSort == 'function');
- text: <code>combSort([25, 32, 12, 7, 20])</code> should return an array.
testString: assert(Array.isArray(combSort([25, 32, 12, 7, 20])));
- text: <code>combSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
testString: assert.deepEqual(combSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
- text: <code>combSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
testString: assert.deepEqual(combSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
- text: <code>combSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
testString: assert.deepEqual(combSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
- text: <code>combSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
testString: assert.deepEqual(combSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
- text: <code>combSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
testString: assert.deepEqual(combSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function combSort(arr) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function combSort(arr) {
function is_array_sorted(arr) {
var sorted = true;
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
break;
}
}
return sorted;
}
var iteration_count = 0;
var gap = arr.length - 2;
var decrease_factor = 1.25;
// Until array is not sorted, repeat iterations
while (!is_array_sorted(arr)) {
// If not first gap
if (iteration_count > 0)
// Calculate gap
gap = gap == 1 ? gap : Math.floor(gap / decrease_factor);
// Set front and back elements and increment to a gap
var front = 0;
var back = gap;
while (back <= arr.length - 1) {
// If elements are not ordered swap them
if (arr[front] > arr[back]) {
var temp = arr[front];
arr[front] = arr[back];
arr[back] = temp;
}
// Increment and re-run swapping
front += 1;
back += 1;
}
iteration_count += 1;
}
return arr;
}
```
</section>

View File

@ -0,0 +1,99 @@
---
id: 5a23c84252665b21eecc8007
title: Sorting algorithms/Gnome sort
challengeType: 5
isHidden: false
forumTopicId: 302314
---
## Description
<section id='description'>
Gnome sort is a sorting algorithm which is similar to <a href="https://rosettacode.org/wiki/Insertion sort" target="_blank">Insertion sort</a>, except that moving an element to its proper place is accomplished by a series of swaps, as in <a href="https://rosettacode.org/wiki/Bubble Sort" target="_blank">Bubble Sort</a>.
The pseudocode for the algorithm is:
<pre>
<b>function</b> <i>gnomeSort</i>(a[0..size-1])
i := 1
j := 2
<b>while</b> i < size <b>do</b>
<b>if</b> a[i-1] <= a[i] <b>then</b>
<i>/// for descending sort, use >= for comparison</i>
i := j
j := j + 1
<b>else</b>
<b>swap</b> a[i-1] <b>and</b> a[i]
i := i - 1
<b>if</b> i = 0 <b>then</b>
i := j
j := j + 1
<b>endif</b>
<b>endif</b>
<b>done</b>
</pre>
</section>
## Instructions
<section id='instructions'>
Write a function to implement the above pseudo code. The function should return the sorted array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>gnomeSort</code> should be a function.
testString: assert(typeof gnomeSort == 'function');
- text: <code>gnomeSort([25, 32, 12, 7, 20])</code> should return an array.
testString: assert(Array.isArray(gnomeSort([25, 32, 12, 7, 20])));
- text: <code>gnomeSort([25, 32, 12, 7, 20])</code> should return <code>[7, 12, 20, 25, 32]</code>.
testString: assert.deepEqual(gnomeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
- text: <code>gnomeSort([38, 45, 35, 8, 13])</code> should return <code>[8, 13, 35, 38, 45]</code>.
testString: assert.deepEqual(gnomeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
- text: <code>gnomeSort([43, 36, 20, 34, 24])</code> should return <code>[20, 24, 34, 36, 43]</code>.
testString: assert.deepEqual(gnomeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
- text: <code>gnomeSort([12, 33, 26, 18, 1, 16, 38])</code> should return <code>[1, 12, 16, 18, 26, 33, 38]</code>.
testString: assert.deepEqual(gnomeSort([12, 33, 26, 18, 1, 16, 38]), [1, 12, 16, 18, 26, 33, 38]);
- text: <code>gnomeSort([3, 39, 48, 16, 1, 4, 29])</code> should return <code>[1, 3, 4, 16, 29, 39, 48]</code>.
testString: assert.deepEqual(gnomeSort([3, 39, 48, 16, 1, 4, 29]), [1, 3, 4, 16, 29, 39, 48]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function gnomeSort(a) {
// Good luck!
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function gnomeSort(a) {
function moveBack(i) {
for (; i > 0 && a[i - 1] > a[i]; i--) {
var t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
}
}
for (var i = 1; i < a.length; i++) {
if (a[i - 1] > a[i]) moveBack(i);
}
return a;
}
```
</section>

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