Feat: add new Markdown parser (#39800)
and change all the challenges to new `md` format.
This commit is contained in:
committed by
GitHub
parent
a07f84c8ec
commit
0bd52f8bd1
@ -1,40 +1,47 @@
|
||||
---
|
||||
title: 100 doors
|
||||
id: 594810f028c0303b75339acb
|
||||
title: 100 doors
|
||||
challengeType: 5
|
||||
forumTopicId: 302217
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`getFinalOpenedDoors` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof getFinalOpenedDoors === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`getFinalOpenedDoors` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(getFinalOpenedDoors(100)));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`getFinalOpenedDoors` should produce the correct result.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFinalOpenedDoors(100), solution);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const solution = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getFinalOpenedDoors(numDoors) {
|
||||
@ -42,23 +49,7 @@ function getFinalOpenedDoors(numDoors) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getFinalOpenedDoors(numDoors) {
|
||||
@ -72,7 +63,4 @@ function getFinalOpenedDoors(numDoors) {
|
||||
}
|
||||
return finalState;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,18 +1,18 @@
|
||||
---
|
||||
title: 24 game
|
||||
id: 5951e88f64ebf159166a1176
|
||||
title: 24 game
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
The [24 Game](https://en.wikipedia.org/wiki/24_Game) 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
|
||||
|
||||
# --instructions--
|
||||
|
||||
## 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>
|
||||
@ -23,51 +23,48 @@ Implement a function that takes a string of four digits as its argument, with ea
|
||||
<li> The order of the digits when given does not have to be preserved. </li>
|
||||
</ul>
|
||||
|
||||
| Example input | Example output |
|
||||
| --- | --- |
|
||||
| <code>solve24("4878");</code> | <code>(7-8/8)*4</code> |
|
||||
| <code>solve24("1234");</code> | <code>3*1*4*2</code> |
|
||||
| <code>solve24("6789");</code> | <code>(6*8)/(9-7)</code> |
|
||||
| <code>solve24("1127");</code> | <code>(1+7)*(2+1)</code> |
|
||||
</section>
|
||||
| Example input | Example output |
|
||||
| ----------------------------- | ------------------------- |
|
||||
| <code>solve24("4878");</code> | <code>(7-8/8)\*4</code> |
|
||||
| <code>solve24("1234");</code> | <code>3\*1\*4\*2</code> |
|
||||
| <code>solve24("6789");</code> | <code>(6\*8)/(9-7)</code> |
|
||||
| <code>solve24("1127");</code> | <code>(1+7)\*(2+1)</code> |
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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], removeParentheses(solve24(testCases[0]))));
|
||||
- text: <code>solve24("1234")</code> should return any arrangement of <code>1*2*3*4</code>
|
||||
testString: assert(include(answers[1], removeParentheses(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], removeParentheses(solve24(testCases[2]))));
|
||||
- text: <code>solve24("1127")</code> should return a permutation of <code>(1+7)*(1+2)</code>
|
||||
testString: assert(include(answers[3], removeParentheses(solve24(testCases[3]))));
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
`solve24` should be a function.
|
||||
|
||||
```js
|
||||
function solve24 (numStr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof solve24 === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`solve24("4878")` should return `(7-8/8)*4` or `4*(7-8/8)`
|
||||
|
||||
```js
|
||||
assert(include(answers[0], removeParentheses(solve24(testCases[0]))));
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`solve24("1234")` should return any arrangement of `1*2*3*4`
|
||||
|
||||
```js
|
||||
assert(include(answers[1], removeParentheses(solve24(testCases[1]))));
|
||||
```
|
||||
|
||||
`solve24("6789")` should return `(6*8)/(9-7)` or `(8*6)/(9-7)`
|
||||
|
||||
```js
|
||||
assert(include(answers[2], removeParentheses(solve24(testCases[2]))));
|
||||
```
|
||||
|
||||
`solve24("1127")` should return a permutation of `(1+7)*(1+2)`
|
||||
|
||||
```js
|
||||
assert(include(answers[3], removeParentheses(solve24(testCases[3]))));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
@ -123,13 +120,16 @@ function replaceChar(origString, replaceChar, index) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function solve24 (numStr) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function solve24(numStr) {
|
||||
@ -199,7 +199,4 @@ function solve24(numStr) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,15 +1,18 @@
|
||||
---
|
||||
title: 9 billion names of God the integer
|
||||
id: 5949b579404977fbaefcd736
|
||||
title: 9 billion names of God the integer
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --description--
|
||||
|
||||
This task is a variation of the [short story by Arthur C. Clarke](<https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary> "wp: The Nine Billion Names of God#Plot_summary").
|
||||
|
||||
(Solvers should be aware of the consequences of completing this task.)
|
||||
In detail, to specify what is meant by a "name":
|
||||
|
||||
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>
|
||||
@ -17,52 +20,72 @@ In detail, to specify what is meant by a "name":
|
||||
<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
|
||||
|
||||
<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>
|
||||
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$.
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
Optionally note that the sum of the $n$-th row $P(n)$ is the integer partition function.
|
||||
|
||||
```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);
|
||||
# --instructions--
|
||||
|
||||
Implement a function that returns the sum of the $n$-th row.
|
||||
|
||||
# --hints--
|
||||
|
||||
`numberOfNames` should be function.
|
||||
|
||||
```js
|
||||
assert(typeof numberOfNames === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`numberOfNames(5)` should equal 7.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(numberOfNames(5), 7);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`numberOfNames(12)` should equal 77.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfNames(12), 77);
|
||||
```
|
||||
|
||||
`numberOfNames(18)` should equal 385.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfNames(18), 385);
|
||||
```
|
||||
|
||||
`numberOfNames(23)` should equal 1255.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfNames(23), 1255);
|
||||
```
|
||||
|
||||
`numberOfNames(42)` should equal 53174.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfNames(42), 53174);
|
||||
```
|
||||
|
||||
`numberOfNames(123)` should equal 2552338241.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfNames(123), 2552338241);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function numberOfNames(num) {
|
||||
@ -71,15 +94,7 @@ function numberOfNames(num) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function numberOfNames(num) {
|
||||
@ -97,7 +112,4 @@ function numberOfNames(num) {
|
||||
}
|
||||
return cache[num][cache[num].length - 1];
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,15 +1,15 @@
|
||||
---
|
||||
title: ABC Problem
|
||||
id: 594810f028c0303b75339acc
|
||||
title: ABC Problem
|
||||
challengeType: 5
|
||||
forumTopicId: 302220
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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)
|
||||
|
||||
<pre>(B O)
|
||||
(X K)
|
||||
(D Q)
|
||||
(C P)
|
||||
@ -30,48 +30,77 @@ You are given a collection of ABC blocks (e.g., childhood alphabet blocks). Ther
|
||||
(P C)
|
||||
(Z M)
|
||||
</pre>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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]));
|
||||
`canMakeWord` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof canMakeWord === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`canMakeWord` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof canMakeWord('hi') === 'boolean');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`canMakeWord("bark")` should return true.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[0]));
|
||||
```
|
||||
|
||||
`canMakeWord("BooK")` should return false.
|
||||
|
||||
```js
|
||||
assert(!canMakeWord(words[1]));
|
||||
```
|
||||
|
||||
`canMakeWord("TReAT")` should return true.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[2]));
|
||||
```
|
||||
|
||||
`canMakeWord("COMMON")` should return false.
|
||||
|
||||
```js
|
||||
assert(!canMakeWord(words[3]));
|
||||
```
|
||||
|
||||
`canMakeWord("squAD")` should return true.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[4]));
|
||||
```
|
||||
|
||||
`canMakeWord("conFUSE")` should return true.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const words = ['bark', 'BooK', 'TReAT', 'COMMON', 'squAD', 'conFUSE'];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function canMakeWord(word) {
|
||||
@ -79,23 +108,7 @@ function canMakeWord(word) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
const words = ['bark', 'BooK', 'TReAT', 'COMMON', 'squAD', 'conFUSE'];
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function canMakeWord(word) {
|
||||
@ -119,7 +132,4 @@ function canMakeWord(word) {
|
||||
});
|
||||
return !length;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,53 +1,63 @@
|
||||
---
|
||||
title: 'Abundant, deficient and perfect number classifications'
|
||||
id: 594810f028c0303b75339acd
|
||||
title: 'Abundant, deficient and perfect number classifications'
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
If <code>P(n) < n</code> then <code>n</code> is classed as <code>deficient</code>
|
||||
These define three classifications of positive integers based on their [proper divisors](<https://rosettacode.org/wiki/Proper divisors> "Proper divisors").
|
||||
|
||||
If <code>P(n) === n</code> then <code>n</code> is classed as <code>perfect</code>
|
||||
Let $P(n)$ be the sum of the proper divisors of `n` where proper divisors are all positive integers `n` other than `n` itself.
|
||||
|
||||
If <code>P(n) > n</code> then <code>n</code> is classed as <code>abundant</code>
|
||||
If `P(n) < n` then `n` is classed as `deficient`
|
||||
|
||||
<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>
|
||||
If `P(n) === n` then `n` is classed as `perfect`
|
||||
|
||||
## 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>
|
||||
If `P(n) > n` then `n` is classed as `abundant`
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
**Example**: `6` has proper divisors of `1`, `2`, and `3`. `1 + 2 + 3 = 6`, so `6` is classed as a perfect number.
|
||||
|
||||
```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);
|
||||
# --instructions--
|
||||
|
||||
Implement a function that calculates how many of the integers from `1` to `20,000` (inclusive) are in each of the three classes. Output the result as an array in the following format `[deficient, perfect, abundant]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getDPA` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof getDPA === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`getDPA` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(getDPA(100)));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`getDPA` return value should have a length of 3.
|
||||
|
||||
```js
|
||||
assert(getDPA(100).length === 3);
|
||||
```
|
||||
|
||||
`getDPA(20000)` should equal [15043, 4, 4953]
|
||||
|
||||
```js
|
||||
assert.deepEqual(getDPA(20000), solution);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const solution = [15043, 4, 4953];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getDPA(num) {
|
||||
@ -55,23 +65,7 @@ function getDPA(num) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
const solution = [15043, 4, 4953];
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getDPA(num) {
|
||||
@ -91,7 +85,4 @@ function getDPA(num) {
|
||||
}
|
||||
return dpa;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,58 +1,55 @@
|
||||
---
|
||||
title: Accumulator factory
|
||||
id: 594810f028c0303b75339ace
|
||||
title: Accumulator factory
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
A problem posed by [Paul Graham](https://en.wikipedia.org/wiki/Paul_Graham_(programmer)) 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).
|
||||
|
||||
# --instructions--
|
||||
|
||||
## 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>
|
||||
|
||||
**Rules:**
|
||||
|
||||
Do not use global variables.
|
||||
<strong>Hint:</strong>
|
||||
|
||||
**Hint:**
|
||||
|
||||
Closures save outer state.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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'>
|
||||
`accumulator` should be a function.
|
||||
|
||||
```js
|
||||
function accumulator(sum) {
|
||||
|
||||
}
|
||||
assert(typeof accumulator === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`accumulator(0)` should return a function.
|
||||
|
||||
```js
|
||||
assert(typeof accumulator(0) === 'function');
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`accumulator(0)(2)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof accumulator(0)(2) === 'number');
|
||||
```
|
||||
|
||||
Passing in the values 3, -4, 1.5, and 5 should return 5.5.
|
||||
|
||||
```js
|
||||
assert(testFn(5) === 5.5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testFn = typeof accumulator(3) === 'function' && accumulator(3);
|
||||
@ -62,13 +59,15 @@ if (testFn) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function accumulator(sum) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function accumulator(sum) {
|
||||
@ -76,7 +75,4 @@ function accumulator(sum) {
|
||||
return sum += n;
|
||||
};
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,47 +1,59 @@
|
||||
---
|
||||
title: Ackermann function
|
||||
id: 594810f028c0303b75339acf
|
||||
title: Ackermann function
|
||||
challengeType: 5
|
||||
forumTopicId: 302223
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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}$
|
||||
|
||||
$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'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`ack` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof ack === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`ack(0, 0)` should return 1.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(ack(0, 0) === 1);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`ack(1, 1)` should return 3.
|
||||
|
||||
```js
|
||||
assert(ack(1, 1) === 3);
|
||||
```
|
||||
|
||||
`ack(2, 5)` should return 13.
|
||||
|
||||
```js
|
||||
assert(ack(2, 5) === 13);
|
||||
```
|
||||
|
||||
`ack(3, 3)` should return 61.
|
||||
|
||||
```js
|
||||
assert(ack(3, 3) === 61);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function ack(m, n) {
|
||||
@ -49,21 +61,10 @@ function ack(m, n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function ack(m, n) {
|
||||
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,20 +1,18 @@
|
||||
---
|
||||
title: Align columns
|
||||
id: 594810f028c0303b75339ad0
|
||||
title: Align columns
|
||||
challengeType: 5
|
||||
forumTopicId: 302224
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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>
|
||||
Given a text file of many lines, where fields within a line are delineated by a single `$` 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.
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Use the following text to test your programs:
|
||||
|
||||
<pre>
|
||||
Given$a$text$file$of$many$lines
|
||||
where$fields$within$a$line$
|
||||
@ -27,7 +25,9 @@ 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>
|
||||
|
||||
**Note that:**
|
||||
|
||||
<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>
|
||||
@ -36,55 +36,36 @@ or$center$justified$within$its$column.
|
||||
<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'>
|
||||
# --hints--
|
||||
|
||||
```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'>
|
||||
`formatText` should be a function.
|
||||
|
||||
```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) {
|
||||
|
||||
}
|
||||
assert(typeof formatText === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`formatText` with the above input and "right" justification should produce the following:
|
||||
|
||||
```js
|
||||
assert.strictEqual(formatText(testInput, 'right'), rightAligned);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`formatText` with the above input and "left" justification should produce the following:
|
||||
|
||||
```js
|
||||
assert.strictEqual(formatText(testInput, 'left'), leftAligned);
|
||||
```
|
||||
|
||||
`formatText` with the above input and "center" justification should produce the following:
|
||||
|
||||
```js
|
||||
assert.strictEqual(formatText(testInput, 'center'), centerAligned);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testInput = [
|
||||
@ -134,13 +115,28 @@ const centerAligned = ' Given a text file of many
|
||||
' or center justified within its column. ';
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```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.'
|
||||
];
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
function formatText(input, justification) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const testArr = [
|
||||
@ -194,7 +190,4 @@ function formatText(input, justification) {
|
||||
input = input.join('\n');
|
||||
return input;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,61 +1,56 @@
|
||||
---
|
||||
title: Amicable pairs
|
||||
id: 5949b579404977fbaefcd737
|
||||
title: Amicable pairs
|
||||
challengeType: 5
|
||||
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:
|
||||
# --description--
|
||||
|
||||
Two integers $N$ and $M$ are said to be [amicable pairs](<https://en.wikipedia.org/wiki/Amicable numbers> "wp: Amicable numbers") if $N \\neq M$ and the sum of the [proper divisors](<https://rosettacode.org/wiki/Proper divisors> "Proper divisors") of $N$ ($\\mathrm{sum}(\\mathrm{propDivs}(N))$) $= M$ as well as $\\mathrm{sum}(\\mathrm{propDivs}(M)) = N$.
|
||||
|
||||
**Example:**
|
||||
|
||||
**1184** and **1210** are an amicable pair, with proper divisors:
|
||||
|
||||
<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'>
|
||||
# --instructions--
|
||||
|
||||
Calculate and show here the Amicable pairs below 20,000 (there are eight).
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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'>
|
||||
`amicablePairsUpTo` should be a function.
|
||||
|
||||
```js
|
||||
function amicablePairsUpTo(maxNum) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof amicablePairsUpTo === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`amicablePairsUpTo(300)` should return `[[220,284]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(amicablePairsUpTo(300), answer300);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`amicablePairsUpTo(3000)` should return `[[220,284],[1184,1210],[2620,2924]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(amicablePairsUpTo(3000), answer3000);
|
||||
```
|
||||
|
||||
`amicablePairsUpTo(20000)` should return `[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(amicablePairsUpTo(20000), answer20000);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const answer300 = [[220, 284]];
|
||||
@ -76,13 +71,16 @@ const answer20000 = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function amicablePairsUpTo(maxNum) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// amicablePairsUpTo :: Int -> [(Int, Int)]
|
||||
@ -124,7 +122,4 @@ function range(m, n, step) {
|
||||
length: Math.floor((n - m) / d) + 1
|
||||
}, (_, i) => m + (i * d));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,42 +1,48 @@
|
||||
---
|
||||
title: Averages/Mode
|
||||
id: 594d8d0ab97724821379b1e6
|
||||
title: Averages/Mode
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
Write a program to find the [mode](<https://en.wikipedia.org/wiki/Mode (statistics)> "wp: Mode (statistics)") 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'>
|
||||
# --hints--
|
||||
|
||||
</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]);
|
||||
`mode` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof mode === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])` should equal `[6]`
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.deepEqual(mode(arr1), [6]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`mode([1, 2, 4, 4, 1])` should equal `[1, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(mode(arr2).sort(), [1, 4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
|
||||
const arr2 = [1, 2, 4, 4, 1];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mode(arr) {
|
||||
@ -45,24 +51,7 @@ function mode(arr) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mode(arr) {
|
||||
@ -86,7 +75,4 @@ function mode(arr) {
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,14 +1,16 @@
|
||||
---
|
||||
title: Averages/Pythagorean means
|
||||
id: 594d966a1467eb84194f0086
|
||||
title: Averages/Pythagorean means
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
Compute all three of the [Pythagorean means](<https://en.wikipedia.org/wiki/Pythagorean means> "wp: Pythagorean means") of the set of integers $1$ through $10$ (inclusive).
|
||||
|
||||
Show that $A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$ 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>
|
||||
@ -17,11 +19,11 @@ Show that <big>$A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n)$
|
||||
<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'>
|
||||
# --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
|
||||
@ -35,38 +37,23 @@ For the answer, please output an object in the following format:
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`pythagoreanMeans` should be a function.
|
||||
|
||||
```js
|
||||
function pythagoreanMeans(rangeArr) {
|
||||
|
||||
}
|
||||
assert(typeof pythagoreanMeans === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`pythagoreanMeans([1, 2, ..., 10])` should equal the same output above.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pythagoreanMeans(range1), answer1);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const range1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
@ -78,16 +65,17 @@ const answer1 = {
|
||||
},
|
||||
test: 'is A >= G >= H ? yes'
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function pythagoreanMeans(rangeArr) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pythagoreanMeans(rangeArr) {
|
||||
@ -152,7 +140,4 @@ function pythagoreanMeans(rangeArr) {
|
||||
mean.Geometric >= mean.Harmonic ? 'yes' : 'no'}`
|
||||
};
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,73 +1,56 @@
|
||||
---
|
||||
title: Averages/Root mean square
|
||||
id: 594da033de4190850b893874
|
||||
title: Averages/Root mean square
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --description--
|
||||
|
||||
Compute the [Root mean square](<https://en.wikipedia.org/wiki/Root mean square> "wp: Root mean square") of the numbers 1 through 10 inclusive.
|
||||
|
||||
The *root mean square* is also known by its initials RMS (or rms), and as the **quadratic mean**.
|
||||
|
||||
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'>
|
||||
$$x\_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. $$
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`rms` should be a function.
|
||||
|
||||
```js
|
||||
function rms(arr) {
|
||||
|
||||
}
|
||||
assert(typeof rms === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])` should equal `6.2048368229954285`.
|
||||
|
||||
```js
|
||||
assert.equal(rms(arr1), answer1);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
const answer1 = 6.2048368229954285;
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function rms(arr) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function rms(arr) {
|
||||
const sumOfSquares = arr.reduce((s, x) => s + x * x, 0);
|
||||
return Math.sqrt(sumOfSquares / arr.length);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,44 +1,52 @@
|
||||
---
|
||||
title: Babbage problem
|
||||
id: 594db4d0dedb4c06a2a4cefd
|
||||
title: Babbage problem
|
||||
challengeType: 5
|
||||
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:
|
||||
# --description--
|
||||
|
||||
[Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage "wp: Charles_Babbage"), 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>
|
||||
<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'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`babbage` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof babbage === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`babbage(99736, 269696)` should not return 99736 (there is a smaller answer).
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(babbage(babbageAns, endDigits), answer);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const babbageAns = 99736;
|
||||
const endDigits = 269696;
|
||||
const answer = 25264;
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function babbage(babbageNum, endDigits) {
|
||||
@ -47,25 +55,7 @@ function babbage(babbageNum, endDigits) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
const babbageAns = 99736;
|
||||
const endDigits = 269696;
|
||||
const answer = 25264;
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function babbage(babbageAns, endDigits) {
|
||||
@ -84,7 +74,4 @@ function babbage(babbageAns, endDigits) {
|
||||
|
||||
return answer;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,95 +1,144 @@
|
||||
---
|
||||
title: Balanced brackets
|
||||
id: 594dc6c729e5700999302b45
|
||||
title: Balanced brackets
|
||||
challengeType: 5
|
||||
forumTopicId: 302230
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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>
|
||||
| Input | Output |
|
||||
| ------------------------- | ------ |
|
||||
| <code>\[]</code> | true |
|
||||
| <code>]\[</code> | false |
|
||||
| <code>[][]</code> | true |
|
||||
| <code>]\[]</code> | false |
|
||||
| <code>\[]]\[\[]</code> | false |
|
||||
| <code>\[\[\[\[]]]]</code> | true |
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --hints--
|
||||
|
||||
</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'>
|
||||
`isBalanced` should be a function.
|
||||
|
||||
```js
|
||||
function isBalanced(str) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof isBalanced === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`isBalanced("[]")` should return true.
|
||||
|
||||
```js
|
||||
assert(isBalanced(testCases[0]));
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`isBalanced("]][[[][][][]][")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[1]));
|
||||
```
|
||||
|
||||
`isBalanced("[][[[[][][[[]]]]]]")` should return true.
|
||||
|
||||
```js
|
||||
assert(isBalanced(testCases[2]));
|
||||
```
|
||||
|
||||
`isBalanced("][")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[3]));
|
||||
```
|
||||
|
||||
`isBalanced("[[[]]]][[]")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[4]));
|
||||
```
|
||||
|
||||
`isBalanced("][[]")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[5]));
|
||||
```
|
||||
|
||||
`isBalanced("][[][]][[[]]")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[6]));
|
||||
```
|
||||
|
||||
`isBalanced("[[][]]][")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[7]));
|
||||
```
|
||||
|
||||
`isBalanced("[[[]]][[]]]][][[")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[8]));
|
||||
```
|
||||
|
||||
`isBalanced("[]][[]]][[[[][]]")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[9]));
|
||||
```
|
||||
|
||||
`isBalanced("][]][[][")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[10]));
|
||||
```
|
||||
|
||||
`isBalanced("[[]][[][]]")` should return true.
|
||||
|
||||
```js
|
||||
assert(isBalanced(testCases[11]));
|
||||
```
|
||||
|
||||
`isBalanced("[[]]")` should return true.
|
||||
|
||||
```js
|
||||
assert(isBalanced(testCases[12]));
|
||||
```
|
||||
|
||||
`isBalanced("]][]][[]][[[")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[13]));
|
||||
```
|
||||
|
||||
`isBalanced("][]][][[")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[14]));
|
||||
```
|
||||
|
||||
`isBalanced("][][")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[15]));
|
||||
```
|
||||
|
||||
`isBalanced("[]]]")` should return false.
|
||||
|
||||
```js
|
||||
assert(!isBalanced(testCases[16]));
|
||||
```
|
||||
|
||||
`isBalanced("")` should return true.
|
||||
|
||||
```js
|
||||
assert(isBalanced(testCases[17]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
@ -114,13 +163,16 @@ const testCases = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function isBalanced(str) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isBalanced(str) {
|
||||
@ -133,7 +185,4 @@ function isBalanced(str) {
|
||||
} while (a !== b);
|
||||
return !a;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,81 +1,86 @@
|
||||
---
|
||||
title: Circles of given radius through two points
|
||||
id: 5951815dd895584b06884620
|
||||
title: Circles of given radius through two points
|
||||
challengeType: 5
|
||||
forumTopicId: 302231
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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>
|
||||
|
||||
**Exceptions:**
|
||||
|
||||
<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'>
|
||||
# --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>
|
||||
|
||||
**For edge cases, return the following:**
|
||||
|
||||
<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
|
||||
|
||||
**Sample inputs:**
|
||||
|
||||
<pre> p1 p2 r
|
||||
0.1234, 0.9876 0.8765, 0.2345 2.0
|
||||
0.0000, 2.0000 0.0000, 0.0000 1.0
|
||||
0.1234, 0.9876 0.1234, 0.9876 2.0
|
||||
0.1234, 0.9876 0.8765, 0.2345 0.5
|
||||
0.1234, 0.9876 0.1234, 0.9876 0.0
|
||||
</pre>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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'>
|
||||
`getCircles` should be a function.
|
||||
|
||||
```js
|
||||
function getCircles(...args) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof getCircles === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)` should return `[[1.8631, 1.9742], [-0.8632, -0.7521]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getCircles(...testCases[0]), answers[0]);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)` should return `[0, 1]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(getCircles(...testCases[1]), answers[1]);
|
||||
```
|
||||
|
||||
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)` should return `Coincident point. Infinite solutions`
|
||||
|
||||
```js
|
||||
assert.deepEqual(getCircles(...testCases[2]), answers[2]);
|
||||
```
|
||||
|
||||
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)` should return `No intersection. Points further apart than circle diameter`
|
||||
|
||||
```js
|
||||
assert.deepEqual(getCircles(...testCases[3]), answers[3]);
|
||||
```
|
||||
|
||||
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)` should return `Radius Zero`
|
||||
|
||||
```js
|
||||
assert.deepEqual(getCircles(...testCases[4]), answers[4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
@ -94,13 +99,16 @@ const answers = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function getCircles(...args) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;
|
||||
@ -138,7 +146,4 @@ function getCircles(...args) {
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,24 +1,25 @@
|
||||
---
|
||||
title: Closest-pair problem
|
||||
id: 5951a53863c8a34f02bf1bdc
|
||||
title: Closest-pair problem
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the [Closest pair of points problem](<https://en.wikipedia.org/wiki/Closest pair of points problem> "wp: Closest pair of points problem") in the *planar* case.
|
||||
|
||||
The straightforward solution is a O(n<sup>2</sup>) algorithm (which we can call *brute-force algorithm*); the pseudo-code (using indexes) could be simply:
|
||||
|
||||
<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>
|
||||
<strong>if</strong> |P(i) - P(j)| < minDistance <strong>then</strong>
|
||||
minDistance ← |P(i) - P(j)|
|
||||
minPoints ← { P(i), P(j) }
|
||||
<strong>endif</strong>
|
||||
@ -27,9 +28,10 @@ The straightforward solution is a O(n<sup>2</sup>) algorithm (which we can call
|
||||
<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)
|
||||
|
||||
A better algorithm is based on the recursive divide and conquer approach, as explained also at [Wikipedia's Closest pair of points problem](<https://en.wikipedia.org/wiki/Closest pair of points problem#Planar_case> "wp: Closest pair of points problem#Planar_case"), which is `O(nlog(n))` 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>
|
||||
@ -39,20 +41,20 @@ A better algorithm is based on the recursive divide and conquer approach, as exp
|
||||
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> > xm }
|
||||
yR ← { p ∈ yP : p<sub>x</sub> > 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>
|
||||
<strong>if</strong> dL < dR <strong>then</strong>
|
||||
(dmin, pairMin) ← (dL, pairL)
|
||||
<strong>endif</strong>
|
||||
yS ← { p ∈ yP : |xm - p<sub>x</sub>| < dmin }
|
||||
yS ← { p ∈ yP : |xm - p<sub>x</sub>| < 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>
|
||||
<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
|
||||
@ -61,82 +63,72 @@ A better algorithm is based on the recursive divide and conquer approach, as exp
|
||||
<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>
|
||||
|
||||
For the input, expect the argument to be an array of objects (points) with `x` and `y` members set to numbers. For the output, return an object containing the key:value pairs for `distance` and `pair` (the pair of two closest points).
|
||||
|
||||
**References and further readings:**
|
||||
|
||||
<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>
|
||||
<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'>
|
||||
# --hints--
|
||||
|
||||
</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'>
|
||||
`getClosestPair` should be a function.
|
||||
|
||||
```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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof getClosestPair === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
Distance should be the following.
|
||||
|
||||
```js
|
||||
assert.equal(getClosestPair(points1).distance, answer1.distance);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
Points should be the following.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
JSON.parse(JSON.stringify(getClosestPair(points1))).pair,
|
||||
answer1.pair
|
||||
);
|
||||
```
|
||||
|
||||
Distance should be the following.
|
||||
|
||||
```js
|
||||
assert.equal(getClosestPair(points2).distance, answer2.distance);
|
||||
```
|
||||
|
||||
Points should be the following.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
JSON.parse(JSON.stringify(getClosestPair(points2))).pair,
|
||||
answer2.pair
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```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)
|
||||
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 = [
|
||||
@ -229,13 +221,27 @@ const benchmarkPoints = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```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;
|
||||
};
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
function getClosestPair(pointsArr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const Point = function(x, y) {
|
||||
@ -250,98 +256,98 @@ Point.prototype.getY = function() {
|
||||
};
|
||||
|
||||
const mergeSort = function mergeSort(points, comp) {
|
||||
if(points.length < 2) return points;
|
||||
if(points.length < 2) return points;
|
||||
|
||||
var n = points.length,
|
||||
i = 0,
|
||||
j = 0,
|
||||
leftN = Math.floor(n / 2),
|
||||
rightN = leftN;
|
||||
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 leftPart = mergeSort( points.slice(0, leftN), comp),
|
||||
rightPart = mergeSort( points.slice(rightN), comp );
|
||||
|
||||
var sortedPart = [];
|
||||
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;
|
||||
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] ]
|
||||
};
|
||||
}
|
||||
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 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 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 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;
|
||||
}
|
||||
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] ]
|
||||
}
|
||||
}
|
||||
}
|
||||
//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
|
||||
};
|
||||
return {
|
||||
distance: minDelta,
|
||||
pair: closestPair
|
||||
};
|
||||
};
|
||||
|
||||
function getClosestPair(points) {
|
||||
@ -353,7 +359,4 @@ function getClosestPair(points) {
|
||||
|
||||
return closestPair(Px, Py);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,17 +1,19 @@
|
||||
---
|
||||
title: Combinations
|
||||
id: 5958469238c0d8d2632f46db
|
||||
title: Combinations
|
||||
challengeType: 5
|
||||
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
|
||||
# --description--
|
||||
|
||||
Given non-negative integers `m` and `n`, generate all size `m` combinations of the integers from `0` (zero) to `n-1` in sorted order (each combination is sorted and the entire table is sorted).
|
||||
|
||||
**Example:**
|
||||
|
||||
`3` comb `5` is:
|
||||
|
||||
<pre>0 1 2
|
||||
0 1 3
|
||||
0 1 4
|
||||
0 2 3
|
||||
@ -22,46 +24,30 @@ Given non-negative integers <code>m</code> and <code>n</code>, generate all size
|
||||
1 3 4
|
||||
2 3 4
|
||||
</pre>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --hints--
|
||||
|
||||
</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'>
|
||||
`combinations` should be a function.
|
||||
|
||||
```js
|
||||
function combinations(m, n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof combinations === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`combinations(3, 5)` should return `[[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]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combinations(testInput1[0], testInput1[1]), testOutput1);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`combinations(4, 6)` should return `[[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]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(combinations(testInput2[0], testInput2[1]), testOutput2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testInput1 = [3, 5];
|
||||
@ -71,13 +57,16 @@ 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>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function combinations(m, n) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function combinations(m, n) {
|
||||
@ -102,7 +91,4 @@ function combinations(m, n) {
|
||||
return ret;
|
||||
}(m, nArr));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,60 +1,84 @@
|
||||
---
|
||||
title: Comma quibbling
|
||||
id: 596e414344c3b2872167f0fe
|
||||
title: Comma quibbling
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
Comma quibbling is a task originally set by Eric Lippert in his [blog](https://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx).
|
||||
|
||||
# --instructions--
|
||||
|
||||
## 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'>
|
||||
**Note:** Assume words are non-empty strings of uppercase characters for this task.
|
||||
|
||||
```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]);
|
||||
# --hints--
|
||||
|
||||
`quibble` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof quibble === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`quibble(["ABC"])` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof quibble(['ABC']) === 'string');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`quibble([])` should return "{}".
|
||||
|
||||
```js
|
||||
assert.equal(quibble(testCases[0]), results[0]);
|
||||
```
|
||||
|
||||
`quibble(["ABC"])` should return "{ABC}".
|
||||
|
||||
```js
|
||||
assert.equal(quibble(testCases[1]), results[1]);
|
||||
```
|
||||
|
||||
`quibble(["ABC", "DEF"])` should return "{ABC and DEF}".
|
||||
|
||||
```js
|
||||
assert.equal(quibble(testCases[2]), results[2]);
|
||||
```
|
||||
|
||||
`quibble(["ABC", "DEF", "G", "H"])` should return "{ABC,DEF,G and H}".
|
||||
|
||||
```js
|
||||
assert.equal(quibble(testCases[3]), results[3]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]];
|
||||
const results = ["{}", "{ABC}", "{ABC and DEF}", "{ABC,DEF,G and H}"];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function quibble(words) {
|
||||
@ -63,24 +87,7 @@ function quibble(words) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function quibble(words) {
|
||||
@ -90,7 +97,4 @@ function quibble(words) {
|
||||
(words[words.length - 1] || '') +
|
||||
"}";
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,62 +1,102 @@
|
||||
---
|
||||
title: Compare a list of strings
|
||||
id: 596e457071c35c882915b3e4
|
||||
title: Compare a list of strings
|
||||
challengeType: 5
|
||||
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:
|
||||
# --description--
|
||||
|
||||
Given a [list](https://en.wikipedia.org/wiki/List_(abstract_data_type) "wp: List\_(abstract_data_type)") 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'>
|
||||
# --hints--
|
||||
|
||||
</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]));
|
||||
`allEqual` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof allEqual === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`azSorted` should be a function.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof azSorted === 'function');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`allEqual(["AA", "AA", "AA", "AA"])` should return true.
|
||||
|
||||
```js
|
||||
assert(allEqual(testCases[0]));
|
||||
```
|
||||
|
||||
`azSorted(["AA", "AA", "AA", "AA"])` should return false.
|
||||
|
||||
```js
|
||||
assert(!azSorted(testCases[0]));
|
||||
```
|
||||
|
||||
`allEqual(["AA", "ACB", "BB", "CC"])` should return false.
|
||||
|
||||
```js
|
||||
assert(!allEqual(testCases[1]));
|
||||
```
|
||||
|
||||
`azSorted(["AA", "ACB", "BB", "CC"])` should return true.
|
||||
|
||||
```js
|
||||
assert(azSorted(testCases[1]));
|
||||
```
|
||||
|
||||
`allEqual([])` should return true.
|
||||
|
||||
```js
|
||||
assert(allEqual(testCases[2]));
|
||||
```
|
||||
|
||||
`azSorted([])` should return true.
|
||||
|
||||
```js
|
||||
assert(azSorted(testCases[2]));
|
||||
```
|
||||
|
||||
`allEqual(["AA"])` should return true.
|
||||
|
||||
```js
|
||||
assert(allEqual(testCases[3]));
|
||||
```
|
||||
|
||||
`azSorted(["AA"])` should return true.
|
||||
|
||||
```js
|
||||
assert(azSorted(testCases[3]));
|
||||
```
|
||||
|
||||
`allEqual(["BB", "AA"])` should return false.
|
||||
|
||||
```js
|
||||
assert(!allEqual(testCases[4]));
|
||||
```
|
||||
|
||||
`azSorted(["BB", "AA"])` should return false.
|
||||
|
||||
```js
|
||||
assert(!azSorted(testCases[4]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [['AA', 'AA', 'AA', 'AA'], ['AA', 'ACB', 'BB', 'CC'], [], ['AA'], ['BB', 'AA']];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function allEqual(arr) {
|
||||
@ -70,23 +110,7 @@ function azSorted(arr) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function allEqual(a) {
|
||||
@ -104,7 +128,4 @@ function azSorted(a) {
|
||||
out = out && (a[i - 1] < a[i]);
|
||||
} return out;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,37 +1,42 @@
|
||||
---
|
||||
title: Convert seconds to compound duration
|
||||
id: 596fd036dc1ab896c5db98b1
|
||||
title: Convert seconds to compound duration
|
||||
challengeType: 5
|
||||
forumTopicId: 302236
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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> |
|
||||
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> | --- |
|
||||
| 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>).
|
||||
@ -43,35 +48,43 @@ Demonstrate that it passes the following three test-cases:
|
||||
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'>
|
||||
# --hints--
|
||||
|
||||
</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]);
|
||||
`convertSeconds` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof convertSeconds === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`convertSeconds(7259)` should return `2 hr, 59 sec`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(convertSeconds(testCases[0]), results[0]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`convertSeconds(86400)` should return `1 d`.
|
||||
|
||||
```js
|
||||
assert.equal(convertSeconds(testCases[1]), results[1]);
|
||||
```
|
||||
|
||||
`convertSeconds(6000000)` should return `9 wk, 6 d, 10 hr, 40 min`.
|
||||
|
||||
```js
|
||||
assert.equal(convertSeconds(testCases[2]), results[2]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [7259, 86400, 6000000];
|
||||
const results = ['2 hr, 59 sec', '1 d', '9 wk, 6 d, 10 hr, 40 min'];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function convertSeconds(sec) {
|
||||
@ -80,24 +93,7 @@ function convertSeconds(sec) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function convertSeconds(sec) {
|
||||
@ -129,7 +125,4 @@ function convertSeconds(sec) {
|
||||
|
||||
return compoundDuration(localNames, sec);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,50 +1,64 @@
|
||||
---
|
||||
title: Count occurrences of a substring
|
||||
id: 596fda99c69f779975a1b67d
|
||||
title: Count occurrences of a substring
|
||||
challengeType: 5
|
||||
forumTopicId: 302237
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
</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]);
|
||||
`countSubstring` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof countSubstring === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`countSubstring("the three truths", "th")` should return `3`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`countSubstring("ababababab", "abab")` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
|
||||
```
|
||||
|
||||
`countSubstring("abaabba*bbaba*bbab", "a*b")` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
|
||||
const searchString = ['th', 'abab', 'a*b'];
|
||||
const results = [3, 2, 2];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countSubstring(str, subStr) {
|
||||
@ -53,25 +67,7 @@ function countSubstring(str, subStr) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countSubstring(str, subStr) {
|
||||
@ -79,7 +75,4 @@ function countSubstring(str, subStr) {
|
||||
const matches = str.match(new RegExp(escapedSubStr, 'g'));
|
||||
return matches ? matches.length : 0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,20 +1,23 @@
|
||||
---
|
||||
title: Count the coins
|
||||
id: 59713bd26bdeb8a594fb9413
|
||||
title: Count the coins
|
||||
challengeType: 5
|
||||
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:
|
||||
# --description--
|
||||
|
||||
There are four types of common coins in [US](https://en.wikipedia.org/wiki/United_States) 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>
|
||||
@ -23,31 +26,28 @@ There are four types of common coins in <a href="https://en.wikipedia.org/wiki/U
|
||||
<li>A nickel and 10 pennies</li>
|
||||
<li>15 pennies</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`countCoins` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof countCoins === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`countCoins()` should return 242.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(countCoins(), 242);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countCoins() {
|
||||
@ -56,15 +56,7 @@ function countCoins() {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countCoins() {
|
||||
@ -86,7 +78,4 @@ function countCoins() {
|
||||
|
||||
return t[targetsLength - 1];
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,74 +1,57 @@
|
||||
---
|
||||
title: Cramer's rule
|
||||
id: 59713da0a428c1a62d7db430
|
||||
title: Cramer's rule
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
In [linear algebra](<https://en.wikipedia.org/wiki/linear algebra> "wp: linear algebra"), [Cramer's rule](<https://en.wikipedia.org/wiki/Cramer's rule> "wp: Cramer's rule") is an explicit formula for the solution of a [system of linear equations](<https://en.wikipedia.org/wiki/system of linear equations> "wp: system of linear equations") 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>
|
||||
|
||||
$\\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.$
|
||||
|
||||
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>
|
||||
|
||||
$\\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}.$
|
||||
|
||||
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'>
|
||||
$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} }.$
|
||||
|
||||
# --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'>
|
||||
$\\begin{cases} 2w-x+5y+z=-3 \\\\ 3w+2x+2y-6z=-32 \\\\ w+3x+3y-z=-47 \\\\ 5w-2x-3y+3z=49 \\\\ \\end{cases}$
|
||||
|
||||
```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]);
|
||||
solve for $w$, $x$, $y$ and $z$, using Cramer's rule.
|
||||
|
||||
```
|
||||
# --hints--
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
`cramersRule` should be a function.
|
||||
|
||||
```js
|
||||
function cramersRule(matrix, freeTerms) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof cramersRule === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`cramersRule([[2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5, -2, -3, 3]], [-3, -32, -47, 49])` should return `[2, -12, -4, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cramersRule(matrices[0], freeTerms[0]), answers[0]);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`cramersRule([[3, 1, 1], [2, 2, 5], [1, -3, -4]], [3, -1, 2])` should return `[1, 1, -1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cramersRule(matrices[1], freeTerms[1]), answers[1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const matrices = [
|
||||
@ -89,13 +72,16 @@ const freeTerms = [[-3, -32, -47, 49], [3, -1, 2]];
|
||||
const answers = [[2, -12, -4, 1], [1, 1, -1]];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function cramersRule(matrix, freeTerms) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
@ -177,7 +163,4 @@ function detr(m) {
|
||||
function clone(m) {
|
||||
return m.map(a => a.slice());
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,49 +5,76 @@ challengeType: 5
|
||||
forumTopicId: 302240
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
<section id='description'>
|
||||
Write a function that takes an array of numbers as parameter and returns the [standard deviation](<https://en.wikipedia.org/wiki/Standard Deviation>) of the series.
|
||||
|
||||
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.
|
||||
# --hints--
|
||||
|
||||
</section>
|
||||
`standardDeviation` should be a function.
|
||||
|
||||
## 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);
|
||||
```js
|
||||
assert(typeof standardDeviation == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])` should return `2`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]), 2);
|
||||
```
|
||||
|
||||
`standardDeviation([600, 470, 170, 430, 300])` should return `147.323`.
|
||||
|
||||
```js
|
||||
assert.equal(standardDeviation([600, 470, 170, 430, 300]), 147.323);
|
||||
```
|
||||
|
||||
`standardDeviation([75, 83, 96, 100, 121, 125])` should return `18.239`.
|
||||
|
||||
```js
|
||||
assert.equal(standardDeviation([75, 83, 96, 100, 121, 125]), 18.239);
|
||||
```
|
||||
|
||||
`standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82])` should return `16.87`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
standardDeviation([23, 37, 45, 49, 56, 63, 63, 70, 72, 82]),
|
||||
16.87
|
||||
);
|
||||
```
|
||||
|
||||
`standardDeviation([271, 354, 296, 301, 333, 326, 285, 298, 327, 316, 287, 314])` should return `22.631`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
standardDeviation([
|
||||
271,
|
||||
354,
|
||||
296,
|
||||
301,
|
||||
333,
|
||||
326,
|
||||
285,
|
||||
298,
|
||||
327,
|
||||
316,
|
||||
287,
|
||||
314
|
||||
]),
|
||||
22.631
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function standardDeviation(arr) {
|
||||
@ -55,12 +82,7 @@ function standardDeviation(arr) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function standardDeviation(arr) {
|
||||
@ -76,5 +98,3 @@ function standardDeviation(arr) {
|
||||
return Math.round(std_dev * 1000) / 1000;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,55 +5,79 @@ challengeType: 5
|
||||
forumTopicId: 302241
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
<section id='description'>
|
||||
A **CUSIP** 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.
|
||||
|
||||
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.
|
||||
# --instructions--
|
||||
|
||||
</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
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`isCusip` should be a function.
|
||||
|
||||
```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);
|
||||
```js
|
||||
assert(typeof isCusip == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`isCusip("037833100")` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof isCusip('037833100') == 'boolean');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`isCusip("037833100")` should return `true`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(isCusip('037833100'), true);
|
||||
```
|
||||
|
||||
`isCusip("17275R102")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('17275R102'), true);
|
||||
```
|
||||
|
||||
`isCusip("38259P50a")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('38259P50a'), false);
|
||||
```
|
||||
|
||||
`isCusip("38259P508")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('38259P508'), true);
|
||||
```
|
||||
|
||||
`isCusip("38259P50#")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('38259P50#'), false);
|
||||
```
|
||||
|
||||
`isCusip("68389X105")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('68389X105'), true);
|
||||
```
|
||||
|
||||
`isCusip("68389X106")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('68389X106'), false);
|
||||
```
|
||||
|
||||
`isCusip("5949181")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isCusip('5949181'), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isCusip(s) {
|
||||
@ -61,12 +85,7 @@ function isCusip(s) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isCusip(s) {
|
||||
@ -96,5 +115,3 @@ function isCusip(s) {
|
||||
return s.charCodeAt(8) - 48 == (10 - (sum % 10)) % 10;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,11 +5,9 @@ challengeType: 5
|
||||
forumTopicId: 302242
|
||||
---
|
||||
|
||||
## Description
|
||||
# --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.
|
||||
A given rectangle is made from *m* × *n* squares. If *m* and *n* 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">
|
||||
@ -59,43 +57,58 @@ A given rectangle is made from <i>m</i> × <i>n</i> squares. If <i>m</i> and <i>
|
||||
</g></g>
|
||||
</svg>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
# --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>
|
||||
Write a function that calculates the number of different ways to cut an *m* × *n* rectangle.
|
||||
|
||||
## Tests
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`cutRectangle` should be a function.
|
||||
|
||||
```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);
|
||||
```js
|
||||
assert(typeof cutRectangle == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`cutRectangle(2, 2)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof cutRectangle(2, 2) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`cutRectangle(2, 2)` should return `2`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(cutRectangle(2, 2), 2);
|
||||
```
|
||||
|
||||
`cutRectangle(4, 3)` should return `9`.
|
||||
|
||||
```js
|
||||
assert.equal(cutRectangle(4, 3), 9);
|
||||
```
|
||||
|
||||
`cutRectangle(4, 4)` should return `22`.
|
||||
|
||||
```js
|
||||
assert.equal(cutRectangle(4, 4), 22);
|
||||
```
|
||||
|
||||
`cutRectangle(8, 3)` should return `53`.
|
||||
|
||||
```js
|
||||
assert.equal(cutRectangle(8, 3), 53);
|
||||
```
|
||||
|
||||
`cutRectangle(7, 4)` should return `151`.
|
||||
|
||||
```js
|
||||
assert.equal(cutRectangle(7, 4), 151);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function cutRectangle(w, h) {
|
||||
@ -103,12 +116,7 @@ function cutRectangle(w, h) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function cutRectangle(w, h) {
|
||||
@ -161,5 +169,3 @@ function cutRectangle(w, h) {
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,60 +1,50 @@
|
||||
---
|
||||
title: Date format
|
||||
id: 59669d08d75b60482359409f
|
||||
title: Date format
|
||||
challengeType: 5
|
||||
forumTopicId: 302243
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Return an array with the current date in the formats:
|
||||
|
||||
<ul>
|
||||
<li>2007-11-23</li>
|
||||
<li>Friday, November 23, 2007</li>
|
||||
</ul>
|
||||
Example output: <code>['2007-11-23', 'Friday, November 23, 2007']</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Example output: `['2007-11-23', 'Friday, November 23, 2007']`
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`getDateFormats` should be a function.
|
||||
|
||||
```js
|
||||
function getDateFormats() {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof getDateFormats === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`getDateFormats` should return an object.
|
||||
|
||||
```js
|
||||
assert(typeof getDateFormats() === 'object');
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`getDateFormats` should return an array with 2 elements.
|
||||
|
||||
```js
|
||||
assert(getDateFormats().length === 2);
|
||||
```
|
||||
|
||||
`getDateFormats` should return the correct date in the right format
|
||||
|
||||
```js
|
||||
assert.deepEqual(getDateFormats(), dates, equalsMessage);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const getDateSolution = () => {
|
||||
@ -70,13 +60,16 @@ const dates = getDateSolution();
|
||||
const equalsMessage = `message: <code>getDataFormats()</code> should return <code>["${dates[0]}", "${dates[1]}"]</code>.`;
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function getDateFormats() {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getDateFormats() {
|
||||
@ -87,7 +80,4 @@ function getDateFormats() {
|
||||
const fmt2 = `${weekdays[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
|
||||
return [fmt1, fmt2];
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,50 +1,69 @@
|
||||
---
|
||||
title: Date manipulation
|
||||
id: 5966c21cf732a95f1b67dd28
|
||||
title: Date manipulation
|
||||
challengeType: 5
|
||||
forumTopicId: 302244
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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 6 2009 7:30pm EST"</code>
|
||||
Example output: <code>"March 7 2009 7:30am EST"</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Example input: `"March 6 2009 7:30pm EST"`
|
||||
|
||||
</section>
|
||||
Example output: `"March 7 2009 7:30am EST"`
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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 6 2009 7:30pm EST")</code> should return <code>"March 7 2009 7:30am EST"</code>
|
||||
testString: assert(add12Hours('March 6 2009 7:30pm EST') === 'March 7 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');
|
||||
`add12Hours` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof add12Hours === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`add12Hours(dateString)` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof add12Hours('January 17 2017 11:43am EST') === 'string');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`add12Hours("January 17 2017 11:43am EST")` should return `"January 17 2017 11:43pm EST"`
|
||||
|
||||
```js
|
||||
assert(
|
||||
add12Hours('January 17 2017 11:43am EST') === 'January 17 2017 11:43pm EST'
|
||||
);
|
||||
```
|
||||
|
||||
Should handle day change. `add12Hours("March 6 2009 7:30pm EST")` should return `"March 7 2009 7:30am EST"`
|
||||
|
||||
```js
|
||||
assert(add12Hours('March 6 2009 7:30pm EST') === 'March 7 2009 7:30am EST');
|
||||
```
|
||||
|
||||
Should handle month change in a leap years. `add12Hours("February 29 2004 9:15pm EST")` should return `"March 1 2004 9:15am EST"`
|
||||
|
||||
```js
|
||||
assert(add12Hours('February 29 2004 9:15pm EST') === 'March 1 2004 9:15am EST');
|
||||
```
|
||||
|
||||
Should handle month change in a common years. `add12Hours("February 28 1999 3:15pm EST")` should return `"March 1 1999 3:15am EST"`
|
||||
|
||||
```js
|
||||
assert(add12Hours('February 28 1999 3:15pm EST') === 'March 1 1999 3:15am EST');
|
||||
```
|
||||
|
||||
Should handle year change. `add12Hours("December 31 2020 1:45pm EST")` should return `"January 1 2021 1:45am EST"`
|
||||
|
||||
```js
|
||||
assert(
|
||||
add12Hours('December 31 2020 1:45pm EST') === 'January 1 2021 1:45am EST'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function add12Hours(dateString) {
|
||||
@ -53,13 +72,7 @@ function add12Hours(dateString) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function add12Hours(dateString) {
|
||||
@ -92,7 +105,4 @@ function add12Hours(dateString) {
|
||||
|
||||
return `${months[date.getMonth()]} ${date.getDate()} ${date.getFullYear()} ${hoursOutput}:${date.getMinutes()}${abbreviation} EST`;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,42 +1,54 @@
|
||||
---
|
||||
title: Day of the week
|
||||
id: 5966f99c45e8976909a85575
|
||||
title: Day of the week
|
||||
challengeType: 5
|
||||
forumTopicId: 302245
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>findXmasSunday</code> should be a function.
|
||||
testString: assert(typeof findXmasSunday === 'function');
|
||||
- text: <code>findXmasSunday(2000, 2100)</code> should return an array.
|
||||
testString: assert(typeof findXmasSunday(2000, 2100) === 'object');
|
||||
- text: <code>findXmasSunday(1970, 2017)</code> should return <code>[1977, 1983, 1988, 1994, 2005, 2011, 2016]</code>
|
||||
testString: assert.deepEqual(findXmasSunday(1970, 2017), firstSolution);
|
||||
- text: <code>findXmasSunday(2008, 2121)</code> should return <code>[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]</code>
|
||||
testString: assert.deepEqual(findXmasSunday(2008, 2121), secondSolution);
|
||||
`findXmasSunday` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof findXmasSunday === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`findXmasSunday(2000, 2100)` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof findXmasSunday(2000, 2100) === 'object');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`findXmasSunday(1970, 2017)` should return `[1977, 1983, 1988, 1994, 2005, 2011, 2016]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(findXmasSunday(1970, 2017), firstSolution);
|
||||
```
|
||||
|
||||
`findXmasSunday(2008, 2121)` should return `[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(findXmasSunday(2008, 2121), secondSolution);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```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];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findXmasSunday(start, end) {
|
||||
@ -45,24 +57,7 @@ function findXmasSunday(start, end) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findXmasSunday(start, end) {
|
||||
@ -75,7 +70,4 @@ function findXmasSunday(start, end) {
|
||||
}
|
||||
return xmasSunday;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,26 +1,31 @@
|
||||
---
|
||||
title: Deal cards for FreeCell
|
||||
id: 59694356a6e7011f7f1c5f4e
|
||||
title: Deal cards for FreeCell
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
*FreeCell* 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 [DOS](https://rosettacode.org/wiki/DOS "DOS"), then [Windows](https://rosettacode.org/wiki/Windows "Windows"). 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:
|
||||
|
||||
The algorithm uses this [linear congruential generator](<https://rosettacode.org/wiki/linear congruential generator> "linear congruential generator") 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><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 ≡ next random number (mod array length).</li>
|
||||
<li>Choose a random card at index ≡ 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>
|
||||
@ -28,8 +33,11 @@ The algorithm follows:
|
||||
</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>
|
||||
|
||||
**Example:**
|
||||
|
||||
**Order to deal cards**
|
||||
|
||||
<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
|
||||
@ -37,7 +45,8 @@ The algorithm follows:
|
||||
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>
|
||||
|
||||
**Game #1**
|
||||
|
||||
```js
|
||||
[
|
||||
@ -51,7 +60,7 @@ The algorithm follows:
|
||||
]
|
||||
```
|
||||
|
||||
<strong>Game #617</strong>
|
||||
**Game #617**
|
||||
|
||||
```js
|
||||
[
|
||||
@ -65,51 +74,47 @@ The algorithm follows:
|
||||
]
|
||||
```
|
||||
|
||||
</section>
|
||||
# --instructions--
|
||||
|
||||
## 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'>
|
||||
Deals can also be checked against [FreeCell solutions to 1000000 games](https://freecellgamesolutions.com/). (Summon a video solution, and it displays the initial deal.)
|
||||
|
||||
```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);"
|
||||
# --hints--
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
`dealFreeCell` should be a function.
|
||||
|
||||
```js
|
||||
function dealFreeCell(seed) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof dealFreeCell === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`dealFreeCell(seed)` should return an object.
|
||||
|
||||
```js
|
||||
assert(typeof dealFreeCell(1) === 'object');
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`dealFreeCell(seed)` should return an array of length 7.
|
||||
|
||||
```js
|
||||
assert(dealFreeCell(1).length === 7);
|
||||
```
|
||||
|
||||
`dealFreeCell(1)` should return an array identical to example "Game #1"
|
||||
|
||||
```js
|
||||
assert.deepEqual(dealFreeCell(1), game1);
|
||||
```
|
||||
|
||||
`dealFreeCell(617)` should return an array identical to example "Game #617"
|
||||
|
||||
```js
|
||||
assert.deepEqual(dealFreeCell(617), game617);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const replaceThis = 3;
|
||||
@ -133,13 +138,16 @@ const game617 = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function dealFreeCell(seed) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// RNG
|
||||
@ -198,7 +206,4 @@ function dealFreeCell(seed) {
|
||||
|
||||
return deltCards;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,64 +1,58 @@
|
||||
---
|
||||
title: Deepcopy
|
||||
id: 596a8888ab7c01048de257d5
|
||||
title: Deepcopy
|
||||
challengeType: 5
|
||||
forumTopicId: 302247
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
</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'>
|
||||
`deepcopy` should be a function.
|
||||
|
||||
```js
|
||||
function deepcopy(obj) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof deepcopy === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`deepcopy({test: "test"})` should return an object.
|
||||
|
||||
```js
|
||||
assert(typeof deepcopy(obj1) === 'object');
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`deepcopy` should not return the same object that was provided.
|
||||
|
||||
```js
|
||||
assert(deepcopy(obj2) != obj2);
|
||||
```
|
||||
|
||||
When passed an object containing an array, `deepcopy` should return a deep copy of the object.
|
||||
|
||||
```js
|
||||
assert.deepEqual(deepcopy(obj2), obj2);
|
||||
```
|
||||
|
||||
When passed an object containing another object, `deepcopy` should return a deep copy of the object.
|
||||
|
||||
```js
|
||||
assert.deepEqual(deepcopy(obj3), obj3);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const obj1 = { test: 'test' };
|
||||
@ -72,20 +66,19 @@ const obj3 = {
|
||||
};
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function deepcopy(obj) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function deepcopy(obj) {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,67 +1,110 @@
|
||||
---
|
||||
title: Define a primitive data type
|
||||
id: 597089c87eec450c68aa1643
|
||||
title: Define a primitive data type
|
||||
challengeType: 5
|
||||
forumTopicId: 302248
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
</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');
|
||||
`Num` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof Num === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`new Num(4)` should return an object.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof new Num(4) === 'object');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`new Num('test')` should throw a TypeError with message 'Not a Number'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num('test'), TypeError);
|
||||
```
|
||||
|
||||
`new Num(0)` should throw a TypeError with message 'Out of range'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num(0), TypeError);
|
||||
```
|
||||
|
||||
`new Num(-5)` should throw a TypeError with message 'Out of range'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num(-5), TypeError);
|
||||
```
|
||||
|
||||
`new Num(10)` should throw a TypeError with message 'Out of range'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num(11), TypeError);
|
||||
```
|
||||
|
||||
`new Num(20)` should throw a TypeError with message 'Out of range'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num(20), TypeError);
|
||||
```
|
||||
|
||||
`new Num(3) + new Num(4)` should equal 7.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) + new Num(4), 7);
|
||||
```
|
||||
|
||||
`new Num(3) - new Num(4)` should equal -1.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) - new Num(4), -1);
|
||||
```
|
||||
|
||||
`new Num(3) * new Num(4)` should equal 12.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) * new Num(4), 12);
|
||||
```
|
||||
|
||||
`new Num(3) / new Num(4)` should equal 0.75.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) / new Num(4), 0.75);
|
||||
```
|
||||
|
||||
`new Num(3) < new Num(4)` should be true.
|
||||
|
||||
```js
|
||||
assert(new Num(3) < new Num(4));
|
||||
```
|
||||
|
||||
`new Num(3) > new Num(4)` should be false.
|
||||
|
||||
```js
|
||||
assert(!(new Num(3) > new Num(4)));
|
||||
```
|
||||
|
||||
`(new Num(5)).toString()` should return '5'
|
||||
|
||||
```js
|
||||
assert.equal(new Num(5).toString(), '5');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function Num(n) {
|
||||
@ -70,12 +113,7 @@ function Num(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function Num(n) {
|
||||
@ -91,5 +129,3 @@ function Num(n) {
|
||||
Num.prototype.valueOf = function() { return this._value; };
|
||||
Num.prototype.toString = function () { return this._value.toString(); };
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,25 +1,28 @@
|
||||
---
|
||||
title: Department Numbers
|
||||
id: 59f40b17e79dbf1ab720ed7a
|
||||
title: Department Numbers
|
||||
challengeType: 5
|
||||
forumTopicId: 302249
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
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.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a program which outputs all valid combinations as an array.
|
||||
|
||||
```js
|
||||
@ -30,43 +33,35 @@ Write a program which outputs all valid combinations as an array.
|
||||
[6, 4, 2] [6, 5, 1]
|
||||
```
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`combinations` should be a function.
|
||||
|
||||
```js
|
||||
function combinations(possibleNumbers, total) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof combinations === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`combinations([1, 2, 3], 6)` should return an Array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(combinations([1, 2, 3], 6)));
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`combinations([1, 2, 3, 4, 5, 6, 7], 12)` should return an array of length 14.
|
||||
|
||||
```js
|
||||
assert(combinations(nums, total).length === len);
|
||||
```
|
||||
|
||||
`combinations([1, 2, 3, 4, 5, 6, 7], 12)` should return all valid combinations.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combinations(nums, total), result);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const nums = [1, 2, 3, 4, 5, 6, 7];
|
||||
@ -90,13 +85,16 @@ const result = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function combinations(possibleNumbers, total) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function combinations(possibleNumbers, total) {
|
||||
@ -124,7 +122,4 @@ function combinations(possibleNumbers, total) {
|
||||
}
|
||||
return allCombinations;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,50 +1,88 @@
|
||||
---
|
||||
title: Discordian date
|
||||
id: 59f4eafba0343628bb682785
|
||||
title: Discordian date
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Convert a given date from the [Gregorian calendar](<https://en.wikipedia.org/wiki/Gregorian calendar> "wp: Gregorian calendar") to the [Discordian calendar](<https://en.wikipedia.org/wiki/Discordian calendar> "wp: Discordian calendar").
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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');
|
||||
`discordianDate` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof discordianDate === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`discordianDate(new Date(2010, 6, 22))` should return `"Pungenday, the 57th day of Confusion in the YOLD 3176"`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2010, 6, 22)) ===
|
||||
'Pungenday, the 57th day of Confusion in the YOLD 3176'
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`discordianDate(new Date(2012, 1, 28))` should return `"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2012, 1, 28)) ===
|
||||
'Prickle-Prickle, the 59th day of Chaos in the YOLD 3178'
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2012, 1, 29))` should return `"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2012, 1, 29)) ===
|
||||
"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib's Day!"
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2012, 2, 1))` should return `"Setting Orange, the 60th day of Chaos in the YOLD 3178"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2012, 2, 1)) ===
|
||||
'Setting Orange, the 60th day of Chaos in the YOLD 3178'
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2010, 0, 5))` should return `"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2010, 0, 5)) ===
|
||||
'Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!'
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2011, 4, 3))` should return `"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2011, 4, 3)) ===
|
||||
'Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!'
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2015, 9, 19))` should return `"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
discordianDate(new Date(2015, 9, 19)) ===
|
||||
'Boomtime, the 73rd day of Bureaucracy in the YOLD 3181'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function discordianDate(date) {
|
||||
@ -53,15 +91,7 @@ function discordianDate(date) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
@ -161,8 +191,4 @@ function discordianDate(date) {
|
||||
+ (celebrateHoliday ? '. Celebrate ' + celebrateHoliday + '!' : '')
|
||||
;
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,49 +5,57 @@ challengeType: 5
|
||||
forumTopicId: 302251
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
<section id='description'>
|
||||
Create a function, to compute the **[dot product](<https://en.wikipedia.org/wiki/Dot product>)**, also known as the **scalar product** of two vectors.
|
||||
|
||||
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.
|
||||
# --hints--
|
||||
|
||||
</section>
|
||||
`dotProduct` should be a function.
|
||||
|
||||
## 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);
|
||||
```js
|
||||
assert(typeof dotProduct == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof dotProduct([1, 3, -5], [4, -2, -1]) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` should return `3`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3);
|
||||
```
|
||||
|
||||
`dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])` should return `130`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]), 130);
|
||||
```
|
||||
|
||||
`dotProduct([5, 4, 3, 2], [7, 8, 9, 6])` should return `106`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([5, 4, 3, 2], [7, 8, 9, 6]), 106);
|
||||
```
|
||||
|
||||
`dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6])` should return `-36`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6]), -36);
|
||||
```
|
||||
|
||||
`dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110])` should return `10392`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110]), 10392);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function dotProduct(ary1, ary2) {
|
||||
@ -55,12 +63,7 @@ function dotProduct(ary1, ary2) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function dotProduct(ary1, ary2) {
|
||||
@ -69,5 +72,3 @@ function dotProduct(ary1, ary2) {
|
||||
return dotprod;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,14 +1,16 @@
|
||||
---
|
||||
title: Element-wise operations
|
||||
id: 599c333915e0ea32d04d4bec
|
||||
title: Element-wise operations
|
||||
challengeType: 5
|
||||
forumTopicId: 302252
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Implement basic element-wise matrix-matrix and scalar-matrix operations.
|
||||
<strong>Implement:</strong>
|
||||
|
||||
**Implement:**
|
||||
|
||||
<ul>
|
||||
<li>addition</li>
|
||||
<li>subtraction</li>
|
||||
@ -16,44 +18,171 @@ Implement basic element-wise matrix-matrix and scalar-matrix operations.
|
||||
<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'>
|
||||
# --hints--
|
||||
|
||||
</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]],2)</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]]);
|
||||
`operation` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof operation === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[2,4],[6,8]]`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.deepEqual(
|
||||
operation(
|
||||
'm_add',
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
],
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
]
|
||||
),
|
||||
[
|
||||
[2, 4],
|
||||
[6, 8]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`operation("s_add",[[1,2],[3,4]],2)` should return `[[3,4],[5,6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
operation(
|
||||
's_add',
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
],
|
||||
2
|
||||
),
|
||||
[
|
||||
[3, 4],
|
||||
[5, 6]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[0,0],[0,0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
operation(
|
||||
'm_sub',
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
],
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
]
|
||||
),
|
||||
[
|
||||
[0, 0],
|
||||
[0, 0]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[1,4],[9,16]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
operation(
|
||||
'm_mult',
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
],
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
]
|
||||
),
|
||||
[
|
||||
[1, 4],
|
||||
[9, 16]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[1,1],[1,1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
operation(
|
||||
'm_div',
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
],
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
]
|
||||
),
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[1,4],[27,256]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
operation(
|
||||
'm_exp',
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
],
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4]
|
||||
]
|
||||
),
|
||||
[
|
||||
[1, 4],
|
||||
[27, 256]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_add",[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])` should return `[[10,12,14,16],[18,20,22,24]]`.
|
||||
|
||||
```js
|
||||
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]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function operation(op, arr1, arr2) {
|
||||
@ -61,15 +190,7 @@ function operation(op, arr1, arr2) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function operation(op, arr1, arr2) {
|
||||
@ -89,7 +210,4 @@ function operation(op, arr1, arr2) {
|
||||
}
|
||||
return arr1;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,51 +1,95 @@
|
||||
---
|
||||
title: Emirp primes
|
||||
id: 599d0ba974141b0f508b37d5
|
||||
title: Emirp primes
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
An emirp (**prime** spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that:
|
||||
|
||||
## 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'>
|
||||
The function should accept two parameters. The first will receive `n` 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.
|
||||
|
||||
```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);
|
||||
# --hints--
|
||||
|
||||
`emirps` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof emirps === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`emirps(20,true)` should return `[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]`
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
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
|
||||
]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`emirps(1000)` should return `70529`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps(1000), 70529);
|
||||
```
|
||||
|
||||
`emirps([7700,8000],true)` should return `[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps([7700, 8000], true), [
|
||||
7717,
|
||||
7757,
|
||||
7817,
|
||||
7841,
|
||||
7867,
|
||||
7879,
|
||||
7901,
|
||||
7927,
|
||||
7949,
|
||||
7951,
|
||||
7963
|
||||
]);
|
||||
```
|
||||
|
||||
`emirps([7700,8000],true)` should return `11`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps([7700, 8000], false), 11);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function emirps(n) {
|
||||
@ -53,26 +97,18 @@ function emirps(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
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; } }
|
||||
{ if (n % (p += 4) == 0 || n % (p += 2) == 0)
|
||||
{ return false; } }
|
||||
return true;
|
||||
};
|
||||
const is_emirp = function(n) {
|
||||
@ -98,7 +134,4 @@ function emirps(num, showEmirps)
|
||||
return arr.length;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,51 +1,67 @@
|
||||
---
|
||||
title: Entropy
|
||||
id: 599d15309e88c813a40baf58
|
||||
title: Entropy
|
||||
challengeType: 5
|
||||
forumTopicId: 302254
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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)$
|
||||
|
||||
$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'>
|
||||
# --hints--
|
||||
|
||||
</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);
|
||||
`entropy` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof entropy === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`entropy("0")` should return `0`
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(entropy('0'), 0);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`entropy("01")` should return `1`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('01'), 1);
|
||||
```
|
||||
|
||||
`entropy("0123")` should return `2`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('0123'), 2);
|
||||
```
|
||||
|
||||
`entropy("01234567")` should return `3`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('01234567'), 3);
|
||||
```
|
||||
|
||||
`entropy("0123456789abcdef")` should return `4`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('0123456789abcdef'), 4);
|
||||
```
|
||||
|
||||
`entropy("1223334444")` should return `1.8464393446710154`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('1223334444'), 1.8464393446710154);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function entropy(s) {
|
||||
@ -53,19 +69,11 @@ function entropy(s) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function entropy(s) {
|
||||
// Create a dictionary of character frequencies and iterate over it.
|
||||
// Create a dictionary of character frequencies and iterate over it.
|
||||
function process(s, evaluator) {
|
||||
let h = Object.create(null),
|
||||
k;
|
||||
@ -74,7 +82,7 @@ function entropy(s) {
|
||||
if (evaluator) for (k in h) evaluator(k, h[k]);
|
||||
return h;
|
||||
}
|
||||
// Measure the entropy of a string in bits per symbol.
|
||||
// Measure the entropy of a string in bits per symbol.
|
||||
|
||||
let sum = 0,
|
||||
len = s.length;
|
||||
@ -84,7 +92,4 @@ function entropy(s) {
|
||||
});
|
||||
return sum;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,15 +1,17 @@
|
||||
---
|
||||
title: Equilibrium index
|
||||
id: 5987fd532b954e0f21b5d3f6
|
||||
title: Equilibrium index
|
||||
challengeType: 5
|
||||
forumTopicId: 302255
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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;">
|
||||
|
||||
For example, in a sequence $A$:
|
||||
|
||||
<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>
|
||||
@ -18,64 +20,76 @@ For example, in a sequence <big>$A$</big>:
|
||||
<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;">
|
||||
|
||||
`3` 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;">
|
||||
|
||||
`6` 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'>
|
||||
`7` is not an equilibrium index, because it is not a valid index of sequence $A$.
|
||||
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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'>
|
||||
`equilibrium` should be a function.
|
||||
|
||||
```js
|
||||
function equilibrium(a) {
|
||||
|
||||
}
|
||||
assert(typeof equilibrium === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`equilibrium([-7, 1, 5, 2, -4, 3, 0])` should return `[3,6]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[0]), ans[0]);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`equilibrium([2, 4, 6])` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[1]), ans[1]);
|
||||
```
|
||||
|
||||
`equilibrium([2, 9, 2])` should return `[1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[2]), ans[2]);
|
||||
```
|
||||
|
||||
`equilibrium([1, -1, 1, -1, 1, -1, 1])` should return `[0,1,2,3,4,5,6]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[3]), ans[3]);
|
||||
```
|
||||
|
||||
`equilibrium([1])` should return `[0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[4]), ans[4]);
|
||||
```
|
||||
|
||||
`equilibrium([])` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[5]), ans[5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const equilibriumTests =
|
||||
@ -89,13 +103,15 @@ const equilibriumTests =
|
||||
const ans = [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function equilibrium(a) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function equilibrium(a) {
|
||||
@ -110,7 +126,4 @@ function equilibrium(a) {
|
||||
{ if (l[i] === r[i]) e.push(i); }
|
||||
return e;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,14 +1,16 @@
|
||||
---
|
||||
title: Ethiopian multiplication
|
||||
id: 599d1566a02b571412643b84
|
||||
title: Ethiopian multiplication
|
||||
challengeType: 5
|
||||
forumTopicId: 302257
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
|
||||
<strong>Method:</strong>
|
||||
|
||||
**Method:**
|
||||
|
||||
<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>
|
||||
@ -16,37 +18,44 @@ Ethiopian multiplication is a method of multiplying integers using only addition
|
||||
<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 × 34</code>
|
||||
<pre>
|
||||
17 34
|
||||
|
||||
**For example:** `17 × 34`
|
||||
|
||||
<pre>17 34
|
||||
</pre>
|
||||
|
||||
Halving the first column:
|
||||
<pre>
|
||||
17 34
|
||||
|
||||
<pre>17 34
|
||||
8
|
||||
4
|
||||
2
|
||||
1
|
||||
</pre>
|
||||
|
||||
Doubling the second column:
|
||||
<pre>
|
||||
17 34
|
||||
|
||||
<pre>17 34
|
||||
8 68
|
||||
4 136
|
||||
2 272
|
||||
1 544
|
||||
</pre>
|
||||
|
||||
Strike-out rows whose first cell is even:
|
||||
<pre>
|
||||
17 34
|
||||
|
||||
<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
|
||||
|
||||
<!-- markdownlint-disable MD003 -->
|
||||
|
||||
<pre>17 34
|
||||
8 --
|
||||
4 ---
|
||||
2 ---
|
||||
@ -54,46 +63,65 @@ Sum the remaining numbers in the right-hand column:
|
||||
====
|
||||
578
|
||||
</pre>
|
||||
So <code>17</code> multiplied by <code>34</code>, by the Ethiopian method is <code>578</code>.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<!-- markdownlint-enable MD003 -->
|
||||
|
||||
So `17` multiplied by `34`, by the Ethiopian method is `578`.
|
||||
|
||||
# --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'>
|
||||
<!-- markdownlint-disable MD046-->
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`eth_mult` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof eth_mult === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`eth_mult(17,34)` should return `578`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(eth_mult(17, 34), 578);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`eth_mult(23,46)` should return `1058`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(23, 46), 1058);
|
||||
```
|
||||
|
||||
`eth_mult(12,27)` should return `324`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(12, 27), 324);
|
||||
```
|
||||
|
||||
`eth_mult(56,98)` should return `5488`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(56, 98), 5488);
|
||||
```
|
||||
|
||||
`eth_mult(63,74)` should return `4662`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(63, 74), 4662);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function eth_mult(a, b) {
|
||||
@ -101,15 +129,7 @@ function eth_mult(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function eth_mult(a, b) {
|
||||
@ -132,5 +152,3 @@ function eth_mult(a, b) {
|
||||
return sum + b[0];
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,99 +1,132 @@
|
||||
---
|
||||
title: Euler method
|
||||
id: 59880443fb36441083c6c20e
|
||||
title: Euler method
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --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 [the wikipedia page](<https://en.wikipedia.org/wiki/Euler method> "wp: Euler method").
|
||||
|
||||
The ODE has to be provided in the following form:
|
||||
<ul style="list-style: none;">
|
||||
|
||||
<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;">
|
||||
|
||||
<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;">
|
||||
|
||||
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;">
|
||||
|
||||
<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;">
|
||||
|
||||
<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;">
|
||||
|
||||
<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;">
|
||||
|
||||
where $h$ 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.
|
||||
|
||||
**Example: Newton's Cooling Law**
|
||||
|
||||
Newton's cooling law describes how an object of initial temperature $T(t_0) = T_0$ cools down in an environment of temperature $T_R$:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$\frac{dT(t)}{dt} = -k \, \Delta T$</big></li>
|
||||
</ul>
|
||||
|
||||
or
|
||||
<ul style="list-style: none;">
|
||||
|
||||
<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.
|
||||
|
||||
It says that the cooling rate $\\frac{dT(t)}{dt}$ of the object is proportional to the current temperature difference $\\Delta T = (T(t) - T_R)$ to the surrounding environment.
|
||||
|
||||
The analytical solution, which we will compare to the numerical approximation, is
|
||||
<ul style="list-style: none;">
|
||||
|
||||
<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'>
|
||||
# --instructions--
|
||||
|
||||
Implement a routine of Euler's method and then use it to solve the given example of Newton's cooling law 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 compare with the analytical solution.
|
||||
<strong>Initial values:</strong>
|
||||
|
||||
**Initial values:**
|
||||
|
||||
<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>
|
||||
</ul>
|
||||
|
||||
First parameter to the function is initial time, second parameter is initial temperature, third parameter is elapsed time and fourth parameter is step size.
|
||||
</section>
|
||||
|
||||
# --hints--
|
||||
|
||||
`eulersMethod` should be a function.
|
||||
|
||||
## 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, 2)</code> should return a number.
|
||||
testString: assert(typeof eulersMethod(0, 100, 100, 2) === 'number');
|
||||
- text: <code>eulersMethod(0, 100, 100, 2)</code> should return 20.0424631833732.
|
||||
testString: assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732);
|
||||
- text: <code>eulersMethod(0, 100, 100, 5)</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);
|
||||
|
||||
```js
|
||||
assert(typeof eulersMethod === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`eulersMethod(0, 100, 100, 2)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof eulersMethod(0, 100, 100, 2) === 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`eulersMethod(0, 100, 100, 2)` should return 20.0424631833732.
|
||||
|
||||
```js
|
||||
assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732);
|
||||
```
|
||||
|
||||
`eulersMethod(0, 100, 100, 5)` should return 20.01449963666907.
|
||||
|
||||
```js
|
||||
assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907);
|
||||
```
|
||||
|
||||
`eulersMethod(0, 100, 100, 10)` should return 20.000472392.
|
||||
|
||||
```js
|
||||
assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function eulersMethod(x1, y1, x2, h) {
|
||||
@ -101,15 +134,7 @@ function eulersMethod(x1, y1, x2, h) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function eulersMethod(x1, y1, x2, h) {
|
||||
@ -123,7 +148,4 @@ function eulersMethod(x1, y1, x2, h) {
|
||||
|
||||
return y;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,48 +1,59 @@
|
||||
---
|
||||
title: Evaluate binomial coefficients
|
||||
id: 598de241872ef8353c58a7a2
|
||||
title: Evaluate binomial coefficients
|
||||
challengeType: 5
|
||||
forumTopicId: 302259
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
$\\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>
|
||||
# --hints--
|
||||
|
||||
## 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);
|
||||
`binom` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof binom === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`binom(5,3)` should return 10.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.equal(binom(5, 3), 10);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`binom(7,2)` should return 21.
|
||||
|
||||
```js
|
||||
assert.equal(binom(7, 2), 21);
|
||||
```
|
||||
|
||||
`binom(10,4)` should return 210.
|
||||
|
||||
```js
|
||||
assert.equal(binom(10, 4), 210);
|
||||
```
|
||||
|
||||
`binom(6,1)` should return 6.
|
||||
|
||||
```js
|
||||
assert.equal(binom(6, 1), 6);
|
||||
```
|
||||
|
||||
`binom(12,8)` should return 495.
|
||||
|
||||
```js
|
||||
assert.equal(binom(12, 8), 495);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function binom(n, k) {
|
||||
@ -50,15 +61,7 @@ function binom(n, k) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function binom(n, k) {
|
||||
@ -67,7 +70,4 @@ function binom(n, k) {
|
||||
for (let i = 1; i <= k; i++) coeff /= i;
|
||||
return coeff;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,29 +1,36 @@
|
||||
---
|
||||
title: Execute a Markov algorithm
|
||||
id: 59e09e6d412c5939baa02d16
|
||||
title: Execute a Markov algorithm
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --description--
|
||||
|
||||
Create an interpreter for a [Markov Algorithm](<https://en.wikipedia.org/wiki/Markov algorithm> "wp: Markov algorithm").
|
||||
|
||||
Rules have the syntax:
|
||||
<pre>
|
||||
[ruleset] ::= (([comment] | [rule]) [newline]+)*
|
||||
|
||||
<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.
|
||||
|
||||
If there is a `.` (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>
|
||||
|
||||
Rulesets
|
||||
|
||||
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
|
||||
|
||||
**Ruleset 1:**
|
||||
|
||||
<pre># This rules file is extracted from Wikipedia:
|
||||
# <code>http://en.wikipedia.org/wiki/Markov_Algorithm</code>
|
||||
A -> apple
|
||||
B -> bag
|
||||
S -> shop
|
||||
@ -31,14 +38,20 @@ 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>
|
||||
|
||||
`I bought a B of As from T S.`
|
||||
|
||||
Should generate the output:
|
||||
<code>I bought a bag of apples from my brother.</code>
|
||||
<strong>Ruleset 2:</strong>
|
||||
|
||||
`I bought a bag of apples from my brother.`
|
||||
|
||||
**Ruleset 2:**
|
||||
|
||||
A test of the terminating rule
|
||||
<pre>
|
||||
# Slightly modified from the rules on Wikipedia
|
||||
|
||||
<pre># Slightly modified from the rules on Wikipedia
|
||||
A -> apple
|
||||
B -> bag
|
||||
S -> .shop
|
||||
@ -46,14 +59,20 @@ 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>
|
||||
|
||||
`I bought a B of As from T S.`
|
||||
|
||||
Should generate:
|
||||
<code>I bought a bag of apples from T shop.</code>
|
||||
<strong>Ruleset 3:</strong>
|
||||
|
||||
`I bought a bag of apples from T shop.`
|
||||
|
||||
**Ruleset 3:**
|
||||
|
||||
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
|
||||
|
||||
<pre># BNF Syntax testing rules
|
||||
A -> apple
|
||||
WWWW -> with
|
||||
Bgage -> ->.*
|
||||
@ -65,14 +84,20 @@ 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>
|
||||
|
||||
`I bought a B of As W my Bgage from T S.`
|
||||
|
||||
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
|
||||
|
||||
`I bought a bag of apples with my money from T shop.`
|
||||
|
||||
**Ruleset 4:**
|
||||
|
||||
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+
|
||||
@ -98,16 +123,24 @@ y_ -> _
|
||||
1+_ -> 1
|
||||
_+_ ->
|
||||
</pre>
|
||||
|
||||
Sample text of:
|
||||
<code>_1111*11111_</code>
|
||||
|
||||
`_1111*11111_`
|
||||
|
||||
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.
|
||||
|
||||
`11111111111111111111`
|
||||
|
||||
**Ruleset 5:**
|
||||
|
||||
A simple [Turing machine](http://en.wikipedia.org/wiki/Turing_machine "link: http://en.wikipedia.org/wiki/Turing_machine"), implementing a three-state [busy beaver](http://en.wikipedia.org/wiki/Busy_beaver "link: http://en.wikipedia.org/wiki/Busy_beaver").
|
||||
|
||||
The tape consists of `0`s and `1`s, the states are `A`, `B`, `C` and `H` (for `H`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
|
||||
|
||||
<pre># Turing machine: three-state busy beaver
|
||||
#
|
||||
# state A, symbol 0 => write 1, move right, new state B
|
||||
A0 -> 1B
|
||||
@ -126,43 +159,56 @@ B1 -> 1B
|
||||
0C1 -> H01
|
||||
1C1 -> H11
|
||||
</pre>
|
||||
|
||||
This ruleset should turn
|
||||
<code>000000A000000</code>
|
||||
|
||||
`000000A000000`
|
||||
|
||||
into
|
||||
<code>00011H1111000</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
`00011H1111000`
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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]);
|
||||
`markov` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof markov === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`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.")` should return "I bought a bag of apples from my brother.".
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.deepEqual(markov(rules[0], tests[0]), outputs[0]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`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.")` should return "I bought a bag of apples from T shop.".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[1], tests[1]), outputs[1]);
|
||||
```
|
||||
|
||||
`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.")` should return "I bought a bag of apples with my money from T shop.".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[2], tests[2]), outputs[2]);
|
||||
```
|
||||
|
||||
`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_")` should return "11111111111111111111".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[3], tests[3]), outputs[3]);
|
||||
```
|
||||
|
||||
`markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")` should return "00011H1111000".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[4], tests[4]), outputs[4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function markov(rules,test) {
|
||||
@ -170,15 +216,7 @@ function markov(rules,test) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function markov(rules,test) {
|
||||
@ -188,10 +226,10 @@ function markov(rules,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);
|
||||
let m = pattern.exec(rule);
|
||||
for (let j = 0; j < m.length; j++)
|
||||
m[j] = m[j + 1];
|
||||
captures.push(m);
|
||||
});
|
||||
|
||||
test = origTest;
|
||||
@ -211,20 +249,18 @@ function markov(rules,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"]];
|
||||
["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"];
|
||||
"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"];
|
||||
"I bought a bag of apples from T shop.",
|
||||
"I bought a bag of apples with my money from T shop.",
|
||||
"11111111111111111111",
|
||||
"00011H1111000"];
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,70 +1,68 @@
|
||||
---
|
||||
title: Execute Brain****
|
||||
id: 59e0a8df964e4540d5abe599
|
||||
title: Execute Brain****
|
||||
challengeType: 5
|
||||
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.
|
||||
# --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 [Brainf\*\*\*](https://rosettacode.org/wiki/Brainf*** "Brainf\*\*\*") 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>></code> | Move the pointer to the right |
|
||||
| <code><</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>
|
||||
| Command | Description |
|
||||
| ----------------- | ---------------------------------------------------------------------------------- |
|
||||
| <code>></code> | Move the pointer to the right |
|
||||
| <code><</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 |
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Any cell size is allowed, EOF (*E*nd-*O*-*F*ile) support is optional, as is whether you have bounded or unbounded memory.
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`brain(bye)` should return a string
|
||||
|
||||
```js
|
||||
function brain(prog) {
|
||||
|
||||
}
|
||||
assert(typeof brain(bye) === 'string');
|
||||
```
|
||||
|
||||
</div>
|
||||
`brain("++++++[>++++++++++<-]>+++++.")` should return "A"
|
||||
|
||||
### Before Test
|
||||
<div id='js-setup'>
|
||||
```js
|
||||
assert.equal(brain('++++++[>++++++++++<-]>+++++.'), 'A');
|
||||
```
|
||||
|
||||
`brain(bye)` should return `Goodbye, World!\r\n`
|
||||
|
||||
```js
|
||||
assert.equal(brain(bye), 'Goodbye, World!\r\n');
|
||||
```
|
||||
|
||||
`brain(hello)` should return `Hello World!\n`
|
||||
|
||||
```js
|
||||
assert.equal(brain(hello), 'Hello World!\n');
|
||||
```
|
||||
|
||||
`brain(fib)` should return `1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89`
|
||||
|
||||
```js
|
||||
assert.equal(brain(fib), '1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
let fib=`+
|
||||
@ -134,19 +132,20 @@ let hello='++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++
|
||||
let bye='++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.<+++++++.--------.<<<<<+.<+++.---.';
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function brain(prog) {
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function brain(prog){
|
||||
var output="";
|
||||
var code; // formatted code
|
||||
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
|
||||
@ -156,50 +155,47 @@ function brain(prog){
|
||||
|
||||
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,"&nbsp;");
|
||||
document.getElementById("output").innerHTML = s;*/
|
||||
},
|
||||
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,"&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;
|
||||
}
|
||||
}
|
||||
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++){
|
||||
for(ip=0;ip<ar.length;ip++){
|
||||
if(commands.hasOwnProperty(ar[ip]))
|
||||
commands[ar[ip]]();
|
||||
}
|
||||
commands[ar[ip]]();
|
||||
}
|
||||
|
||||
return output;
|
||||
return output;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,52 +1,92 @@
|
||||
---
|
||||
title: Extensible prime generator
|
||||
id: 598ee8b91b410510ae82efef
|
||||
title: Extensible prime generator
|
||||
challengeType: 5
|
||||
forumTopicId: 302262
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
The function should have two parameters. The first will receive `n` 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>
|
||||
# --hints--
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>primeGenerator</code> should be a function.
|
||||
testString: assert(typeof primeGenerator === 'function');
|
||||
- text: <code>primeGenerator(20, true)</code> should return <code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]</code>.
|
||||
testString: assert.deepEqual(primeGenerator(20, true), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]);
|
||||
- text: <code>primeGenerator([100, 150], true)</code> should return <code>[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]</code>.
|
||||
testString: assert.deepEqual(primeGenerator([100, 150], true), [101, 103, 107, 109, 113, 127, 131, 137, 139, 149]);
|
||||
- text: <code>primeGenerator([7700, 8000], false)</code> should return <code>30</code>.
|
||||
testString: assert.equal(primeGenerator([7700, 8000], false), 30);
|
||||
- text: <code>primeGenerator(10000, false)</code> should return <code>104729</code>.
|
||||
testString: assert.equal(primeGenerator(10000, false), 104729);
|
||||
`primeGenerator` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof primeGenerator === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`primeGenerator(20, true)` should return `[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
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
|
||||
]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`primeGenerator([100, 150], true)` should return `[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(primeGenerator([100, 150], true), [
|
||||
101,
|
||||
103,
|
||||
107,
|
||||
109,
|
||||
113,
|
||||
127,
|
||||
131,
|
||||
137,
|
||||
139,
|
||||
149
|
||||
]);
|
||||
```
|
||||
|
||||
`primeGenerator([7700, 8000], false)` should return `30`.
|
||||
|
||||
```js
|
||||
assert.equal(primeGenerator([7700, 8000], false), 30);
|
||||
```
|
||||
|
||||
`primeGenerator(10000, false)` should return `104729`.
|
||||
|
||||
```js
|
||||
assert.equal(primeGenerator(10000, false), 104729);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function primeGenerator(num, showPrimes) {
|
||||
@ -54,15 +94,7 @@ function primeGenerator(num, showPrimes) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function primeGenerator(num, showPrimes) {
|
||||
@ -103,7 +135,4 @@ function primeGenerator(num, showPrimes) {
|
||||
return arr.length;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,54 +1,63 @@
|
||||
---
|
||||
title: Factorial
|
||||
id: 597b2b2a2702b44414742771
|
||||
title: Factorial
|
||||
challengeType: 5
|
||||
forumTopicId: 302263
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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><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'>
|
||||
**Note:** `0! = 1`
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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);
|
||||
`factorial` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof factorial === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`factorial(2)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof factorial(2) === 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`factorial(3)` should return 6.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(3), 6);
|
||||
```
|
||||
|
||||
`factorial(5)` should return 120.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(5), 120);
|
||||
```
|
||||
|
||||
`factorial(10)` should return 3,628,800.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(10), 3628800);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function factorial(n) {
|
||||
@ -56,14 +65,7 @@ function factorial(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factorial(n) {
|
||||
@ -74,8 +76,4 @@ function factorial(n) {
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,24 +1,33 @@
|
||||
---
|
||||
title: Factors of a Mersenne number
|
||||
id: 598eea87e5cf4b116c3ff81a
|
||||
title: Factors of a Mersenne number
|
||||
challengeType: 5
|
||||
forumTopicId: 302264
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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>.
|
||||
|
||||
If `P` is prime, the Mersenne number may be a Mersenne prime. (If `P` 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, [Lucas-Lehmer test](<https://rosettacode.org/wiki/Lucas-Lehmer test> "Lucas-Lehmer test").
|
||||
|
||||
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
|
||||
|
||||
Remove the top bit of the exponent, and if it's 1 multiply `square` 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 `square` in the next step:
|
||||
|
||||
<pre>Remove Optional
|
||||
square top bit multiply by 2 mod 47
|
||||
------------ ------- ------------- ------
|
||||
1*1 = 1 1 0111 1*2 = 2 2
|
||||
@ -27,44 +36,63 @@ square top bit multiply by 2 mod 47
|
||||
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>
|
||||
Any factor `q` of <code>2<sup>P</sup>-1</code> must be of the form `2kP+1`, `k` being a positive integer or zero. Furthermore, `q` must be `1` or `7 mod 8`.
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
Finally any potential factor `q` must be [prime](<https://rosettacode.org/wiki/Primality by Trial Division> "Primality by Trial Division").
|
||||
|
||||
```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");
|
||||
As in other trial division algorithms, the algorithm stops when `2kP+1 > sqrt(N)`.These primarily tests only work on Mersenne numbers where `P` 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 `2kP+1`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using the above method find a factor of <code>2<sup>929</sup>-1</code> (aka M929)
|
||||
|
||||
# --hints--
|
||||
|
||||
`check_mersenne` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof check_mersenne === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`check_mersenne(3)` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof check_mersenne(3) == 'string');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`check_mersenne(3)` should return "M3 = 2^3-1 is prime".
|
||||
|
||||
```js
|
||||
assert.equal(check_mersenne(3), 'M3 = 2^3-1 is prime');
|
||||
```
|
||||
|
||||
`check_mersenne(23)` should return "M23 = 2^23-1 is composite with factor 47".
|
||||
|
||||
```js
|
||||
assert.equal(check_mersenne(23), 'M23 = 2^23-1 is composite with factor 47');
|
||||
```
|
||||
|
||||
`check_mersenne(929)` should return "M929 = 2^929-1 is composite with factor 13007
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
check_mersenne(929),
|
||||
'M929 = 2^929-1 is composite with factor 13007'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function check_mersenne(p) {
|
||||
@ -72,60 +100,48 @@ function check_mersenne(p) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```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 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 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;
|
||||
}
|
||||
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>
|
||||
|
@ -1,43 +1,51 @@
|
||||
---
|
||||
title: Factors of an integer
|
||||
id: 597f1e7fbc206f0e9ba95dc4
|
||||
title: Factors of an integer
|
||||
challengeType: 5
|
||||
forumTopicId: 302265
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
</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]);
|
||||
`factors` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof factors === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`factors(45)` should return `[1,3,5,9,15,45]`.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.deepEqual(factors(45), ans[0]);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`factors(53)` should return `[1,53]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(factors(53), ans[1]);
|
||||
```
|
||||
|
||||
`factors(64)` should return `[1,2,4,8,16,32,64]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(factors(64), ans[2]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const ans=[[1,3,5,9,15,45],[1,53],[1,2,4,8,16,32,64]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function factors(num) {
|
||||
@ -45,23 +53,7 @@ function factors(num) {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factors(num)
|
||||
@ -78,7 +70,4 @@ function factors(num)
|
||||
n_factors.sort(function(a, b){return a - b;});
|
||||
return n_factors;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,58 +1,83 @@
|
||||
---
|
||||
title: Farey sequence
|
||||
id: 59c3ec9f15068017c96eb8a3
|
||||
title: Farey sequence
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --description--
|
||||
|
||||
The [Farey sequence](<https://en.wikipedia.org/wiki/Farey sequence> "wp: Farey sequence") <code>F<sub>n</sub></code> of order `n` is the sequence of completely reduced fractions between `0` and `1` which, when in lowest terms, have denominators less than or equal to `n`, arranged in order of increasing size.
|
||||
|
||||
The *Farey sequence* is sometimes incorrectly called a *Farey series*.
|
||||
|
||||
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:
|
||||
|
||||
The Farey sequences of orders `1` to `5` 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>
|
||||
<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>
|
||||
# --instructions--
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
Write a function that returns the Farey sequence of order `n`. The function should have one parameter that is `n`. It should return the sequence as an array.
|
||||
|
||||
```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"]);
|
||||
# --hints--
|
||||
|
||||
`farey` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof farey === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`farey(3)` should return an array
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(farey(3)));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`farey(3)` should return `["1/3","1/2","2/3"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(farey(3), ['1/3', '1/2', '2/3']);
|
||||
```
|
||||
|
||||
`farey(4)` should return `["1/4","1/3","1/2","2/4","2/3","3/4"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(farey(4), ['1/4', '1/3', '1/2', '2/4', '2/3', '3/4']);
|
||||
```
|
||||
|
||||
`farey(5)` should return `["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(farey(5), [
|
||||
'1/5',
|
||||
'1/4',
|
||||
'1/3',
|
||||
'2/5',
|
||||
'1/2',
|
||||
'2/4',
|
||||
'3/5',
|
||||
'2/3',
|
||||
'3/4',
|
||||
'4/5'
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function farey(n) {
|
||||
@ -60,35 +85,24 @@ function farey(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```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;
|
||||
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>
|
||||
|
@ -1,84 +1,96 @@
|
||||
---
|
||||
title: Fibonacci n-step number sequences
|
||||
id: 598eef80ba501f1268170e1e
|
||||
title: Fibonacci n-step number sequences
|
||||
challengeType: 5
|
||||
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:
|
||||
# --description--
|
||||
|
||||
These number series are an expansion of the ordinary [Fibonacci sequence](<https://rosettacode.org/wiki/Fibonacci sequence> "Fibonacci sequence") 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.
|
||||
|
||||
For small values of $n$, [Greek numeric prefixes](<https://en.wikipedia.org/wiki/Number prefix#Greek_series> "wp: Number prefix#Greek_series") 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>
|
||||
| $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 ... |
|
||||
|
||||
## 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>
|
||||
Allied sequences can be generated where the initial values are changed: The [Lucas series](<https://en.wikipedia.org/wiki/Lucas number> "wp: Lucas number") sums the two preceding values like the fibonacci series for $n=2$ but uses $\[2, 1]$ as its initial values.
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --instructions--
|
||||
|
||||
```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]);
|
||||
Write a function to generate Fibonacci $n$-step number sequences and Lucas sequences. The first parameter will be $n$. The second parameter will be the number of elements to be returned. The third parameter will specify whether to output the Fibonacci sequence or the Lucas sequence. If the parameter is `"f"` then return the Fibonacci sequence and if it is `"l"`, then return the Lucas sequence. The sequences must be returned as an array.
|
||||
|
||||
```
|
||||
# --hints--
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
`fib_luc` should be a function.
|
||||
|
||||
```js
|
||||
function fib_luc(n, len, w) {
|
||||
|
||||
}
|
||||
assert(typeof fib_luc === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`fib_luc(2,10,"f")` should return `[1,1,2,3,5,8,13,21,34,55]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(2, 10, 'f'), ans[0]);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`fib_luc(3,15,"f")` should return `[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(3, 15, 'f'), ans[1]);
|
||||
```
|
||||
|
||||
`fib_luc(4,15,"f")` should return `[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(4, 15, 'f'), ans[2]);
|
||||
```
|
||||
|
||||
`fib_luc(2,10,"l")` should return `[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(2, 10, 'l'), ans[3]);
|
||||
```
|
||||
|
||||
`fib_luc(3,15,"l")` should return `[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(3, 15, 'l'), ans[4]);
|
||||
```
|
||||
|
||||
`fib_luc(4,15,"l")` should return `[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(4, 15, 'l'), ans[5]);
|
||||
```
|
||||
|
||||
`fib_luc(5,15,"l")` should return `[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(5, 15, 'l'), ans[6]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const ans = [[1,1,2,3,5,8,13,21,34,55],
|
||||
@ -90,32 +102,31 @@ const ans = [[1,1,2,3,5,8,13,21,34,55],
|
||||
[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]];
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```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>
|
||||
# --solutions--
|
||||
|
||||
```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);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -1,48 +1,57 @@
|
||||
---
|
||||
title: Fibonacci sequence
|
||||
id: 597f24c1dda4e70f53c79c81
|
||||
title: Fibonacci sequence
|
||||
challengeType: 5
|
||||
forumTopicId: 302268
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
</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);
|
||||
`fibonacci` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof fibonacci === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`fibonacci(2)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof fibonacci(2) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`fibonacci(3)` should return 2.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(3), 2);
|
||||
```
|
||||
|
||||
`fibonacci(5)` should return 5.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(5), 5);
|
||||
```
|
||||
|
||||
`fibonacci(10)` should return 55.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(10), 55);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fibonacci(n) {
|
||||
@ -50,15 +59,7 @@ function fibonacci(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fibonacci(n) {
|
||||
@ -70,7 +71,4 @@ function fibonacci(n) {
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,58 +1,47 @@
|
||||
---
|
||||
title: Fibonacci word
|
||||
id: 5992e222d397f00d21122931
|
||||
title: Fibonacci word
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence [as described here](https://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf):
|
||||
|
||||
<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>
|
||||
# --instructions--
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
Write a function to return the Fibonacci Words up to `n`. `n` will be provided as a parameter to the function. The function should return an array of objects. The objects should be of the form: `{ N: 1, Length: 1, Entropy: 0, Word: '1' }`.
|
||||
|
||||
```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);
|
||||
# --hints--
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
`fibWord` should be a function.
|
||||
|
||||
```js
|
||||
function fibWord(n) {
|
||||
|
||||
}
|
||||
assert(typeof fibWord === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`fibWord(5)` should return an array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(fibWord(5)));
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`fibWord(5)` should return `[{ 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" }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibWord(5), ans);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let ans=[ { N: 1, Length: 1, Entropy: 0, Word: '1' },
|
||||
@ -66,13 +55,15 @@ let ans=[ { N: 1, Length: 1, Entropy: 0, Word: '1' },
|
||||
{ N: 5, Length: 5, Entropy: 0.9709505944546688, Word: '01001' }];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function fibWord(n) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fibWord(n) {
|
||||
@ -109,24 +100,21 @@ function fibWord(n) {
|
||||
var e = entropy(w);
|
||||
|
||||
if (l <= 21) {
|
||||
o.push({
|
||||
N: i + 1,
|
||||
Length: l,
|
||||
Entropy: e,
|
||||
Word: w
|
||||
});
|
||||
o.push({
|
||||
N: i + 1,
|
||||
Length: l,
|
||||
Entropy: e,
|
||||
Word: w
|
||||
});
|
||||
} else {
|
||||
o.push({
|
||||
N: i + 1,
|
||||
Length: l,
|
||||
Entropy: e,
|
||||
Word: "..."
|
||||
});
|
||||
o.push({
|
||||
N: i + 1,
|
||||
Length: l,
|
||||
Entropy: e,
|
||||
Word: "..."
|
||||
});
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,53 +1,65 @@
|
||||
---
|
||||
title: FizzBuzz
|
||||
id: 5e9ddb06ec35240f39657419
|
||||
title: FizzBuzz
|
||||
challengeType: 5
|
||||
forumTopicId: 385370
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Write a program that generates an array of integers from 1 to 100 (inclusive). But:
|
||||
|
||||
<ul>
|
||||
<li>for multiples of 3, add <code>"Fizz"</code> to the array instead of the number</li>
|
||||
<li>for multiples of 5, add <code>"Buzz"</code> to the array instead of the number</li>
|
||||
<li>for multiples of 3 and 5, add <code>"FizzBuzz"</code> to the array instead of the number</li>
|
||||
</ul>
|
||||
|
||||
</section>
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Your program should return an array containing the results based on the rules above.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>fizzBuzz</code> should be a function.
|
||||
testString: assert(typeof fizzBuzz=='function');
|
||||
- text: <code>fizzBuzz()</code> should return an Array.
|
||||
testString: assert(Array.isArray(fizzBuzz())==true);
|
||||
- text: Numbers divisible by only 3 should return <code>"Fizz"</code>.
|
||||
testString: assert.equal(fizzBuzz()[2], "Fizz");
|
||||
- text: Numbers divisible by only 5 should return <code>"Buzz"</code>.
|
||||
testString: assert.equal(fizzBuzz()[99], "Buzz");
|
||||
- text: Numbers divisible by both 3 and 5 should return <code>"FizzBuzz"</code>.
|
||||
testString: assert.equal(fizzBuzz()[89], "FizzBuzz");
|
||||
- text: Numbers not divisible by either 3 or 5 should return the number itself.
|
||||
testString: assert.equal(fizzBuzz()[12], 13);
|
||||
`fizzBuzz` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof fizzBuzz == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`fizzBuzz()` should return an Array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(fizzBuzz()) == true);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
Numbers divisible by only 3 should return `"Fizz"`.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[2], 'Fizz');
|
||||
```
|
||||
|
||||
Numbers divisible by only 5 should return `"Buzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[99], 'Buzz');
|
||||
```
|
||||
|
||||
Numbers divisible by both 3 and 5 should return `"FizzBuzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[89], 'FizzBuzz');
|
||||
```
|
||||
|
||||
Numbers not divisible by either 3 or 5 should return the number itself.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[12], 13);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fizzBuzz() {
|
||||
@ -55,12 +67,7 @@ function fizzBuzz() {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fizzBuzz() {
|
||||
@ -82,5 +89,3 @@ function fizzBuzz() {
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,61 +1,93 @@
|
||||
---
|
||||
title: Fractran
|
||||
id: 5a7dad05be01840e1778a0d1
|
||||
title: Fractran
|
||||
challengeType: 5
|
||||
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$.
|
||||
# --description--
|
||||
|
||||
[FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN "wp: FRACTRAN") is a Turing-complete esoteric programming language invented by the mathematician [John Horton Conway](<https://en.wikipedia.org/wiki/John Horton Conway> "wp: John Horton Conway").
|
||||
|
||||
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>
|
||||
|
||||
$\\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}$
|
||||
|
||||
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:
|
||||
|
||||
$2$, $15$, $825$, $725$, $1925$, $2275$, $425$, $390$, $330$, $290$, $770$, $\\ldots$
|
||||
|
||||
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>
|
||||
|
||||
$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$
|
||||
|
||||
which are the prime powers of 2.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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 ]);
|
||||
`fractran` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof fractran == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`fractran("3/2, 1/3")` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(fractran('3/2, 1/3')));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`fractran("3/2, 1/3")` should return `[ 2, 3, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('3/2, 1/3'), [2, 3, 1]);
|
||||
```
|
||||
|
||||
`fractran("3/2, 5/3, 1/5")` should return `[ 2, 3, 5, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('3/2, 5/3, 1/5'), [2, 3, 5, 1]);
|
||||
```
|
||||
|
||||
`fractran("3/2, 6/3")` should return `[ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('3/2, 6/3'), [2, 3, 6, 9, 18, 27, 54, 81, 162, 243]);
|
||||
```
|
||||
|
||||
`fractran("2/7, 7/2")` should return `[ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('2/7, 7/2'), [2, 7, 2, 7, 2, 7, 2, 7, 2, 7]);
|
||||
```
|
||||
|
||||
`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")` should return `[ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]`.
|
||||
|
||||
```js
|
||||
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]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fractran(progStr) {
|
||||
@ -63,13 +95,7 @@ function fractran(progStr) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fractran(progStr){
|
||||
@ -109,7 +135,4 @@ function fractran(progStr){
|
||||
exec(2);
|
||||
return seq;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,61 +1,65 @@
|
||||
---
|
||||
title: Gamma function
|
||||
id: 5a23c84252665b21eecc7e76
|
||||
title: Gamma function
|
||||
challengeType: 5
|
||||
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).
|
||||
# --description--
|
||||
|
||||
Implement one algorithm (or more) to compute the [Gamma](<https://en.wikipedia.org/wiki/Gamma function>) ($\\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'>
|
||||
# --hints--
|
||||
|
||||
</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'>
|
||||
`gamma` should be a function.
|
||||
|
||||
```js
|
||||
function gamma(x) {
|
||||
|
||||
}
|
||||
assert(typeof gamma == 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`gamma(.1)` should return a number.
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
```js
|
||||
assert(typeof gamma(0.1) == 'number');
|
||||
```
|
||||
|
||||
`gamma(.1)` should return `9.513507698668736`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.1)), round(9.513507698668736));
|
||||
```
|
||||
|
||||
`gamma(.2)` should return `4.590843711998803`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.2)), round(4.590843711998803));
|
||||
```
|
||||
|
||||
`gamma(.3)` should return `2.9915689876875904`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.3)), round(2.9915689876875904));
|
||||
```
|
||||
|
||||
`gamma(.4)` should return `2.218159543757687`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.4)), round(2.218159543757687));
|
||||
```
|
||||
|
||||
`gamma(.5)` should return `1.7724538509055159`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.5)), round(1.7724538509055159));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
function round(x) {
|
||||
@ -63,13 +67,15 @@ function round(x) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function gamma(x) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gamma(x) {
|
||||
@ -94,7 +100,4 @@ function gamma(x) {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,50 +1,121 @@
|
||||
---
|
||||
title: Gaussian elimination
|
||||
id: 5a23c84252665b21eecc7e77
|
||||
title: Gaussian elimination
|
||||
challengeType: 5
|
||||
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.
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
</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 ]);
|
||||
`gaussianElimination` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof gaussianElimination == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`gaussianElimination([[1,1],[1,-1]], [5,1])` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(
|
||||
Array.isArray(
|
||||
gaussianElimination(
|
||||
[
|
||||
[1, 1],
|
||||
[1, -1]
|
||||
],
|
||||
[5, 1]
|
||||
)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`gaussianElimination([[1,1],[1,-1]], [5,1])` should return `[ 3, 2 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
gaussianElimination(
|
||||
[
|
||||
[1, 1],
|
||||
[1, -1]
|
||||
],
|
||||
[5, 1]
|
||||
),
|
||||
[3, 2]
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[2,3],[2,1]] , [8,4])` should return `[ 1, 2 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
gaussianElimination(
|
||||
[
|
||||
[2, 3],
|
||||
[2, 1]
|
||||
],
|
||||
[8, 4]
|
||||
),
|
||||
[1, 2]
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,3],[5,-2]], [14,19])` should return `[ 5, 3 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
gaussianElimination(
|
||||
[
|
||||
[1, 3],
|
||||
[5, -2]
|
||||
],
|
||||
[14, 19]
|
||||
),
|
||||
[5, 3]
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,1],[5,-1]] , [10,14])` should return `[ 4, 6 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
gaussianElimination(
|
||||
[
|
||||
[1, 1],
|
||||
[5, -1]
|
||||
],
|
||||
[10, 14]
|
||||
),
|
||||
[4, 6]
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23])` should return `[ 1, 1, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
gaussianElimination(
|
||||
[
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
[7, 8, 8]
|
||||
],
|
||||
[6, 15, 23]
|
||||
),
|
||||
[1, 1, 1]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gaussianElimination(A,b) {
|
||||
@ -52,118 +123,107 @@ function gaussianElimination(A,b) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```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
|
||||
// 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
|
||||
}
|
||||
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 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}
|
||||
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
|
||||
// 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
|
||||
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
|
||||
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)
|
||||
var lu = ludcmp(A)
|
||||
if (lu === undefined) return // Singular Matrix!
|
||||
return lubksb(lu, b)
|
||||
}
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,56 +1,153 @@
|
||||
---
|
||||
title: General FizzBuzz
|
||||
id: 5a23c84252665b21eecc7e78
|
||||
title: General FizzBuzz
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
Write a generalized version of [FizzBuzz](https://rosettacode.org/wiki/FizzBuzz) 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 first will be an array with the FizzBuzz rules. For example: `[ [3, "Fizz"] , [5, "Buzz"] ]`.
|
||||
|
||||
This indicates that `Fizz` should be printed if the number is a multiple of 3 and `Buzz` 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, `FizzBuzz` 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'>
|
||||
# --hints--
|
||||
|
||||
</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");
|
||||
`genFizzBuzz` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof genFizzBuzz == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(
|
||||
typeof genFizzBuzz(
|
||||
[
|
||||
[3, 'Fizz'],
|
||||
[5, 'Buzz']
|
||||
],
|
||||
6
|
||||
) == 'string'
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)` should return `"Fizz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Fizz'],
|
||||
[5, 'Buzz']
|
||||
],
|
||||
6
|
||||
),
|
||||
'Fizz'
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10)` should return `"Buzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Fizz'],
|
||||
[5, 'Buzz']
|
||||
],
|
||||
10
|
||||
),
|
||||
'Buzz'
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12)` should return `"Buzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Buzz'],
|
||||
[5, 'Fizz']
|
||||
],
|
||||
12
|
||||
),
|
||||
'Buzz'
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13)` should return `"13"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Buzz'],
|
||||
[5, 'Fizz']
|
||||
],
|
||||
13
|
||||
),
|
||||
'13'
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15)` should return `"BuzzFizz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Buzz'],
|
||||
[5, 'Fizz']
|
||||
],
|
||||
15
|
||||
),
|
||||
'BuzzFizz'
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15)` should return `"FizzBuzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Fizz'],
|
||||
[5, 'Buzz']
|
||||
],
|
||||
15
|
||||
),
|
||||
'FizzBuzz'
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105)` should return `"FizzBuzzBaxx"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
genFizzBuzz(
|
||||
[
|
||||
[3, 'Fizz'],
|
||||
[5, 'Buzz'],
|
||||
[7, 'Baxx']
|
||||
],
|
||||
105
|
||||
),
|
||||
'FizzBuzzBaxx'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function genFizzBuzz(rules, num) {
|
||||
@ -58,13 +155,7 @@ function genFizzBuzz(rules, num) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function genFizzBuzz(rules, num) {
|
||||
@ -80,10 +171,4 @@ function genFizzBuzz(rules, num) {
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,60 +1,61 @@
|
||||
---
|
||||
title: Generate lower case ASCII alphabet
|
||||
id: 5a23c84252665b21eecc7e7a
|
||||
title: Generate lower case ASCII alphabet
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Write a function to generate an array of lower case ASCII characters for a given range. For example, given the range `['a', 'd']`, the function should return `['a', 'b', 'c', 'd']`.
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`lascii` should be a function.
|
||||
|
||||
```js
|
||||
function lascii(cFrom, cTo) {
|
||||
|
||||
}
|
||||
assert(typeof lascii == 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`lascii("a","d")` should return an array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(lascii('a', 'd')));
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`lascii('a','d')` should return `[ 'a', 'b', 'c', 'd' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('a', 'd'), results[0]);
|
||||
```
|
||||
|
||||
`lascii('c','i')` should return `[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('c', 'i'), results[1]);
|
||||
```
|
||||
|
||||
`lascii('m','q')` should return `[ 'm', 'n', 'o', 'p', 'q' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('m', 'q'), results[2]);
|
||||
```
|
||||
|
||||
`lascii('k','n')` should return `[ 'k', 'l', 'm', 'n' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('k', 'n'), results[3]);
|
||||
```
|
||||
|
||||
`lascii('t','z')` should return `[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('t', 'z'), results[4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let results=[
|
||||
@ -66,13 +67,15 @@ let results=[
|
||||
]
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function lascii(cFrom, cTo) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function lascii(cFrom, cTo) {
|
||||
@ -92,7 +95,4 @@ function lascii(cFrom, cTo) {
|
||||
return cRange(cFrom, cTo);
|
||||
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,52 +1,73 @@
|
||||
---
|
||||
title: Generator/Exponential
|
||||
id: 5a23c84252665b21eecc7e7b
|
||||
title: Generator/Exponential
|
||||
challengeType: 5
|
||||
forumTopicId: 302275
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
# --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'>
|
||||
The function should return the \\( n^{th} \\) value of the filtered generator.
|
||||
|
||||
```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);
|
||||
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.
|
||||
|
||||
# --hints--
|
||||
|
||||
`exponentialGenerator` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof exponentialGenerator == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`exponentialGenerator()` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof exponentialGenerator(10) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`exponentialGenerator(10)` should return `144`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(10), 144);
|
||||
```
|
||||
|
||||
`exponentialGenerator(12)` should return `196`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(12), 196);
|
||||
```
|
||||
|
||||
`exponentialGenerator(14)` should return `256`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(14), 256);
|
||||
```
|
||||
|
||||
`exponentialGenerator(20)` should return `484`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(20), 484);
|
||||
```
|
||||
|
||||
`exponentialGenerator(25)` should return `784`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(25), 784);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function exponentialGenerator(n) {
|
||||
@ -54,40 +75,32 @@ function exponentialGenerator(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function exponentialGenerator(n){
|
||||
function* PowersGenerator(m) {
|
||||
var n=0;
|
||||
while(1) {
|
||||
yield Math.pow(n, m);
|
||||
n += 1;
|
||||
}
|
||||
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 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);
|
||||
@ -100,7 +113,4 @@ function exponentialGenerator(n){
|
||||
|
||||
return curr.value;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,72 +1,101 @@
|
||||
---
|
||||
title: Gray code
|
||||
id: 5a23c84252665b21eecc7e80
|
||||
title: Gray code
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
[Gray code](<https://en.wikipedia.org/wiki/Gray code>) 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 [Karnaugh maps](<https://en.wikipedia.org/wiki/Karnaugh map>) in order from left to right or top to bottom.
|
||||
|
||||
# --instructions--
|
||||
|
||||
## 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
|
||||
|
||||
<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>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>
|
||||
|
||||
<pre>b[0] = g[0]<br>
|
||||
for other bits:
|
||||
b[i] = g[i] xor b[i-1]
|
||||
</pre>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`gray` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof gray == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`gray(true,177)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof gray(true, 177) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`gray(true,177)` should return `233`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(true, 177), 233);
|
||||
```
|
||||
|
||||
`gray(true,425)` should return `381`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(true, 425), 381);
|
||||
```
|
||||
|
||||
`gray(true,870)` should return `725`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(true, 870), 725);
|
||||
```
|
||||
|
||||
`gray(false,233)` should return `177`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(false, 233), 177);
|
||||
```
|
||||
|
||||
`gray(false,381)` should return `425`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(false, 381), 425);
|
||||
```
|
||||
|
||||
`gray(false,725)` should return `870`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(false, 725), 870);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gray(enc, number) {
|
||||
@ -74,15 +103,7 @@ function gray(enc, number) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gray(enc, number){
|
||||
@ -97,7 +118,4 @@ function gray(enc, number){
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,50 +1,67 @@
|
||||
---
|
||||
title: Greatest common divisor
|
||||
id: 5a23c84252665b21eecc7e82
|
||||
title: Greatest common divisor
|
||||
challengeType: 5
|
||||
forumTopicId: 302277
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Write a function that returns the greatest common divisor of two integers.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --hints--
|
||||
|
||||
</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);
|
||||
`gcd` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof gcd == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`gcd(24,36)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof gcd(24, 36) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`gcd(24,36)` should return `12`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(24, 36), 12);
|
||||
```
|
||||
|
||||
`gcd(30,48)` should return `6`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(30, 48), 6);
|
||||
```
|
||||
|
||||
`gcd(10,15)` should return `5`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(10, 15), 5);
|
||||
```
|
||||
|
||||
`gcd(100,25)` should return `25`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(100, 25), 25);
|
||||
```
|
||||
|
||||
`gcd(13,250)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(13, 250), 1);
|
||||
```
|
||||
|
||||
`gcd(1300,250)` should return `50`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(1300, 250), 50);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gcd(a, b) {
|
||||
@ -52,21 +69,10 @@ function gcd(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gcd(a, b) {
|
||||
return b==0 ? Math.abs(a):gcd(b, a % b);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,51 +1,80 @@
|
||||
---
|
||||
title: Greatest subsequential sum
|
||||
id: 5a23c84252665b21eecc7e84
|
||||
title: Greatest subsequential sum
|
||||
challengeType: 5
|
||||
forumTopicId: 302278
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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'>
|
||||
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>
|
||||
# --hints--
|
||||
|
||||
## 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 ]);
|
||||
`maximumSubsequence` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof maximumSubsequence == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(maximumSubsequence([1, 2, -1, 3, 10, -10])));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])` should return `[ 1, 2, -1, 3, 10 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([1, 2, -1, 3, 10, -10]), [1, 2, -1, 3, 10]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 0, 8, 10, -2, -4, -1, -5, -3 ])` should return `[ 0, 8, 10 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([0, 8, 10, -2, -4, -1, -5, -3]), [
|
||||
0,
|
||||
8,
|
||||
10
|
||||
]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 9, 9, -10, 1 ])` should return `[ 9, 9 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([9, 9, -10, 1]), [9, 9]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 7, 1, -5, -3, -8, 1 ])` should return `[ 7, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([7, 1, -5, -3, -8, 1]), [7, 1]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ -3, 6, -1, 4, -4, -6 ])` should return `[ 6, -1, 4 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([-3, 6, -1, 4, -4, -6]), [6, -1, 4]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ])` should return `[ 3, 5, 6, -2, -1, 4 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]), [
|
||||
3,
|
||||
5,
|
||||
6,
|
||||
-2,
|
||||
-1,
|
||||
4
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function maximumSubsequence(population) {
|
||||
@ -53,13 +82,7 @@ function maximumSubsequence(population) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function maximumSubsequence(population) {
|
||||
@ -86,7 +109,4 @@ function maximumSubsequence(population) {
|
||||
|
||||
return greatest;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,53 +1,61 @@
|
||||
---
|
||||
title: Hailstone sequence
|
||||
id: 595608ff8bcd7a50bd490181
|
||||
title: Hailstone sequence
|
||||
challengeType: 5
|
||||
forumTopicId: 302279
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
The Hailstone sequence of numbers can be generated from a starting positive integer, <code>n</code> by:
|
||||
# --description--
|
||||
|
||||
The Hailstone sequence of numbers can be generated from a starting positive integer, `n` 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'>
|
||||
The (unproven) [Collatz conjecture](<https://en.wikipedia.org/wiki/Collatz conjecture> "wp: Collatz conjecture") 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.
|
||||
|
||||
# --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>
|
||||
|
||||
**See also:**
|
||||
|
||||
<ul>
|
||||
<li><a href="https://xkcd.com/710" target="_blank">xkcd</a> (humourous).</li>
|
||||
<li><a href='https://xkcd.com/710' target='_blank'>xkcd</a> (humourous).</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`hailstoneSequence` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof hailstoneSequence === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`hailstoneSequence()` should return `[[27,82,41,124,8,4,2,1], [351, 77031]]`
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.deepEqual(hailstoneSequence(), res);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const res = [[27, 82, 41, 124, 8, 4, 2, 1], [351, 77031]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function hailstoneSequence() {
|
||||
@ -58,23 +66,7 @@ function hailstoneSequence() {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hailstoneSequence () {
|
||||
@ -108,7 +100,4 @@ function hailstoneSequence () {
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,61 +1,103 @@
|
||||
---
|
||||
title: Happy numbers
|
||||
id: 594810f028c0303b75339ad1
|
||||
title: Happy numbers
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
A [happy number](https://en.wikipedia.org/wiki/Happy_number) 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 `1` (where it will stay), or it loops endlessly in a cycle which does not include `1`. Those numbers for which this process ends in `1` are happy numbers, while those that do not end in `1` are unhappy numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Implement a function that returns true if the number is happy, or false if not.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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));
|
||||
`happy` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof happy === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`happy(1)` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof happy(1) === 'boolean');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`happy(1)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(1));
|
||||
```
|
||||
|
||||
`happy(2)` should return false.
|
||||
|
||||
```js
|
||||
assert(!happy(2));
|
||||
```
|
||||
|
||||
`happy(7)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(7));
|
||||
```
|
||||
|
||||
`happy(10)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(10));
|
||||
```
|
||||
|
||||
`happy(13)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(13));
|
||||
```
|
||||
|
||||
`happy(19)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(19));
|
||||
```
|
||||
|
||||
`happy(23)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(23));
|
||||
```
|
||||
|
||||
`happy(28)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(28));
|
||||
```
|
||||
|
||||
`happy(31)` should return true.
|
||||
|
||||
```js
|
||||
assert(happy(31));
|
||||
```
|
||||
|
||||
`happy(32)` should return true:.
|
||||
|
||||
```js
|
||||
assert(happy(32));
|
||||
```
|
||||
|
||||
`happy(33)` should return false.
|
||||
|
||||
```js
|
||||
assert(!happy(33));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function happy(number) {
|
||||
@ -63,15 +105,7 @@ function happy(number) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function happy (number) {
|
||||
@ -91,7 +125,4 @@ function happy (number) {
|
||||
}
|
||||
return (number === 1);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,41 +1,50 @@
|
||||
---
|
||||
title: Harshad or Niven series
|
||||
id: 595668ca4cfe1af2fb9818d4
|
||||
title: Harshad or Niven series
|
||||
challengeType: 5
|
||||
forumTopicId: 302281
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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.
|
||||
|
||||
For example, `42` is a [Harshad number](https://rosettacode.org/wiki/Harshad_or_Niven_series "Harshad or Niven series") as `42` is divisible by `(4 + 2)` without remainder.
|
||||
|
||||
Assume that the series is defined as the numbers in increasing order.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`isHarshadOrNiven` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof isHarshadOrNiven === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`isHarshadOrNiven()` should return `{"firstTwenty": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],"firstOver1000": 1002}`
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert.deepEqual(isHarshadOrNiven(), res);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```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
|
||||
};
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isHarshadOrNiven() {
|
||||
@ -49,26 +58,7 @@ function isHarshadOrNiven() {
|
||||
}
|
||||
```
|
||||
|
||||
</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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isHarshadOrNiven() {
|
||||
@ -104,7 +94,4 @@ function isHarshadOrNiven() {
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,65 +1,67 @@
|
||||
---
|
||||
title: Hash from two arrays
|
||||
id: 595671d4d2cdc305f0d5b36f
|
||||
title: Hash from two arrays
|
||||
challengeType: 5
|
||||
forumTopicId: 302283
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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>
|
||||
|
||||
**Related task:**
|
||||
|
||||
<ul>
|
||||
<li><a href="https://rosettacode.org/wiki/Associative arrays/Creation" title="Associative arrays/Creation" target="_blank">Associative arrays/Creation</a></li>
|
||||
<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'>
|
||||
# --hints--
|
||||
|
||||
</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'>
|
||||
`arrToObj` should be a function.
|
||||
|
||||
```js
|
||||
function arrToObj (keys, vals) {
|
||||
|
||||
return true;
|
||||
}
|
||||
assert(typeof arrToObj === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"])` should return `{ 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[0]), res[0]);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"])` should return `{ 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[1]), res[1]);
|
||||
```
|
||||
|
||||
`arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"])` should return `{ 1: "a", 2: "b", 3: "c" }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[2]), res[2]);
|
||||
```
|
||||
|
||||
`arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5])` should return `{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[3]), res[3]);
|
||||
```
|
||||
|
||||
`arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4])` should return `{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[4]), res[4]);
|
||||
```
|
||||
|
||||
`arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])` should return `{ "a": 1, "b": 2, "c": 3 }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[5]), res[5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
@ -81,13 +83,16 @@ const res = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function arrToObj (keys, vals) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function arrToObj (keys, vals) {
|
||||
@ -97,5 +102,3 @@ function arrToObj (keys, vals) {
|
||||
}, {});
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,25 +1,28 @@
|
||||
---
|
||||
title: Hash join
|
||||
id: 5956795bc9e2c415eb244de1
|
||||
title: Hash join
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
An [inner join](https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join "wp: Join\_(SQL)#Inner_join") 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 [nested loop join](<https://en.wikipedia.org/wiki/Nested loop join> "wp: Nested loop join") algorithm, but a more scalable alternative is the [hash join](<https://en.wikipedia.org/wiki/hash join> "wp: hash join") 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>
|
||||
<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)
|
||||
|
||||
<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>
|
||||
@ -32,10 +35,8 @@ In pseudo-code, the algorithm could be expressed as follows:
|
||||
<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'>
|
||||
# --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.
|
||||
|
||||
@ -127,51 +128,35 @@ Implement the "hash join" algorithm as a function and demonstrate that it passes
|
||||
|
||||
<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|
|
||||
| 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>
|
||||
# --hints--
|
||||
|
||||
## 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'>
|
||||
`hashJoin` should be a function.
|
||||
|
||||
```js
|
||||
function hashJoin(hash1, hash2) {
|
||||
|
||||
return [];
|
||||
}
|
||||
assert(typeof hashJoin === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`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" }])` should return `[{"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"}]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(hashJoin(hash1, hash2), res);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const hash1 = [
|
||||
@ -205,13 +190,16 @@ const bench1 = [{ name: 'u2v7v', num: 1 }, { name: 'n53c8', num: 10 }, { name: '
|
||||
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>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function hashJoin(hash1, hash2) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hashJoin(hash1, hash2) {
|
||||
@ -245,8 +233,4 @@ function hashJoin(hash1, hash2) {
|
||||
|
||||
return hJoin(hash1, hash2, 'name=character');
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,67 +1,71 @@
|
||||
---
|
||||
title: Heronian triangles
|
||||
id: 595b98f8b5a2245e243aa831
|
||||
title: Heronian triangles
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
[Hero's formula](<https://en.wikipedia.org/wiki/Heron's formula> "wp: Heron's formula") for the area of a triangle given the length of its three sides `a`, `b`, and `c` is given by:
|
||||
|
||||
$A = \\sqrt{s(s-a)(s-b)(s-c)},$
|
||||
|
||||
where `s` is half the perimeter of the triangle; that is,
|
||||
|
||||
$s=\\frac{a+b+c}{2}.$
|
||||
|
||||
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.
|
||||
|
||||
An example is the triangle with sides `3, 4, 5` whose area is `6` (and whose perimeter is `12`).
|
||||
|
||||
Note that any triangle whose sides are all an integer multiple of `3, 4, 5`; such as `6, 8, 10,` will also be a Heronian triangle.
|
||||
|
||||
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'>
|
||||
of all three sides is `1` (unity).
|
||||
|
||||
This will exclude, for example, triangle `6, 8, 10.`
|
||||
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>heronianTriangle</code> should be a function.
|
||||
testString: assert(typeof heronianTriangle === 'function');
|
||||
- text: <code>heronianTriangle(10)</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(15)</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(20)</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(25)</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'>
|
||||
`heronianTriangle` should be a function.
|
||||
|
||||
```js
|
||||
function heronianTriangle(n) {
|
||||
|
||||
|
||||
return [];
|
||||
}
|
||||
assert(typeof heronianTriangle === 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`heronianTriangle(10)` should return `[[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]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[0]), res[0]);
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`heronianTriangle(15)` should return `[[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]],`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[1]), res[1]);
|
||||
```
|
||||
|
||||
`heronianTriangle(20)` should return `[[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]],`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[2]), res[2]);
|
||||
```
|
||||
|
||||
`heronianTriangle(25)` should return `[[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]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[3]), res[3]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [10, 15, 20, 25];
|
||||
@ -74,13 +78,17 @@ const res = [
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
## --seed-contents--
|
||||
|
||||
</section>
|
||||
```js
|
||||
function heronianTriangle(n) {
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function heronianTriangle(n) {
|
||||
@ -143,7 +151,4 @@ function heronianTriangle(n) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,74 +1,127 @@
|
||||
---
|
||||
title: Hofstadter Figure-Figure sequences
|
||||
id: 59622f89e4e137560018a40e
|
||||
title: Hofstadter Figure-Figure sequences
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
These two sequences of positive integers are defined as:
|
||||
|
||||
$R(1)=1\\ ;\\ S(1)=2 \\\\R(n)=R(n-1)+S(n-1), \\quad n>1.$
|
||||
|
||||
The sequence $S(n)$ is further defined as the sequence of positive integers not present in $R(n)$.
|
||||
|
||||
Sequence $R$ starts:
|
||||
|
||||
<pre>1, 3, 7, 12, 18, ...</pre>
|
||||
|
||||
Sequence $S$ starts:
|
||||
|
||||
<pre>2, 4, 5, 6, 8, ...</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create two functions named `ffr` and `ffs` that when given `n` return `R(n)` or `S(n)` respectively. (Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
|
||||
|
||||
No maximum value for `n` should be assumed.
|
||||
|
||||
**References**
|
||||
|
||||
## 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>.
|
||||
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>.
|
||||
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'>
|
||||
# --hints--
|
||||
|
||||
```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(10)</code> should return <code>69</code>
|
||||
testString: assert.equal(ffr(ffrParamRes[0][0]), ffrParamRes[0][1]);
|
||||
- text: <code>ffr(50)</code> should return <code>1509</code>
|
||||
testString: assert.equal(ffr(ffrParamRes[1][0]), ffrParamRes[1][1]);
|
||||
- text: <code>ffr(100)</code> should return <code>5764</code>
|
||||
testString: assert.equal(ffr(ffrParamRes[2][0]), ffrParamRes[2][1]);
|
||||
- text: <code>ffr(1000)</code> should return <code>526334</code>
|
||||
testString: assert.equal(ffr(ffrParamRes[3][0]), ffrParamRes[3][1]);
|
||||
- text: <code>ffs(10)</code> should return <code>14</code>
|
||||
testString: assert.equal(ffs(ffsParamRes[0][0]), ffsParamRes[0][1]);
|
||||
- text: <code>ffs(50)</code> should return <code>59</code>
|
||||
testString: assert.equal(ffs(ffsParamRes[1][0]), ffsParamRes[1][1]);
|
||||
- text: <code>ffs(100)</code> should return <code>112</code>
|
||||
testString: assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1]);
|
||||
- text: <code>ffs(1000)</code> should return <code>1041</code>
|
||||
testString: assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1]);
|
||||
`ffr` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof ffr === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`ffs` should be a function.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof ffs === 'function');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`ffr` should return integer.
|
||||
|
||||
```js
|
||||
assert(Number.isInteger(ffr(1)));
|
||||
```
|
||||
|
||||
`ffs` should return integer.
|
||||
|
||||
```js
|
||||
assert(Number.isInteger(ffs(1)));
|
||||
```
|
||||
|
||||
`ffr(10)` should return `69`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[0][0]), ffrParamRes[0][1]);
|
||||
```
|
||||
|
||||
`ffr(50)` should return `1509`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[1][0]), ffrParamRes[1][1]);
|
||||
```
|
||||
|
||||
`ffr(100)` should return `5764`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[2][0]), ffrParamRes[2][1]);
|
||||
```
|
||||
|
||||
`ffr(1000)` should return `526334`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[3][0]), ffrParamRes[3][1]);
|
||||
```
|
||||
|
||||
`ffs(10)` should return `14`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[0][0]), ffsParamRes[0][1]);
|
||||
```
|
||||
|
||||
`ffs(50)` should return `59`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[1][0]), ffsParamRes[1][1]);
|
||||
```
|
||||
|
||||
`ffs(100)` should return `112`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1]);
|
||||
```
|
||||
|
||||
`ffs(1000)` should return `1041`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const ffrParamRes = [[10, 69], [50, 1509], [100, 5764], [1000, 526334]];
|
||||
const ffsParamRes = [[10, 14], [50, 59], [100, 112], [1000, 1041]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function ffr(n) {
|
||||
@ -80,25 +133,7 @@ function ffs(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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const R = [null, 1];
|
||||
@ -127,7 +162,4 @@ function ffs (n) {
|
||||
extendSequences(n);
|
||||
return S[n];
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,48 +1,70 @@
|
||||
---
|
||||
title: Hofstadter Q sequence
|
||||
id: 59637c4d89f6786115efd814
|
||||
title: Hofstadter Q sequence
|
||||
challengeType: 5
|
||||
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>
|
||||
# --description--
|
||||
|
||||
## 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>
|
||||
The [Hofstadter Q sequence](https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence "wp: Hofstadter_sequence#Hofstadter_Q_sequence") is defined as:
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
$Q(1)=Q(2)=1, \\\\ Q(n)=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)), \\quad n>2.$
|
||||
|
||||
```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]);
|
||||
It is defined like the [Fibonacci sequence](<https://rosettacode.org/wiki/Fibonacci sequence> "Fibonacci sequence"), 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.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement the Hofstadter Q Sequence equation as a function. The function should accept number, `n`, and return an integer.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hofstadterQ` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof hofstadterQ === 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`hofstadterQ()` should return `integer`
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Number.isInteger(hofstadterQ(1000)));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`hofstadterQ(1000)` should return `502`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[0]), res[0]);
|
||||
```
|
||||
|
||||
`hofstadterQ(1500)` should return `755`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[1]), res[1]);
|
||||
```
|
||||
|
||||
`hofstadterQ(2000)` should return `1005`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[2]), res[2]);
|
||||
```
|
||||
|
||||
`hofstadterQ(2500)` should return `1261`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[3]), res[3]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCase = [1000, 1500, 2000, 2500];
|
||||
const res = [502, 755, 1005, 1261];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function hofstadterQ(n) {
|
||||
@ -51,24 +73,7 @@ function hofstadterQ(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'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hofstadterQ (n) {
|
||||
@ -83,7 +88,4 @@ function hofstadterQ (n) {
|
||||
};
|
||||
return Q(n);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,14 +1,16 @@
|
||||
---
|
||||
title: I before E except after C
|
||||
id: 5a23c84252665b21eecc7eb0
|
||||
title: I before E except after C
|
||||
challengeType: 5
|
||||
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.
|
||||
# --description--
|
||||
|
||||
The phrase ["I before E, except after C"](<https://en.wikipedia.org/wiki/I before E except after C>) 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>
|
||||
@ -17,44 +19,66 @@ Using the words provided, check if the two sub-clauses of the phrase are plausib
|
||||
<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'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`IBeforeExceptC` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof IBeforeExceptC == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`IBeforeExceptC("receive")` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof IBeforeExceptC('receive') == 'boolean');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`IBeforeExceptC("receive")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('receive'), true);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("science")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('science'), false);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("imperceivable")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('imperceivable'), true);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("inconceivable")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('inconceivable'), true);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("insufficient")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('insufficient'), false);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("omniscient")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('omniscient'), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function IBeforeExceptC(word) {
|
||||
@ -62,26 +86,15 @@ function IBeforeExceptC(word) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```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;
|
||||
if(word.indexOf("c")==-1 && word.indexOf("ie")!=-1)
|
||||
return true;
|
||||
else if(word.indexOf("cei")!=-1)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,55 +1,75 @@
|
||||
---
|
||||
title: IBAN
|
||||
id: 5a23c84252665b21eecc7eaf
|
||||
title: IBAN
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --description--
|
||||
|
||||
The [International Bank Account Number (IBAN)](https://en.wikipedia.org/wiki/International_Bank_Account_Number) is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating [transcription errors](https://en.wikipedia.org/wiki/Transcription_error).
|
||||
|
||||
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'>
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes IBAN string as parameter. If it is valid return true. Otherwise, return false.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`isValid` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof isValid == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`isValid("GB82 WEST 1234 5698 7654 32")` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof isValid('GB82 WEST 1234 5698 7654 32') == 'boolean');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`isValid("GB82 WEST 1234 5698 7654 32")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 WEST 1234 5698 7654 32'), true);
|
||||
```
|
||||
|
||||
`isValid("GB82 WEST 1.34 5698 7654 32")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 WEST 1.34 5698 7654 32'), false);
|
||||
```
|
||||
|
||||
`isValid("GB82 WEST 1234 5698 7654 325")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 WEST 1234 5698 7654 325'), false);
|
||||
```
|
||||
|
||||
`isValid("GB82 TEST 1234 5698 7654 32")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 TEST 1234 5698 7654 32'), false);
|
||||
```
|
||||
|
||||
`isValid("SA03 8000 0000 6080 1016 7519")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('SA03 8000 0000 6080 1016 7519'), true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isValid(iban) {
|
||||
@ -57,36 +77,27 @@ function isValid(iban) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```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
|
||||
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 = __helpers.removeWhiteSpace(iban)
|
||||
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
|
||||
iban = __helpers.removeWhiteSpace(iban)
|
||||
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>
|
||||
|
@ -1,61 +1,63 @@
|
||||
---
|
||||
title: Identity matrix
|
||||
id: 5a23c84252665b21eecc7eb1
|
||||
title: Identity matrix
|
||||
challengeType: 5
|
||||
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).
|
||||
# --description--
|
||||
|
||||
An *identity matrix* is a square matrix of size \\( n \\times n \\), where the diagonal elements are all `1`s (ones), and all the other elements are all `0`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>
|
||||
<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>
|
||||
# --instructions--
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
Write a function that takes a number `n` as a parameter and returns the identity matrix of order \\( n \\times n \\).
|
||||
|
||||
```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]);
|
||||
# --hints--
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
`idMatrix` should be a function.
|
||||
|
||||
```js
|
||||
function idMatrix(n) {
|
||||
|
||||
}
|
||||
assert(typeof idMatrix == 'function');
|
||||
```
|
||||
|
||||
</div>
|
||||
`idMatrix(1)` should return an array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(idMatrix(1)));
|
||||
```
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
`idMatrix(1)` should return `[ [ 1 ] ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(idMatrix(1), results[0]);
|
||||
```
|
||||
|
||||
`idMatrix(2)` should return `[ [ 1, 0 ], [ 0, 1 ] ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(idMatrix(2), results[1]);
|
||||
```
|
||||
|
||||
`idMatrix(3)` should return `[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(idMatrix(3), results[2]);
|
||||
```
|
||||
|
||||
`idMatrix(4)` should return `[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(idMatrix(4), results[3]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let results=[[ [ 1 ] ],
|
||||
@ -64,23 +66,22 @@ let results=[[ [ 1 ] ],
|
||||
[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]]
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```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>
|
||||
# --solutions--
|
||||
|
||||
```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;
|
||||
})
|
||||
});
|
||||
}
|
||||
```
|
||||
|
@ -1,54 +1,75 @@
|
||||
---
|
||||
title: Iterated digits squaring
|
||||
id: 5a23c84252665b21eecc7ec1
|
||||
title: Iterated digits squaring
|
||||
challengeType: 5
|
||||
forumTopicId: 302291
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --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
|
||||
|
||||
<pre>15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
|
||||
7 -> 49 -> 97 -> 130 -> 10 -> 1
|
||||
</pre>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`iteratedSquare` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof iteratedSquare == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`iteratedSquare(4)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof iteratedSquare(4) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`iteratedSquare(4)` should return `89`.
|
||||
|
||||
```js
|
||||
assert.equal(iteratedSquare(4), 89);
|
||||
```
|
||||
|
||||
`iteratedSquare(7)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(iteratedSquare(7), 1);
|
||||
```
|
||||
|
||||
`iteratedSquare(15)` should return `89`.
|
||||
|
||||
```js
|
||||
assert.equal(iteratedSquare(15), 89);
|
||||
```
|
||||
|
||||
`iteratedSquare(20)` should return `89`.
|
||||
|
||||
```js
|
||||
assert.equal(iteratedSquare(20), 89);
|
||||
```
|
||||
|
||||
`iteratedSquare(70)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(iteratedSquare(70), 1);
|
||||
```
|
||||
|
||||
`iteratedSquare(100)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(iteratedSquare(100), 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function iteratedSquare(n) {
|
||||
@ -56,30 +77,19 @@ function iteratedSquare(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```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;
|
||||
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>
|
||||
|
@ -1,67 +1,95 @@
|
||||
---
|
||||
title: Jaro distance
|
||||
id: 5a23c84252665b21eecc7ec2
|
||||
title: Jaro distance
|
||||
challengeType: 5
|
||||
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& & \text{if }m=0 \\\\{\frac {1}{3}}\left({\frac {m}{|s_{1}|}}+{\frac {m}{|s_{2}|}}+{\frac {m-t}{m}}\right)& & \text{otherwise}\end{cases}\end{align}
|
||||
# --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 `0` equates to no similarity and `1` is an exact match.
|
||||
|
||||
**Definition**
|
||||
|
||||
The Jaro distance \\( d_j \\) of two given strings \\(s_1\\) and \\(s_2\\) is
|
||||
|
||||
\\begin{align}d_j = \\begin{cases}0& & \\text{if }m=0 \\\\\\\\{\\frac {1}{3}}\\left({\\frac {m}{|s\_{1}|}}+{\\frac {m}{|s\_{2}|}}+{\\frac {m-t}{m}}\\right)& & \\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>
|
||||
|
||||
Two characters from \\(s_1\\) and \\(s_2\\) respectively, are considered *matching* 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 *transpositions*.
|
||||
|
||||
**Example**
|
||||
|
||||
Given the strings \\(s_1\\) *DWAYNE* and \\(s_2\\) *DUANE* 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'>
|
||||
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\\).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function a that takes two strings as parameters and returns the associated Jaro distance.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`jaro` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof jaro == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`jaro("MARTHA", "MARHTA")` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof jaro('MARTHA', 'MARHTA') == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`jaro("MARTHA", "MARHTA")` should return `0.9444444444444445`.
|
||||
|
||||
```js
|
||||
assert.equal(jaro('MARTHA', 'MARHTA'), 0.9444444444444445);
|
||||
```
|
||||
|
||||
`jaro("DIXON", "DICKSONX")` should return `0.7666666666666666`.
|
||||
|
||||
```js
|
||||
assert.equal(jaro('DIXON', 'DICKSONX'), 0.7666666666666666);
|
||||
```
|
||||
|
||||
`jaro("JELLYFISH", "SMELLYFISH")` should return `0.8962962962962964`.
|
||||
|
||||
```js
|
||||
assert.equal(jaro('JELLYFISH', 'SMELLYFISH'), 0.8962962962962964);
|
||||
```
|
||||
|
||||
`jaro("HELLOS", "CHELLO")` should return `0.888888888888889`.
|
||||
|
||||
```js
|
||||
assert.equal(jaro('HELLOS', 'CHELLO'), 0.888888888888889);
|
||||
```
|
||||
|
||||
`jaro("ABCD", "BCDA")` should return `0.8333333333333334`.
|
||||
|
||||
```js
|
||||
assert.equal(jaro('ABCD', 'BCDA'), 0.8333333333333334);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function jaro(s, t) {
|
||||
@ -69,13 +97,7 @@ function jaro(s, t) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function jaro(s, t) {
|
||||
@ -120,7 +142,4 @@ function jaro(s, t) {
|
||||
(matches / t_len) +
|
||||
((matches - transpositions / 2.0) / matches)) / 3.0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,51 +1,69 @@
|
||||
---
|
||||
title: JortSort
|
||||
id: 5a23c84252665b21eecc7ec4
|
||||
title: JortSort
|
||||
challengeType: 5
|
||||
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>.
|
||||
# --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 [JSConf](https://www.youtube.com/watch?v=pj4U_W0OFoE).
|
||||
|
||||
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'>
|
||||
# --hints--
|
||||
|
||||
</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);
|
||||
`jortsort` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof jortsort == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`jortsort([1,2,3,4,5])` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof jortsort([1, 2, 3, 4, 5]) == 'boolean');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`jortsort([1,2,3,4,5])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(jortsort([1, 2, 3, 4, 5]), true);
|
||||
```
|
||||
|
||||
`jortsort([1,2,13,4,5])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(jortsort([1, 2, 13, 4, 5]), false);
|
||||
```
|
||||
|
||||
`jortsort([12,4,51,2,4])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(jortsort([12, 4, 51, 2, 4]), false);
|
||||
```
|
||||
|
||||
`jortsort([1,2])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(jortsort([1, 2]), true);
|
||||
```
|
||||
|
||||
`jortsort([5,4,3,2,1])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(jortsort([5, 4, 3, 2, 1]), false);
|
||||
```
|
||||
|
||||
`jortsort([1,1,1,1,1])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(jortsort([1, 1, 1, 1, 1]), true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function jortsort(array) {
|
||||
@ -53,13 +71,7 @@ function jortsort(array) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function jortsort(array) {
|
||||
@ -74,7 +86,4 @@ function jortsort(array) {
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -1,55 +1,79 @@
|
||||
---
|
||||
title: Josephus problem
|
||||
id: 5a23c84252665b21eecc7ec5
|
||||
title: Josephus problem
|
||||
challengeType: 5
|
||||
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$.
|
||||
# --description--
|
||||
|
||||
[Josephus problem](<https://en.wikipedia.org/wiki/Josephus problem>) 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>).
|
||||
|
||||
Given any $n, k > 0$, 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 ($k=3$).
|
||||
|
||||
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'>
|
||||
# --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'>
|
||||
# --hints--
|
||||
|
||||
```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);
|
||||
`josephus` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof josephus == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`josephus(30,3)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof josephus(30, 3) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`josephus(30,3)` should return `29`.
|
||||
|
||||
```js
|
||||
assert.equal(josephus(30, 3), 29);
|
||||
```
|
||||
|
||||
`josephus(30,5)` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(josephus(30, 5), 3);
|
||||
```
|
||||
|
||||
`josephus(20,2)` should return `9`.
|
||||
|
||||
```js
|
||||
assert.equal(josephus(20, 2), 9);
|
||||
```
|
||||
|
||||
`josephus(17,6)` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(josephus(17, 6), 2);
|
||||
```
|
||||
|
||||
`josephus(29,4)` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(josephus(29, 4), 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function josephus(init, kill) {
|
||||
@ -57,15 +81,7 @@ function josephus(init, kill) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function josephus(init, kill) {
|
||||
@ -101,8 +117,4 @@ function josephus(init, kill) {
|
||||
|
||||
return Josephus.init(init).kill(kill)
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,56 +5,159 @@ challengeType: 5
|
||||
forumTopicId: 302295
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
<section id='description'>
|
||||
A k-d tree (short for *k*-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 *k*, the number of points in the data, *N*, should be *N* ≫ 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.
|
||||
|
||||
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'>
|
||||
# --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>
|
||||
# --hints--
|
||||
|
||||
## Tests
|
||||
`kdNN` should be a function.
|
||||
|
||||
<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]);
|
||||
```js
|
||||
assert(typeof kdNN == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(
|
||||
Array.isArray(
|
||||
kdNN(
|
||||
[
|
||||
[2, 3],
|
||||
[5, 4],
|
||||
[9, 6],
|
||||
[4, 7],
|
||||
[8, 1],
|
||||
[7, 2]
|
||||
],
|
||||
[9, 2]
|
||||
)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])` should return `[ 8, 1 ]`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.deepEqual(
|
||||
kdNN(
|
||||
[
|
||||
[2, 3],
|
||||
[5, 4],
|
||||
[9, 6],
|
||||
[4, 7],
|
||||
[8, 1],
|
||||
[7, 2]
|
||||
],
|
||||
[9, 2]
|
||||
),
|
||||
[8, 1]
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1])` should return `[ 8, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
kdNN(
|
||||
[
|
||||
[2, 3],
|
||||
[5, 4],
|
||||
[9, 6],
|
||||
[4, 7],
|
||||
[8, 1],
|
||||
[7, 2]
|
||||
],
|
||||
[7, 1]
|
||||
),
|
||||
[8, 1]
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2])` should return `[ 2, 3 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
kdNN(
|
||||
[
|
||||
[2, 3],
|
||||
[5, 4],
|
||||
[9, 6],
|
||||
[4, 7],
|
||||
[8, 1],
|
||||
[7, 2]
|
||||
],
|
||||
[3, 2]
|
||||
),
|
||||
[2, 3]
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3])` should return `[ 1, 2, 5 ]`.
|
||||
|
||||
```js
|
||||
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]
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6])` should return `[ 4, 6, 7 ]`.
|
||||
|
||||
```js
|
||||
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]
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8])` should return `[ 7, 8, 9 ]`.
|
||||
|
||||
```js
|
||||
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]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function kdNN(fpoints, fpoint) {
|
||||
@ -62,12 +165,7 @@ function kdNN(fpoints, fpoint) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function kdNN(fpoints, fpoint) {
|
||||
@ -368,5 +466,3 @@ function kdNN(fpoints, fpoint) {
|
||||
return tree.nearest(fpoint, 1, 1000)[0][0];
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,60 +5,87 @@ challengeType: 5
|
||||
forumTopicId: 302296
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
A positive integer is a [Kaprekar number](<https://en.wikipedia.org/wiki/Kaprekar number>) if:
|
||||
|
||||
<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>
|
||||
<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
|
||||
# --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
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`isKaprekar` should be a function.
|
||||
|
||||
```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);
|
||||
```js
|
||||
assert(typeof isKaprekar == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`isKaprekar(1, 10)` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof isKaprekar(1, 10) == 'boolean');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`isKaprekar(1, 10)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(1, 10), true);
|
||||
```
|
||||
|
||||
`isKaprekar(9, 10)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(9, 10), true);
|
||||
```
|
||||
|
||||
`isKaprekar(2223, 10)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(2223, 10), true);
|
||||
```
|
||||
|
||||
`isKaprekar(22823, 10)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(22823, 10), false);
|
||||
```
|
||||
|
||||
`isKaprekar(9, 17)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(9, 17), false);
|
||||
```
|
||||
|
||||
`isKaprekar(225, 17)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(225, 17), true);
|
||||
```
|
||||
|
||||
`isKaprekar(999, 17)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(999, 17), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isKaprekar(n, bs) {
|
||||
@ -66,12 +93,7 @@ function isKaprekar(n, bs) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isKaprekar(n, bs) {
|
||||
@ -85,5 +107,3 @@ function isKaprekar(n, bs) {
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,45 +5,143 @@ challengeType: 5
|
||||
forumTopicId: 323649
|
||||
---
|
||||
|
||||
## Description
|
||||
# --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
|
||||
# --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>
|
||||
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.
|
||||
|
||||
## Tests
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`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)` should return `405`.
|
||||
|
||||
```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);
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
</section>
|
||||
`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)` should return `510`.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`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)` should return `145`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `185`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `237`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `317`.'
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function knapsack(items, maxweight) {
|
||||
@ -51,12 +149,7 @@ function knapsack(items, maxweight) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function knapsack(items, maxweight) {
|
||||
@ -159,5 +252,3 @@ function knapsack(items, maxweight) {
|
||||
return val;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,43 +5,151 @@ challengeType: 5
|
||||
forumTopicId: 323652
|
||||
---
|
||||
|
||||
## Description
|
||||
# --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
|
||||
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 `pieces` times.
|
||||
|
||||
# --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
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`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)` should return `755`.
|
||||
|
||||
```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);
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
</section>
|
||||
`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)` should return `875`.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`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)` should return `1015`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `1120`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `1225`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findBestPack(data, maxweight) {
|
||||
@ -49,12 +157,7 @@ function findBestPack(data, maxweight) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findBestPack(data, maxweight) {
|
||||
@ -106,5 +209,3 @@ function findBestPack(data, maxweight) {
|
||||
return val;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,43 +5,131 @@ challengeType: 5
|
||||
forumTopicId: 323654
|
||||
---
|
||||
|
||||
## Description
|
||||
# --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
|
||||
# --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
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`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)` should return `257.875`.
|
||||
|
||||
```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);
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
</section>
|
||||
`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)` should return `295.05405405405406`.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`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)` should return `349.3783783783784`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `459.5263157894737`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `478.4736842105263`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function knapContinuous(items, maxweight) {
|
||||
@ -49,12 +137,7 @@ function knapContinuous(items, maxweight) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function knapContinuous(items, maxweight) {
|
||||
@ -83,5 +166,3 @@ function knapContinuous(items, maxweight) {
|
||||
return val;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,45 +5,110 @@ challengeType: 5
|
||||
forumTopicId: 323655
|
||||
---
|
||||
|
||||
## Description
|
||||
# --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.
|
||||
|
||||
<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
|
||||
# --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
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`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)` should return `54500`.
|
||||
|
||||
```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);
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
</section>
|
||||
`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)` should return `88400`.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`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)` should return `42500`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `75300`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
`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)` should return `43200`.
|
||||
|
||||
```js
|
||||
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
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function knapsackUnbounded(items, maxweight, maxvolume) {
|
||||
@ -51,12 +116,7 @@ function knapsackUnbounded(items, maxweight, maxvolume) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function knapsackUnbounded(items, maxweight, maxvolume) {
|
||||
@ -92,5 +152,3 @@ function knapsackUnbounded(items, maxweight, maxvolume) {
|
||||
return best_value;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,46 +5,61 @@ challengeType: 5
|
||||
forumTopicId: 302297
|
||||
---
|
||||
|
||||
## Description
|
||||
# --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>
|
||||
[Knight's Tour](https://en.wikipedia.org/wiki/Knight%27s_tour)Problem: You have an empty `w` \* `h` 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 *not* a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.
|
||||
|
||||
## Instructions
|
||||
# --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>
|
||||
Write a function that takes `w` and `h` as parameters and returns the number of initial positions from where it is possible to achieve the task stated above.
|
||||
|
||||
## Tests
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`knightTour` should be a function.
|
||||
|
||||
```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);
|
||||
```js
|
||||
assert(typeof knightTour == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`knightTour(6, 6)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof knightTour(6, 6) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`knightTour(6, 6)` should return `35`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(6, 6), 35);
|
||||
```
|
||||
|
||||
`knightTour(5, 6)` should return `20`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(5, 6), 20);
|
||||
```
|
||||
|
||||
`knightTour(4, 6)` should return `10`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(4, 6), 10);
|
||||
```
|
||||
|
||||
`knightTour(7, 3)` should return `4`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(7, 3), 4);
|
||||
```
|
||||
|
||||
`knightTour(8, 6)` should return `47`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(8, 6), 47);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function knightTour(w, h) {
|
||||
@ -52,12 +67,7 @@ function knightTour(w, h) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function knightTour(w, h) {
|
||||
@ -141,5 +151,3 @@ function knightTour(w, h) {
|
||||
return cnt;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,49 +5,57 @@ challengeType: 5
|
||||
forumTopicId: 302298
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<section id='description'>
|
||||
# --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>
|
||||
# --hints--
|
||||
|
||||
## Instructions
|
||||
`maxCombine` should be a function.
|
||||
|
||||
<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);
|
||||
```js
|
||||
assert(typeof maxCombine == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`maxCombine([1, 3, 3, 4, 55])` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof maxCombine([1, 3, 3, 4, 55]) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`maxCombine([1, 3, 3, 4, 55])` should return `554331`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(maxCombine([1, 3, 3, 4, 55]), 554331);
|
||||
```
|
||||
|
||||
`maxCombine([71, 45, 23, 4, 5])` should return `71545423`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([71, 45, 23, 4, 5]), 71545423);
|
||||
```
|
||||
|
||||
`maxCombine([14, 43, 53, 114, 55])` should return `55534314114`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([14, 43, 53, 114, 55]), 55534314114);
|
||||
```
|
||||
|
||||
`maxCombine([1, 34, 3, 98, 9, 76, 45, 4])` should return `998764543431`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([1, 34, 3, 98, 9, 76, 45, 4]), 998764543431);
|
||||
```
|
||||
|
||||
`maxCombine([54, 546, 548, 60])` should return `6054854654`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([54, 546, 548, 60]), 6054854654);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function maxCombine(xs) {
|
||||
@ -55,12 +63,7 @@ function maxCombine(xs) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function maxCombine(xs) {
|
||||
@ -79,5 +82,3 @@ function maxCombine(xs) {
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,55 +5,75 @@ challengeType: 5
|
||||
forumTopicId: 302299
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Write a function that returns the date of the last Friday of a given month for a given year.
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## Instructions
|
||||
`lastFriday` should be a function.
|
||||
|
||||
<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);
|
||||
```js
|
||||
assert(typeof lastFriday == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`lastFriday(2018, 1)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof lastFriday(2018, 1) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`lastFriday(2018, 1)` should return `26`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(lastFriday(2018, 1), 26);
|
||||
```
|
||||
|
||||
`lastFriday(2017, 2)` should return `24`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2017, 2), 24);
|
||||
```
|
||||
|
||||
`lastFriday(2012, 3)` should return `30`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2012, 3), 30);
|
||||
```
|
||||
|
||||
`lastFriday(1900, 4)` should return `27`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(1900, 4), 27);
|
||||
```
|
||||
|
||||
`lastFriday(2000, 5)` should return `26`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2000, 5), 26);
|
||||
```
|
||||
|
||||
`lastFriday(2006, 6)` should return `30`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2006, 6), 30);
|
||||
```
|
||||
|
||||
`lastFriday(2010, 7)` should return `30`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2010, 7), 30);
|
||||
```
|
||||
|
||||
`lastFriday(2005, 8)` should return `26`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2005, 8), 26);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function lastFriday(year, month) {
|
||||
@ -61,12 +81,7 @@ function lastFriday(year, month) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function lastFriday(year, month) {
|
||||
@ -81,5 +96,3 @@ function lastFriday(year, month) {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,51 +5,138 @@ challengeType: 5
|
||||
forumTopicId: 385256
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game.
|
||||
|
||||
For example, with "animals" as the category,
|
||||
<pre>
|
||||
Child 1: dog
|
||||
|
||||
<pre>Child 1: dog
|
||||
Child 2: goldfish
|
||||
Child 1: hippopotamus
|
||||
Child 2: snake
|
||||
...
|
||||
</pre>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an input array of words. The function should return an array of words where the first letter of each word is the same as the last letter of the previous word. Only use the words in the input array, and once a word is used it cannot be repeated. The words in the return array should be selected and sequenced so that that its length is maximized.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>findLongestChain</code> should be a function.
|
||||
testString: assert(typeof findLongestChain == 'function');
|
||||
- text: <code>findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])</code> should return an array.
|
||||
testString: assert(Array.isArray(findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])));
|
||||
- text: <code>findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])</code> should return <code>["involves", "starting", "game", "each"]</code>.
|
||||
testString: assert.deepEqual(findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"]), ['involves', 'starting', 'game', 'each']);
|
||||
- text: <code>findLongestChain(["audino", "bagon", "kangaskhan", "banette", "bidoof", "braviary", "exeggcute", "yamask"])</code> should return <code>["braviary", "yamask", "kangaskhan"]</code>
|
||||
testString: assert.deepEqual(findLongestChain(["audino", "bagon", "kangaskhan", "banette", "bidoof", "braviary", "exeggcute", "yamask"]), ['braviary', 'yamask', 'kangaskhan']);
|
||||
- text: <code>findLongestChain(["harp", "poliwrath", "poochyena", "porygon2", "porygonz", "archana"])</code> should return <code>["poliwrath", "harp", "poochyena", "archana"]</code>.
|
||||
testString: assert.deepEqual(findLongestChain(["harp", "poliwrath", "poochyena", "porygon2", "porygonz", "archana"]), ['poliwrath', 'harp', 'poochyena', 'archana']);
|
||||
- text: <code>findLongestChain(["scolipede", "elephant", "zeaking", "sealeo", "silcoon", "tigers"])</code> should return <code>["scolipede", "elephant", "tigers", "sealeo"]</code>.
|
||||
testString: assert.deepEqual(findLongestChain(["scolipede", "elephant", "zeaking", "sealeo", "silcoon", "tigers"]), ['scolipede', 'elephant', 'tigers', 'sealeo']);
|
||||
- text: <code>findLongestChain(["loudred", "lumineon", "lunatone", "machamp", "magnezone", "nosepass", "petilil", "pidgeotto", "pikachu"])</code> should return <code>["machamp", "petilil", "lumineon", "nosepass"]</code>.
|
||||
testString: assert.deepEqual(findLongestChain(["loudred", "lumineon", "lunatone", "machamp", "magnezone", "nosepass", "petilil", "pidgeotto", "pikachu"]), ['machamp', 'petilil', 'lumineon', 'nosepass']);
|
||||
`findLongestChain` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof findLongestChain == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(
|
||||
Array.isArray(
|
||||
findLongestChain([
|
||||
'certain',
|
||||
'each',
|
||||
'game',
|
||||
'involves',
|
||||
'starting',
|
||||
'with',
|
||||
'word'
|
||||
])
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])` should return `["involves", "starting", "game", "each"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
findLongestChain([
|
||||
'certain',
|
||||
'each',
|
||||
'game',
|
||||
'involves',
|
||||
'starting',
|
||||
'with',
|
||||
'word'
|
||||
]),
|
||||
['involves', 'starting', 'game', 'each']
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["audino", "bagon", "kangaskhan", "banette", "bidoof", "braviary", "exeggcute", "yamask"])` should return `["braviary", "yamask", "kangaskhan"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
findLongestChain([
|
||||
'audino',
|
||||
'bagon',
|
||||
'kangaskhan',
|
||||
'banette',
|
||||
'bidoof',
|
||||
'braviary',
|
||||
'exeggcute',
|
||||
'yamask'
|
||||
]),
|
||||
['braviary', 'yamask', 'kangaskhan']
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["harp", "poliwrath", "poochyena", "porygon2", "porygonz", "archana"])` should return `["poliwrath", "harp", "poochyena", "archana"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
findLongestChain([
|
||||
'harp',
|
||||
'poliwrath',
|
||||
'poochyena',
|
||||
'porygon2',
|
||||
'porygonz',
|
||||
'archana'
|
||||
]),
|
||||
['poliwrath', 'harp', 'poochyena', 'archana']
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["scolipede", "elephant", "zeaking", "sealeo", "silcoon", "tigers"])` should return `["scolipede", "elephant", "tigers", "sealeo"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
findLongestChain([
|
||||
'scolipede',
|
||||
'elephant',
|
||||
'zeaking',
|
||||
'sealeo',
|
||||
'silcoon',
|
||||
'tigers'
|
||||
]),
|
||||
['scolipede', 'elephant', 'tigers', 'sealeo']
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["loudred", "lumineon", "lunatone", "machamp", "magnezone", "nosepass", "petilil", "pidgeotto", "pikachu"])` should return `["machamp", "petilil", "lumineon", "nosepass"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
findLongestChain([
|
||||
'loudred',
|
||||
'lumineon',
|
||||
'lunatone',
|
||||
'machamp',
|
||||
'magnezone',
|
||||
'nosepass',
|
||||
'petilil',
|
||||
'pidgeotto',
|
||||
'pikachu'
|
||||
]),
|
||||
['machamp', 'petilil', 'lumineon', 'nosepass']
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findLongestChain(items) {
|
||||
@ -57,12 +144,7 @@ function findLongestChain(items) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findLongestChain(items) {
|
||||
@ -126,5 +208,3 @@ function findLongestChain(items) {
|
||||
return longest_path;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,51 +5,63 @@ challengeType: 5
|
||||
forumTopicId: 302300
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Determine whether a given year is a leap year in the Gregorian calendar.
|
||||
|
||||
</section>
|
||||
# --hints--
|
||||
|
||||
## Instructions
|
||||
`isLeapYear` should be a function.
|
||||
|
||||
<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);
|
||||
```js
|
||||
assert(typeof isLeapYear == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`isLeapYear()` should return a boolean.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof isLeapYear(2018) == 'boolean');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`isLeapYear(2018)` should return `false`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(isLeapYear(2018), false);
|
||||
```
|
||||
|
||||
`isLeapYear(2016)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(2016), true);
|
||||
```
|
||||
|
||||
`isLeapYear(2000)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(2000), true);
|
||||
```
|
||||
|
||||
`isLeapYear(1900)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(1900), false);
|
||||
```
|
||||
|
||||
`isLeapYear(1996)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(1996), true);
|
||||
```
|
||||
|
||||
`isLeapYear(1800)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(1800), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isLeapYear(year) {
|
||||
@ -57,17 +69,10 @@ function isLeapYear(year) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isLeapYear(year) {
|
||||
return year % 100 === 0 ? year % 400 === 0 : year % 4 === 0;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,55 +5,61 @@ challengeType: 5
|
||||
forumTopicId: 302301
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
<section id='description'>
|
||||
The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either *m* or *n* is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of *m*, until you find one that is also a multiple of *n*. If you already have *gcd* for [greatest common divisor](<https://rosettacode.org/wiki/greatest common divisor>), then this formula calculates *lcm*. ( \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)} )
|
||||
|
||||
The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 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)} \)
|
||||
# --instructions--
|
||||
|
||||
</section>
|
||||
Compute the least common multiple of an array of integers. Given *m* and *n*, the least common multiple is the smallest positive integer that has both *m* and *n* as factors.
|
||||
|
||||
## Instructions
|
||||
# --hints--
|
||||
|
||||
<section id='instructions'>
|
||||
`LCM` should be a function.
|
||||
|
||||
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);
|
||||
```js
|
||||
assert(typeof LCM == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`LCM([2, 4, 8])` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof LCM([2, 4, 8]) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
`LCM([2, 4, 8])` should return `8`.
|
||||
|
||||
<div id='js-seed'>
|
||||
```js
|
||||
assert.equal(LCM([2, 4, 8]), 8);
|
||||
```
|
||||
|
||||
`LCM([4, 8, 12])` should return `24`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([4, 8, 12]), 24);
|
||||
```
|
||||
|
||||
`LCM([3, 4, 5, 12, 40])` should return `120`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([3, 4, 5, 12, 40]), 120);
|
||||
```
|
||||
|
||||
`LCM([11, 33, 90])` should return `990`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([11, 33, 90]), 990);
|
||||
```
|
||||
|
||||
`LCM([-50, 25, -45, -18, 90, 447])` should return `67050`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([-50, 25, -45, -18, 90, 447]), 67050);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function LCM(A) {
|
||||
@ -61,12 +67,7 @@ function LCM(A) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function LCM(A) {
|
||||
@ -83,5 +84,3 @@ function LCM(A) {
|
||||
return a;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,58 +5,85 @@ challengeType: 5
|
||||
forumTopicId: 302302
|
||||
---
|
||||
|
||||
## Description
|
||||
# --description--
|
||||
|
||||
**Left factorials**, $ !n $, may refer to either *subfactorials* or to *factorial sums*. The same notation can be confusingly seen used for the two different definitions. Sometimes, *subfactorials* (also known as *derangements*) may use any of the notations:
|
||||
|
||||
<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! $
|
||||
|
||||
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This task will be using this formula for **left factorial**:
|
||||
|
||||
$ !n = \\sum\_{k=0}^{n-1} k! $
|
||||
|
||||
where $!0 = 0$
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
# --instructions--
|
||||
|
||||
<section id='instructions'>
|
||||
Write a function to calculate the left factorial of a given number.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
# --hints--
|
||||
|
||||
<section id='tests'>
|
||||
`leftFactorial` should be a function.
|
||||
|
||||
```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);
|
||||
```js
|
||||
assert(typeof leftFactorial == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`leftFactorial(0)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
```js
|
||||
assert(typeof leftFactorial(0) == 'number');
|
||||
```
|
||||
|
||||
<section id='challengeSeed'>
|
||||
<div id='js-seed'>
|
||||
`leftFactorial(0)` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(0), 0);
|
||||
```
|
||||
|
||||
`leftFactorial(1)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(1), 1);
|
||||
```
|
||||
|
||||
`leftFactorial(2)` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(2), 2);
|
||||
```
|
||||
|
||||
`leftFactorial(3)` should return `4`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(3), 4);
|
||||
```
|
||||
|
||||
`leftFactorial(10)` should return `409114`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(10), 409114);
|
||||
```
|
||||
|
||||
`leftFactorial(17)` should return `22324392524314`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(17), 22324392524314);
|
||||
```
|
||||
|
||||
`leftFactorial(19)` should return `6780385526348314`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(19), 6780385526348314);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function leftFactorial(n) {
|
||||
@ -64,12 +91,7 @@ function leftFactorial(n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function leftFactorial(n) {
|
||||
@ -90,5 +112,3 @@ function leftFactorial(n) {
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,48 +5,180 @@ challengeType: 5
|
||||
forumTopicId: 385263
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Given a string, calculate the frequency of each character.
|
||||
|
||||
All characters should be counted. This includes lower and upper case letters, digits, whitespace, special characters, or any other distinct characters.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Write a function to count the occurrences of each character in a given string.
|
||||
The function should return a 2D array with each of the elements in the following form: <code>['char', freq]</code>. The character should be a string with a length of 1, and frequency is a number denoting the count.
|
||||
For example, given the string "ab", your function should return <code>[['a', 1], ['b', 1]]</code>.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
The function should return a 2D array with each of the elements in the following form: `['char', freq]`. The character should be a string with a length of 1, and frequency is a number denoting the count.
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>letterFrequency</code> should be a function.
|
||||
testString: assert(typeof letterFrequency == 'function');
|
||||
- text: <code>letterFrequency("Not all that Mrs. Bennet, however")</code> should return an array.
|
||||
testString: assert(Array.isArray(letterFrequency("Not all that Mrs. Bennet, however")));
|
||||
- text: <code>letterFrequency("Not all that Mrs. Bennet, however")</code> should return <code>[[" ", 5], [", ", 1], [".", 1], ["B", 1], ["M", 1], ["N", 1], ["a", 2], ["e", 4], ["h", 2], ["l", 2], ["n", 2], ["o", 2], ["r", 2], ["s", 1], ["t", 4], ["v", 1], ["w", 1]]</code>.
|
||||
testString: assert.deepEqual(letterFrequency("Not all that Mrs. Bennet, however"), [[' ', 5], [',', 1], ['.', 1], ['B', 1], ['M', 1], ['N', 1], ['a', 2], ['e', 4], ['h', 2], ['l', 2], ['n', 2], ['o', 2], ['r', 2], ['s', 1], ['t', 4], ['v', 1], ['w', 1]]);
|
||||
- text: <code>letterFrequency("daughters, could ask on the ")</code> should return <code>[[' ',5],[',',1],['a',2],['c',1],['d',2],['e',2],['g',1],['h',2],['k',1],['l',1],['n',1],['o',2],['r',1],['s',2],['t',2],['u',2]]</code>.
|
||||
testString: assert.deepEqual(letterFrequency("daughters, could ask on the "), [[' ', 5], [',', 1], ['a', 2], ['c', 1], ['d', 2], ['e', 2], ['g', 1], ['h', 2], ['k', 1], ['l', 1], ['n', 1], ['o', 2], ['r', 1], ['s', 2], ['t', 2], ['u', 2]]);
|
||||
- text: <code>letterFrequency("husband any satisfactory description")</code> should return <code>[[" ", 3], ["a", 4], ["b", 1], ["c", 2], ["d", 2], ["e", 1], ["f", 1], ["h", 1], ["i", 3], ["n", 3], ["o", 2], ["p", 1], ["r", 2], ["s", 4], ["t", 3], ["u", 1], ["y", 2]]</code>.
|
||||
testString: assert.deepEqual(letterFrequency("husband any satisfactory description"), [[' ', 3], ['a', 4], ['b', 1], ['c', 2], ['d', 2], ['e', 1], ['f', 1], ['h', 1], ['i', 3], ['n', 3], ['o', 2], ['p', 1], ['r', 2], ['s', 4], ['t', 3], ['u', 1], ['y', 2]]);
|
||||
- text: <code>letterFrequency("in various ways--with barefaced")</code> should return <code>[[" ", 3], ["-", 2], ["a", 4], ["b", 1], ["c", 1], ["d", 1], ["e", 2], ["f", 1], ["h", 1], ["i", 3], ["n", 1], ["o", 1], ["r", 2], ["s", 2], ["t", 1], ["u", 1], ["v", 1], ["w", 2], ["y", 1]]</code>.
|
||||
testString: assert.deepEqual(letterFrequency("in various ways--with barefaced"), [[' ', 3], ['-', 2], ['a', 4], ['b', 1], ['c', 1], ['d', 1], ['e', 2], ['f', 1], ['h', 1], ['i', 3], ['n', 1], ['o', 1], ['r', 2], ['s', 2], ['t', 1], ['u', 1], ['v', 1], ['w', 2], ['y', 1]]);
|
||||
- text: <code>letterFrequency("distant surmises; but he eluded")</code> should return <code>[[" ", 4], ["; ", 1], ["a", 1], ["b", 1], ["d", 3], ["e", 4], ["h", 1], ["i", 2], ["l", 1], ["m", 1], ["n", 1], ["r", 1], ["s", 4], ["t", 3], ["u", 3]]</code>.
|
||||
testString: assert.deepEqual(letterFrequency("distant surmises; but he eluded"), [[' ', 4], [';', 1], ['a', 1], ['b', 1], ['d', 3], ['e', 4], ['h', 1], ['i', 2], ['l', 1], ['m', 1], ['n', 1], ['r', 1], ['s', 4], ['t', 3], ['u', 3]]);
|
||||
- text: <code>letterFrequency("last obliged to accept the second-hand,")</code> should return <code>[[" ", 5], [", ", 1], ["-", 1], ["a", 3], ["b", 1], ["c", 3], ["d", 3], ["e", 4], ["g", 1], ["h", 2], ["i", 1], ["l", 2], ["n", 2], ["o", 3], ["p", 1], ["s", 2], ["t", 4]]</code>.
|
||||
testString: assert.deepEqual(letterFrequency("last obliged to accept the second-hand,"), [[' ', 5], [',', 1], ['-', 1], ['a', 3], ['b', 1], ['c', 3], ['d', 3], ['e', 4], ['g', 1], ['h', 2], ['i', 1], ['l', 2], ['n', 2], ['o', 3], ['p', 1], ['s', 2], ['t', 4]]);
|
||||
For example, given the string "ab", your function should return `[['a', 1], ['b', 1]]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`letterFrequency` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof letterFrequency == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`letterFrequency("Not all that Mrs. Bennet, however")` should return an array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(letterFrequency('Not all that Mrs. Bennet, however')));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`letterFrequency("Not all that Mrs. Bennet, however")` should return `[[" ", 5], [", ", 1], [".", 1], ["B", 1], ["M", 1], ["N", 1], ["a", 2], ["e", 4], ["h", 2], ["l", 2], ["n", 2], ["o", 2], ["r", 2], ["s", 1], ["t", 4], ["v", 1], ["w", 1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('Not all that Mrs. Bennet, however'), [
|
||||
[' ', 5],
|
||||
[',', 1],
|
||||
['.', 1],
|
||||
['B', 1],
|
||||
['M', 1],
|
||||
['N', 1],
|
||||
['a', 2],
|
||||
['e', 4],
|
||||
['h', 2],
|
||||
['l', 2],
|
||||
['n', 2],
|
||||
['o', 2],
|
||||
['r', 2],
|
||||
['s', 1],
|
||||
['t', 4],
|
||||
['v', 1],
|
||||
['w', 1]
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("daughters, could ask on the ")` should return `[[' ',5],[',',1],['a',2],['c',1],['d',2],['e',2],['g',1],['h',2],['k',1],['l',1],['n',1],['o',2],['r',1],['s',2],['t',2],['u',2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('daughters, could ask on the '), [
|
||||
[' ', 5],
|
||||
[',', 1],
|
||||
['a', 2],
|
||||
['c', 1],
|
||||
['d', 2],
|
||||
['e', 2],
|
||||
['g', 1],
|
||||
['h', 2],
|
||||
['k', 1],
|
||||
['l', 1],
|
||||
['n', 1],
|
||||
['o', 2],
|
||||
['r', 1],
|
||||
['s', 2],
|
||||
['t', 2],
|
||||
['u', 2]
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("husband any satisfactory description")` should return `[[" ", 3], ["a", 4], ["b", 1], ["c", 2], ["d", 2], ["e", 1], ["f", 1], ["h", 1], ["i", 3], ["n", 3], ["o", 2], ["p", 1], ["r", 2], ["s", 4], ["t", 3], ["u", 1], ["y", 2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('husband any satisfactory description'), [
|
||||
[' ', 3],
|
||||
['a', 4],
|
||||
['b', 1],
|
||||
['c', 2],
|
||||
['d', 2],
|
||||
['e', 1],
|
||||
['f', 1],
|
||||
['h', 1],
|
||||
['i', 3],
|
||||
['n', 3],
|
||||
['o', 2],
|
||||
['p', 1],
|
||||
['r', 2],
|
||||
['s', 4],
|
||||
['t', 3],
|
||||
['u', 1],
|
||||
['y', 2]
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("in various ways--with barefaced")` should return `[[" ", 3], ["-", 2], ["a", 4], ["b", 1], ["c", 1], ["d", 1], ["e", 2], ["f", 1], ["h", 1], ["i", 3], ["n", 1], ["o", 1], ["r", 2], ["s", 2], ["t", 1], ["u", 1], ["v", 1], ["w", 2], ["y", 1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('in various ways--with barefaced'), [
|
||||
[' ', 3],
|
||||
['-', 2],
|
||||
['a', 4],
|
||||
['b', 1],
|
||||
['c', 1],
|
||||
['d', 1],
|
||||
['e', 2],
|
||||
['f', 1],
|
||||
['h', 1],
|
||||
['i', 3],
|
||||
['n', 1],
|
||||
['o', 1],
|
||||
['r', 2],
|
||||
['s', 2],
|
||||
['t', 1],
|
||||
['u', 1],
|
||||
['v', 1],
|
||||
['w', 2],
|
||||
['y', 1]
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("distant surmises; but he eluded")` should return `[[" ", 4], ["; ", 1], ["a", 1], ["b", 1], ["d", 3], ["e", 4], ["h", 1], ["i", 2], ["l", 1], ["m", 1], ["n", 1], ["r", 1], ["s", 4], ["t", 3], ["u", 3]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('distant surmises; but he eluded'), [
|
||||
[' ', 4],
|
||||
[';', 1],
|
||||
['a', 1],
|
||||
['b', 1],
|
||||
['d', 3],
|
||||
['e', 4],
|
||||
['h', 1],
|
||||
['i', 2],
|
||||
['l', 1],
|
||||
['m', 1],
|
||||
['n', 1],
|
||||
['r', 1],
|
||||
['s', 4],
|
||||
['t', 3],
|
||||
['u', 3]
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("last obliged to accept the second-hand,")` should return `[[" ", 5], [", ", 1], ["-", 1], ["a", 3], ["b", 1], ["c", 3], ["d", 3], ["e", 4], ["g", 1], ["h", 2], ["i", 1], ["l", 2], ["n", 2], ["o", 3], ["p", 1], ["s", 2], ["t", 4]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('last obliged to accept the second-hand,'), [
|
||||
[' ', 5],
|
||||
[',', 1],
|
||||
['-', 1],
|
||||
['a', 3],
|
||||
['b', 1],
|
||||
['c', 3],
|
||||
['d', 3],
|
||||
['e', 4],
|
||||
['g', 1],
|
||||
['h', 2],
|
||||
['i', 1],
|
||||
['l', 2],
|
||||
['n', 2],
|
||||
['o', 3],
|
||||
['p', 1],
|
||||
['s', 2],
|
||||
['t', 4]
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function letterFrequency(txt) {
|
||||
@ -54,12 +186,7 @@ function letterFrequency(txt) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function letterFrequency(txt) {
|
||||
@ -79,5 +206,3 @@ function letterFrequency(txt) {
|
||||
return keys.map(function (c) { return [c, dct[c]]; });
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,54 +5,81 @@ challengeType: 5
|
||||
forumTopicId: 385264
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
In information theory and computer science, the <strong>Levenshtein distance</strong> is a <a href="https://en.wikipedia.org/wiki/string metric">metric</a> for measuring the amount of difference between two sequences (i.e. an <a href="https://en.wikipedia.org/wiki/edit distance">edit distance</a>). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
|
||||
# --description--
|
||||
|
||||
In information theory and computer science, the **Levenshtein distance** is a [metric](<https://en.wikipedia.org/wiki/string metric>) for measuring the amount of difference between two sequences (i.e. an [edit distance](<https://en.wikipedia.org/wiki/edit distance>)). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
|
||||
|
||||
Example:
|
||||
The Levenshtein distance between "<strong>kitten</strong>" and "<strong>sitting</strong>" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
|
||||
|
||||
The Levenshtein distance between "**kitten**" and "**sitting**" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
|
||||
|
||||
<ul>
|
||||
<li><strong>k</strong>itten <strong>s</strong>itten (substitution of 'k' with 's')</strong></li>
|
||||
<li>sitt<strong>e</strong>n sitt<strong>i</strong>n (substitution of 'e' with 'i')</strong></li>
|
||||
<li>sittin sittin<strong>g</strong> (insert 'g' at the end).</strong></li>
|
||||
<li><strong>k</strong>itten <strong>s</strong>itten (substitution of 'k' with 's')</li>
|
||||
<li>sitt<strong>e</strong>n sitt<strong>i</strong>n (substitution of 'e' with 'i')</li>
|
||||
<li>sittin sittin<strong>g</strong> (insert 'g' at the end).</li>
|
||||
</ul>
|
||||
<i>The Levenshtein distance between "<strong>rosettacode</strong>", "<strong>raisethysword</strong>" is <strong>8</strong>.</i>
|
||||
<i>The distance between two strings is same as that when both strings are reversed.</i>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
*The Levenshtein distance between "**rosettacode**", "**raisethysword**" is **8**.*
|
||||
|
||||
*The distance between two strings is same as that when both strings are reversed.*
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns the Levenshtein distance between two strings given as parameters.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>levenshtein</code> should be a function.
|
||||
testString: assert(typeof levenshtein == 'function');
|
||||
- text: <code>levenshtein("mist", "dist")</code> should return a number.
|
||||
testString: assert(typeof levenshtein("mist", "dist") == 'number');
|
||||
- text: <code>levenshtein("mist", "dist")</code> should return <code>1</code>.
|
||||
testString: assert.equal(levenshtein("mist", "dist"), 1);
|
||||
- text: <code>levenshtein("tier", "tor")</code> should return <code>2</code>.
|
||||
testString: assert.equal(levenshtein("tier", "tor"), 2);
|
||||
- text: <code>levenshtein("kitten", "sitting")</code> should return <code>3</code>.
|
||||
testString: assert.equal(levenshtein("kitten", "sitting"), 3);
|
||||
- text: <code>levenshtein("stop", "tops")</code> should return <code>2</code>.
|
||||
testString: assert.equal(levenshtein("stop", "tops"), 2);
|
||||
- text: <code>levenshtein("rosettacode", "raisethysword")</code> should return <code>8</code>.
|
||||
testString: assert.equal(levenshtein("rosettacode", "raisethysword"), 8);
|
||||
- text: <code>levenshtein("mississippi", "swiss miss")</code> should return <code>8</code>.
|
||||
testString: assert.equal(levenshtein("mississippi", "swiss miss"), 8);
|
||||
`levenshtein` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof levenshtein == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`levenshtein("mist", "dist")` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof levenshtein('mist', 'dist') == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`levenshtein("mist", "dist")` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('mist', 'dist'), 1);
|
||||
```
|
||||
|
||||
`levenshtein("tier", "tor")` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('tier', 'tor'), 2);
|
||||
```
|
||||
|
||||
`levenshtein("kitten", "sitting")` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('kitten', 'sitting'), 3);
|
||||
```
|
||||
|
||||
`levenshtein("stop", "tops")` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('stop', 'tops'), 2);
|
||||
```
|
||||
|
||||
`levenshtein("rosettacode", "raisethysword")` should return `8`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('rosettacode', 'raisethysword'), 8);
|
||||
```
|
||||
|
||||
`levenshtein("mississippi", "swiss miss")` should return `8`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('mississippi', 'swiss miss'), 8);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function levenshtein(a, b) {
|
||||
@ -60,12 +87,7 @@ function levenshtein(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function levenshtein(a, b) {
|
||||
@ -80,5 +102,3 @@ function levenshtein(a, b) {
|
||||
} return u[n];
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,52 +5,78 @@ challengeType: 5
|
||||
forumTopicId: 385266
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
The <a href="https://en.wikipedia.org/wiki/linear congruential generator">linear congruential generator</a> is a very simple example of a <a href="http://rosettacode.org/wiki/random number generator">random number generator</a>. All linear congruential generators use this formula:
|
||||
$$r_{n + 1} = a \times r_n + c \pmod m$$
|
||||
# --description--
|
||||
|
||||
The [linear congruential generator](<https://en.wikipedia.org/wiki/linear congruential generator>) is a very simple example of a [random number generator](<http://rosettacode.org/wiki/random number generator>). All linear congruential generators use this formula:
|
||||
|
||||
$$r\_{n + 1} = a \\times r_n + c \\pmod m$$
|
||||
|
||||
Where:
|
||||
|
||||
<ul>
|
||||
<li>$ r_0 $ is a seed.</li>
|
||||
<li>$r_1$, $r_2$, $r_3$, ..., are the random numbers.</li>
|
||||
<li>$a$, $c$, $m$ are constants.</li>
|
||||
</ul>
|
||||
|
||||
If one chooses the values of $a$, $c$ and $m$ with care, then the generator produces a uniform distribution of integers from $0$ to $m - 1$.
|
||||
LCG numbers have poor quality. $r_n$ and $r_{n + 1}$ are not independent, as true random numbers would be. Anyone who knows $r_n$ can predict $r_{n + 1}$, therefore LCG is not cryptographically secure. The LCG is still good enough for simple tasks like <a href="http://rosettacode.org/wiki/Miller-Rabin primality test">Miller-Rabin primality test</a>, or <a href="http://rosettacode.org/wiki/deal cards for FreeCell">FreeCell deals</a>. Among the benefits of the LCG, one can easily reproduce a sequence of numbers, from the same $r_0$. One can also reproduce such sequence with a different programming language, because the formula is so simple.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
LCG numbers have poor quality. $r_n$ and $r\_{n + 1}$ are not independent, as true random numbers would be. Anyone who knows $r_n$ can predict $r\_{n + 1}$, therefore LCG is not cryptographically secure. The LCG is still good enough for simple tasks like [Miller-Rabin primality test](<http://rosettacode.org/wiki/Miller-Rabin primality test>), or [FreeCell deals](<http://rosettacode.org/wiki/deal cards for FreeCell>). Among the benefits of the LCG, one can easily reproduce a sequence of numbers, from the same $r_0$. One can also reproduce such sequence with a different programming language, because the formula is so simple.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes $r_0,a,c,m,n$ as parameters and returns $r_n$.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>linearCongGenerator</code> should be a function.
|
||||
testString: assert(typeof linearCongGenerator == 'function');
|
||||
- text: <code>linearCongGenerator(324, 1145, 177, 2148, 3)</code> should return a number.
|
||||
testString: assert(typeof linearCongGenerator(324, 1145, 177, 2148, 3) == 'number');
|
||||
- text: <code>linearCongGenerator(324, 1145, 177, 2148, 3)</code> should return <code>855</code>.
|
||||
testString: assert.equal(linearCongGenerator(324, 1145, 177, 2148, 3), 855);
|
||||
- text: <code>linearCongGenerator(234, 11245, 145, 83648, 4)</code> should return <code>1110</code>.
|
||||
testString: assert.equal(linearCongGenerator(234, 11245, 145, 83648, 4), 1110);
|
||||
- text: <code>linearCongGenerator(85, 11, 1234, 214748, 5)</code> should return <code>62217</code>.
|
||||
testString: assert.equal(linearCongGenerator(85, 11, 1234, 214748, 5), 62217);
|
||||
- text: <code>linearCongGenerator(0, 1103515245, 12345, 2147483648, 1)</code> should return <code>12345</code>.
|
||||
testString: assert.equal(linearCongGenerator(0, 1103515245, 12345, 2147483648, 1), 12345);
|
||||
- text: <code>linearCongGenerator(0, 1103515245, 12345, 2147483648, 2)</code> should return <code>1406932606</code>.
|
||||
testString: assert.equal(linearCongGenerator(0, 1103515245, 12345, 2147483648, 2), 1406932606);
|
||||
`linearCongGenerator` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof linearCongGenerator == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`linearCongGenerator(324, 1145, 177, 2148, 3)` should return a number.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof linearCongGenerator(324, 1145, 177, 2148, 3) == 'number');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`linearCongGenerator(324, 1145, 177, 2148, 3)` should return `855`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(324, 1145, 177, 2148, 3), 855);
|
||||
```
|
||||
|
||||
`linearCongGenerator(234, 11245, 145, 83648, 4)` should return `1110`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(234, 11245, 145, 83648, 4), 1110);
|
||||
```
|
||||
|
||||
`linearCongGenerator(85, 11, 1234, 214748, 5)` should return `62217`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(85, 11, 1234, 214748, 5), 62217);
|
||||
```
|
||||
|
||||
`linearCongGenerator(0, 1103515245, 12345, 2147483648, 1)` should return `12345`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(0, 1103515245, 12345, 2147483648, 1), 12345);
|
||||
```
|
||||
|
||||
`linearCongGenerator(0, 1103515245, 12345, 2147483648, 2)` should return `1406932606`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
linearCongGenerator(0, 1103515245, 12345, 2147483648, 2),
|
||||
1406932606
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function linearCongGenerator(r0, a, c, m, n) {
|
||||
@ -58,12 +84,7 @@ function linearCongGenerator(r0, a, c, m, n) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function linearCongGenerator(r0, a, c, m, n) {
|
||||
@ -73,5 +94,3 @@ function linearCongGenerator(r0, a, c, m, n) {
|
||||
return r0;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,45 +5,80 @@ challengeType: 5
|
||||
forumTopicId: 385269
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Explicitly implement <a href="https://en.wikipedia.org/wiki/long multiplication">long multiplication</a>.
|
||||
# --description--
|
||||
|
||||
Explicitly implement [long multiplication](<https://en.wikipedia.org/wiki/long multiplication>).
|
||||
|
||||
This is one possible approach to arbitrary-precision integer algebra.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes two strings of large numbers as parameters. Your function should return the product of these two large numbers as a string.
|
||||
<strong>Note:</strong> In JavaScript, arithmetic operations are inaccurate with large numbers, so you will have to implement precise multiplication yourself.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
**Note:** In JavaScript, arithmetic operations are inaccurate with large numbers, so you will have to implement precise multiplication yourself.
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>mult</code> should be a function.
|
||||
testString: assert(typeof mult == 'function');
|
||||
- text: <code>mult("18446744073709551616", "18446744073709551616")</code> should return a string.
|
||||
testString: assert(typeof mult("18446744073709551616", "18446744073709551616") == 'string');
|
||||
- text: <code>mult("18446744073709551616", "18446744073709551616")</code> should return <code>"340282366920938463463374607431768211456"</code>.
|
||||
testString: assert.equal(mult("18446744073709551616", "18446744073709551616"), "340282366920938463463374607431768211456");
|
||||
- text: <code>mult("31844674073709551616", "1844674407309551616")</code> should return <code>"58743055272886011737990786529368211456"</code>.
|
||||
testString: assert.equal(mult("31844674073709551616", "1844674407309551616"), "58743055272886011737990786529368211456");
|
||||
- text: <code>mult("1846744073709551616", "44844644073709551616")</code> should return <code>"82816580680737279241781007431768211456"</code>.
|
||||
testString: assert.equal(mult("1846744073709551616", "44844644073709551616"), "82816580680737279241781007431768211456");
|
||||
- text: <code>mult("1844674407370951616", "1844674407709551616")</code> should return <code>"3402823669833978308014392742590611456"</code>.
|
||||
testString: assert.equal(mult("1844674407370951616", "1844674407709551616"), "3402823669833978308014392742590611456");
|
||||
- text: <code>mult("2844674407370951616", "1844674407370955616")</code> should return <code>"5247498076580334548376218009219475456"</code>.
|
||||
testString: assert.equal(mult("2844674407370951616", "1844674407370955616"), "5247498076580334548376218009219475456");
|
||||
# --hints--
|
||||
|
||||
`mult` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof mult == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`mult("18446744073709551616", "18446744073709551616")` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof mult('18446744073709551616', '18446744073709551616') == 'string');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`mult("18446744073709551616", "18446744073709551616")` should return `"340282366920938463463374607431768211456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
mult('18446744073709551616', '18446744073709551616'),
|
||||
'340282366920938463463374607431768211456'
|
||||
);
|
||||
```
|
||||
|
||||
`mult("31844674073709551616", "1844674407309551616")` should return `"58743055272886011737990786529368211456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
mult('31844674073709551616', '1844674407309551616'),
|
||||
'58743055272886011737990786529368211456'
|
||||
);
|
||||
```
|
||||
|
||||
`mult("1846744073709551616", "44844644073709551616")` should return `"82816580680737279241781007431768211456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
mult('1846744073709551616', '44844644073709551616'),
|
||||
'82816580680737279241781007431768211456'
|
||||
);
|
||||
```
|
||||
|
||||
`mult("1844674407370951616", "1844674407709551616")` should return `"3402823669833978308014392742590611456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
mult('1844674407370951616', '1844674407709551616'),
|
||||
'3402823669833978308014392742590611456'
|
||||
);
|
||||
```
|
||||
|
||||
`mult("2844674407370951616", "1844674407370955616")` should return `"5247498076580334548376218009219475456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
mult('2844674407370951616', '1844674407370955616'),
|
||||
'5247498076580334548376218009219475456'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mult(strNum1, strNum2) {
|
||||
@ -51,12 +86,7 @@ function mult(strNum1, strNum2) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mult(strNum1, strNum2) {
|
||||
@ -78,5 +108,3 @@ function mult(strNum1, strNum2) {
|
||||
return aResult.reverse().join("");
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,50 +5,75 @@ challengeType: 5
|
||||
forumTopicId: 385271
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
The <b>longest common subsequence</b> (or <a href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem" target="_blank"><b>LCS</b></a>) of groups A and B is the longest group of elements from A and B that are common between the two groups and in the same order in each group. For example, the sequences "1234" and "1224533324" have an LCS of "1234":
|
||||
<b><u>1234</u></b>
|
||||
<b><u>12</u></b>245<b><u>3</u></b>332<b><u>4</u></b>
|
||||
# --description--
|
||||
|
||||
The **longest common subsequence** (or [**LCS**](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem)) of groups A and B is the longest group of elements from A and B that are common between the two groups and in the same order in each group. For example, the sequences "1234" and "1224533324" have an LCS of "1234":
|
||||
|
||||
***1234***
|
||||
|
||||
***12***245***3***332***4***
|
||||
|
||||
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
|
||||
<b><u>t</u></b>hi<b><u>si</u></b>sa<b><u>test</u></b>
|
||||
<b><u>t</u></b>e<b><u>s</u></b>t<b><u>i</u></b>ng123<b><u>test</u></b>ing.
|
||||
|
||||
***t***hi***si***sa***test***
|
||||
|
||||
***t***e***s***t***i***ng123***test***ing.
|
||||
|
||||
Your code only needs to deal with strings.
|
||||
For more information on this problem please see <a href="https://en.wikipedia.org/wiki/Longest_common_subsequence_problem" target="_black">Wikipedia</a>.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
For more information on this problem please see [Wikipedia](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a case-sensitive function that returns the LCS of two strings. You don't need to show multiple LCS's.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>lcs</code> should be a function.
|
||||
testString: assert(typeof lcs == 'function');
|
||||
- text: <code>lcs("thisisatest", "testing123testing")</code> should return a string.
|
||||
testString: assert(typeof lcs("thisisatest", "testing123testing") == 'string');
|
||||
- text: <code>lcs("thisisatest", "testing123testing")</code> should return <code>"tsitest"</code>.
|
||||
testString: assert.equal(lcs("thisisatest", "testing123testing"), "tsitest");
|
||||
- text: <code>lcs("ABCDGH", "AEDFHR")</code> should return <code>"ADH"</code>.
|
||||
testString: assert.equal(lcs("ABCDGH", "AEDFHR"), "ADH");
|
||||
- text: <code>lcs("AGGTAB", "GXTXAYB")</code> should return <code>"GTAB"</code>.
|
||||
testString: assert.equal(lcs("AGGTAB", "GXTXAYB"), "GTAB");
|
||||
- text: <code>lcs("BDACDB", "BDCB")</code> should return <code>"BDCB"</code>.
|
||||
testString: assert.equal(lcs("BDACDB", "BDCB"), "BDCB");
|
||||
- text: <code>lcs("ABAZDC", "BACBAD")</code> should return <code>"ABAD"</code>.
|
||||
testString: assert.equal(lcs("ABAZDC", "BACBAD"), "ABAD");
|
||||
`lcs` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof lcs == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`lcs("thisisatest", "testing123testing")` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof lcs('thisisatest', 'testing123testing') == 'string');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`lcs("thisisatest", "testing123testing")` should return `"tsitest"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('thisisatest', 'testing123testing'), 'tsitest');
|
||||
```
|
||||
|
||||
`lcs("ABCDGH", "AEDFHR")` should return `"ADH"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('ABCDGH', 'AEDFHR'), 'ADH');
|
||||
```
|
||||
|
||||
`lcs("AGGTAB", "GXTXAYB")` should return `"GTAB"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('AGGTAB', 'GXTXAYB'), 'GTAB');
|
||||
```
|
||||
|
||||
`lcs("BDACDB", "BDCB")` should return `"BDCB"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('BDACDB', 'BDCB'), 'BDCB');
|
||||
```
|
||||
|
||||
`lcs("ABAZDC", "BACBAD")` should return `"ABAD"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('ABAZDC', 'BACBAD'), 'ABAD');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function lcs(a, b) {
|
||||
@ -56,12 +81,7 @@ function lcs(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function lcs(a, b) {
|
||||
@ -79,5 +99,3 @@ function lcs(a, b) {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,49 +5,83 @@ challengeType: 5
|
||||
forumTopicId: 385272
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. An example:
|
||||
|
||||
For the following array:
|
||||
$\{3, 10, 2, 1, 20\}$
|
||||
|
||||
$\\{3, 10, 2, 1, 20\\}$
|
||||
|
||||
Longest increasing sequence is:
|
||||
$\{3, 10, 20\}$
|
||||
For more information on this problem please see <a href="https://en.wikipedia.org/wiki/Longest increasing subsequence" target="_blank">Wikipedia</a>.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
$\\{3, 10, 20\\}$
|
||||
|
||||
For more information on this problem please see [Wikipedia](<https://en.wikipedia.org/wiki/Longest increasing subsequence>).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of numbers as a parameter and returns the longest increasing subsequence.
|
||||
|
||||
It is guaranteed that every array will have a longest increasing subsequence.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>findSequence</code> should be a function.
|
||||
testString: assert(typeof findSequence == 'function');
|
||||
- text: <code>findSequence([3, 10, 2, 1, 20])</code> should return a array.
|
||||
testString: assert(Array.isArray(findSequence([3, 10, 2, 1, 20])));
|
||||
- text: <code>findSequence([3, 10, 2, 1, 20])</code> should return <code>[3, 10, 20]</code>.
|
||||
testString: assert.deepEqual(findSequence([3, 10, 2, 1, 20]), [3, 10, 20]);
|
||||
- text: <code>findSequence([2, 7, 3, 5, 8])</code> should return <code>[2, 3, 5, 8]</code>.
|
||||
testString: assert.deepEqual(findSequence([2, 7, 3, 5, 8]), [2, 3, 5, 8]);
|
||||
- text: <code>findSequence([2, 6, 4, 5, 1])</code> should return <code>[2, 4, 5]</code>.
|
||||
testString: assert.deepEqual(findSequence([2, 6, 4, 5, 1]), [2, 4, 5]);
|
||||
- text: <code>findSequence([10, 22, 9, 33, 21, 50, 60, 80])</code> should return <code>[10, 22, 33, 50, 60, 80]</code>.
|
||||
testString: assert.deepEqual(findSequence([10, 22, 9, 33, 21, 50, 60, 80]), [10, 22, 33, 50, 60, 80]);
|
||||
- text: <code>findSequence([0, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])</code> should return <code>[0, 2, 6, 9, 11, 15</code>.
|
||||
testString: assert.deepEqual(findSequence([0, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]), [0, 2, 6, 9, 11, 15]);
|
||||
`findSequence` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof findSequence == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`findSequence([3, 10, 2, 1, 20])` should return a array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(findSequence([3, 10, 2, 1, 20])));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`findSequence([3, 10, 2, 1, 20])` should return `[3, 10, 20]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([3, 10, 2, 1, 20]), [3, 10, 20]);
|
||||
```
|
||||
|
||||
`findSequence([2, 7, 3, 5, 8])` should return `[2, 3, 5, 8]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([2, 7, 3, 5, 8]), [2, 3, 5, 8]);
|
||||
```
|
||||
|
||||
`findSequence([2, 6, 4, 5, 1])` should return `[2, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([2, 6, 4, 5, 1]), [2, 4, 5]);
|
||||
```
|
||||
|
||||
`findSequence([10, 22, 9, 33, 21, 50, 60, 80])` should return `[10, 22, 33, 50, 60, 80]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([10, 22, 9, 33, 21, 50, 60, 80]), [
|
||||
10,
|
||||
22,
|
||||
33,
|
||||
50,
|
||||
60,
|
||||
80
|
||||
]);
|
||||
```
|
||||
|
||||
`findSequence([0, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])` should return `[0, 2, 6, 9, 11, 15`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
findSequence([0, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]),
|
||||
[0, 2, 6, 9, 11, 15]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findSequence(input) {
|
||||
@ -55,12 +89,7 @@ function findSequence(input) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findSequence(input) {
|
||||
@ -88,5 +117,3 @@ function findSequence(input) {
|
||||
return output;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,43 +5,75 @@ challengeType: 5
|
||||
forumTopicId: 385275
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
In this challenge, you have to find the strings that are the longest among the given strings.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of strings and returns the strings that have a length equal to the longest length.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>longestString</code> should be a function.
|
||||
testString: assert(typeof longestString == 'function');
|
||||
- text: <code>longestString(["a", "bb", "ccc", "ee", "f", "ggg"])</code> should return a array.
|
||||
testString: assert(Array.isArray(longestString(["a", "bb", "ccc", "ee", "f", "ggg"])));
|
||||
- text: <code>longestString(["a", "bb", "ccc", "ee", "f", "ggg"])</code> should return <code>["ccc", "ggg"]'</code>.
|
||||
testString: assert.deepEqual(longestString(["a", "bb", "ccc", "ee", "f", "ggg"]), ["ccc", "ggg"]);
|
||||
- text: <code>longestString(["afedg", "bb", "sdccc", "efdee", "f", "geegg"])</code> should return <code>["afedg", "sdccc", "efdee", "geegg"]</code>.
|
||||
testString: assert.deepEqual(longestString(["afedg", "bb", "sdccc", "efdee", "f", "geegg"]), ["afedg", "sdccc", "efdee", "geegg"]);
|
||||
- text: <code>longestString(["a", "bhghgb", "ccc", "efde", "fssdrr", "ggg"])</code> should return <code>["bhghgb", "fssdrr"]</code>.
|
||||
testString: assert.deepEqual(longestString(["a", "bhghgb", "ccc", "efde", "fssdrr", "ggg"]), ["bhghgb", "fssdrr"]);
|
||||
- text: <code>longestString(["ahgfhg", "bdsfsb", "ccc", "ee", "f", "ggdsfg"])</code> should return <code>["ahgfhg", "bdsfsb", "ggdsfg"]</code>.
|
||||
testString: assert.deepEqual(longestString(["ahgfhg", "bdsfsb", "ccc", "ee", "f", "ggdsfg"]), ["ahgfhg", "bdsfsb", "ggdsfg"]);
|
||||
- text: <code>longestString(["a", "bbdsf", "ccc", "edfe", "gzzzgg"])</code> should return <code>["gzzzgg"]</code>.
|
||||
testString: assert.deepEqual(longestString(["a", "bbdsf", "ccc", "edfe", "gzzzgg"]), ["gzzzgg"]);
|
||||
`longestString` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof longestString == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`longestString(["a", "bb", "ccc", "ee", "f", "ggg"])` should return a array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(Array.isArray(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg'])));
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`longestString(["a", "bb", "ccc", "ee", "f", "ggg"])` should return `["ccc", "ggg"]'`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg']), [
|
||||
'ccc',
|
||||
'ggg'
|
||||
]);
|
||||
```
|
||||
|
||||
`longestString(["afedg", "bb", "sdccc", "efdee", "f", "geegg"])` should return `["afedg", "sdccc", "efdee", "geegg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
longestString(['afedg', 'bb', 'sdccc', 'efdee', 'f', 'geegg']),
|
||||
['afedg', 'sdccc', 'efdee', 'geegg']
|
||||
);
|
||||
```
|
||||
|
||||
`longestString(["a", "bhghgb", "ccc", "efde", "fssdrr", "ggg"])` should return `["bhghgb", "fssdrr"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
longestString(['a', 'bhghgb', 'ccc', 'efde', 'fssdrr', 'ggg']),
|
||||
['bhghgb', 'fssdrr']
|
||||
);
|
||||
```
|
||||
|
||||
`longestString(["ahgfhg", "bdsfsb", "ccc", "ee", "f", "ggdsfg"])` should return `["ahgfhg", "bdsfsb", "ggdsfg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
longestString(['ahgfhg', 'bdsfsb', 'ccc', 'ee', 'f', 'ggdsfg']),
|
||||
['ahgfhg', 'bdsfsb', 'ggdsfg']
|
||||
);
|
||||
```
|
||||
|
||||
`longestString(["a", "bbdsf", "ccc", "edfe", "gzzzgg"])` should return `["gzzzgg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(longestString(['a', 'bbdsf', 'ccc', 'edfe', 'gzzzgg']), [
|
||||
'gzzzgg'
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function longestString(strings) {
|
||||
@ -49,12 +81,7 @@ function longestString(strings) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function longestString(strings) {
|
||||
@ -71,5 +98,3 @@ function longestString(strings) {
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,52 +5,74 @@ challengeType: 5
|
||||
forumTopicId: 385277
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
The <a href="https://en.wikipedia.org/wiki/Look and say sequence" target="_blank">Look and say sequence</a> is a recursively defined sequence of numbers.
|
||||
# --description--
|
||||
|
||||
The [Look and say sequence](<https://en.wikipedia.org/wiki/Look and say sequence>) is a recursively defined sequence of numbers.
|
||||
|
||||
Sequence Definition
|
||||
|
||||
<ul><li>Take a decimal number</li>
|
||||
<li><span>Look</span> at the number, visually grouping consecutive runs of the same digit.</li>
|
||||
<li><span>Say</span> the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.</li></ul><span> This becomes the next number of the sequence.</span>
|
||||
<span>An example:</span>
|
||||
|
||||
An example:
|
||||
|
||||
<ul><li>Starting with the number 1, you have <span>one</span> 1 which produces 11</li>
|
||||
<li>Starting with 11, you have <span>two</span> 1's. I.E.: 21</li>
|
||||
<li>Starting with 21, you have <span>one</span> 2, then <span>one</span> 1. I.E.: (12)(11) which becomes 1211</li>
|
||||
<li>Starting with 1211, you have <span>one</span> 1, <span>one</span> 2, then <span>two</span> 1's. I.E.: (11)(12)(21) which becomes 111221</li></ul>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
# --instructions--
|
||||
|
||||
Write a function that accepts a string as a parameter, processes it, and returns the resultant string.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>lookAndSay</code> should be a function.
|
||||
testString: assert(typeof lookAndSay == 'function');
|
||||
- text: <code>lookAndSay("1")</code> should return a string.
|
||||
testString: assert(typeof lookAndSay("1") == 'string');
|
||||
- text: <code>lookAndSay("1")</code> should return <code>"11"</code>.
|
||||
testString: assert.equal(lookAndSay("1"), "11");
|
||||
- text: <code>lookAndSay("11")</code> should return <code>"21"</code>.
|
||||
testString: assert.equal(lookAndSay("11"), "21");
|
||||
- text: <code>lookAndSay("21")</code> should return <code>"1211"</code>.
|
||||
testString: assert.equal(lookAndSay("21"), "1211");
|
||||
- text: <code>lookAndSay("1211")</code> should return <code>"111221"</code>.
|
||||
testString: assert.equal(lookAndSay("1211"), "111221");
|
||||
- text: <code>lookAndSay("3542")</code> should return <code>"13151412"</code>.
|
||||
testString: assert.equal(lookAndSay("3542"), "13151412");
|
||||
`lookAndSay` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof lookAndSay == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`lookAndSay("1")` should return a string.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(typeof lookAndSay('1') == 'string');
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`lookAndSay("1")` should return `"11"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('1'), '11');
|
||||
```
|
||||
|
||||
`lookAndSay("11")` should return `"21"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('11'), '21');
|
||||
```
|
||||
|
||||
`lookAndSay("21")` should return `"1211"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('21'), '1211');
|
||||
```
|
||||
|
||||
`lookAndSay("1211")` should return `"111221"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('1211'), '111221');
|
||||
```
|
||||
|
||||
`lookAndSay("3542")` should return `"13151412"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('3542'), '13151412');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function lookAndSay(str) {
|
||||
@ -58,12 +80,7 @@ function lookAndSay(str) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function lookAndSay(str) {
|
||||
@ -72,5 +89,3 @@ function lookAndSay(str) {
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,47 +5,112 @@ challengeType: 5
|
||||
forumTopicId: 385279
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
# --description--
|
||||
|
||||
Loop over multiple arrays and create a new array whose $i^{th}$ element is the concatenation of $i^{th}$ element of each of the given.
|
||||
|
||||
For this example, if you are given this array of arrays:
|
||||
<code>[ ["a", "b", "c"], ["A", "B", "C"], [1, 2, 3] ]</code>
|
||||
|
||||
`[ ["a", "b", "c"], ["A", "B", "C"], [1, 2, 3] ]`
|
||||
|
||||
the output should be:
|
||||
<code>["aA1","bB2","cC3"]</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
`["aA1","bB2","cC3"]`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of arrays as a parameter and returns an array of strings satisfying the given description.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
# --hints--
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>loopSimult</code> should be a function.
|
||||
testString: assert(typeof loopSimult == 'function');
|
||||
- text: <code>loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])</code> should return a array.
|
||||
testString: assert(Array.isArray(loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])));
|
||||
- text: <code>loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])</code> should return <code>["aA1", "bB2", "cC3"]</code>.
|
||||
testString: assert.deepEqual(loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]]), ["aA1", "bB2", "cC3"]);
|
||||
- text: <code>loopSimult([["c", "b", "c"], ["4", "5", "C"], [7, 7, 3]])</code> should return <code>["c47", "b57", "cC3"]</code>.
|
||||
testString: assert.deepEqual(loopSimult([["c", "b", "c"], ["4", "5", "C"], [7, 7, 3]]), ["c47", "b57", "cC3"]);
|
||||
- text: <code>loopSimult([["a", "b", "c", "d"], ["A", "B", "C", "d"], [1, 2, 3, 4]])</code> should return <code>["aA1", "bB2", "cC3", "dd4"]</code>.
|
||||
testString: assert.deepEqual(loopSimult([["a", "b", "c", "d"], ["A", "B", "C", "d"], [1, 2, 3, 4]]), ["aA1", "bB2", "cC3", "dd4"]);
|
||||
- text: <code>loopSimult([["a", "b"], ["A", "B"], [1, 2]])</code> should return <code>["aA1", "bB2"]</code>.
|
||||
testString: assert.deepEqual(loopSimult([["a", "b"], ["A", "B"], [1, 2]]), ["aA1", "bB2"]);
|
||||
- text: <code>loopSimult([["b", "c"], ["B", "C"], [2, 3]])</code> should return <code>["bB2", "cC3"]</code>.
|
||||
testString: assert.deepEqual(loopSimult([["b", "c"], ["B", "C"], [2, 3]]), ["bB2", "cC3"]);
|
||||
`loopSimult` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof loopSimult == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])` should return a array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(
|
||||
Array.isArray(
|
||||
loopSimult([
|
||||
['a', 'b', 'c'],
|
||||
['A', 'B', 'C'],
|
||||
[1, 2, 3]
|
||||
])
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])` should return `["aA1", "bB2", "cC3"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
loopSimult([
|
||||
['a', 'b', 'c'],
|
||||
['A', 'B', 'C'],
|
||||
[1, 2, 3]
|
||||
]),
|
||||
['aA1', 'bB2', 'cC3']
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["c", "b", "c"], ["4", "5", "C"], [7, 7, 3]])` should return `["c47", "b57", "cC3"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
loopSimult([
|
||||
['c', 'b', 'c'],
|
||||
['4', '5', 'C'],
|
||||
[7, 7, 3]
|
||||
]),
|
||||
['c47', 'b57', 'cC3']
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["a", "b", "c", "d"], ["A", "B", "C", "d"], [1, 2, 3, 4]])` should return `["aA1", "bB2", "cC3", "dd4"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
loopSimult([
|
||||
['a', 'b', 'c', 'd'],
|
||||
['A', 'B', 'C', 'd'],
|
||||
[1, 2, 3, 4]
|
||||
]),
|
||||
['aA1', 'bB2', 'cC3', 'dd4']
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["a", "b"], ["A", "B"], [1, 2]])` should return `["aA1", "bB2"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
loopSimult([
|
||||
['a', 'b'],
|
||||
['A', 'B'],
|
||||
[1, 2]
|
||||
]),
|
||||
['aA1', 'bB2']
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["b", "c"], ["B", "C"], [2, 3]])` should return `["bB2", "cC3"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
loopSimult([
|
||||
['b', 'c'],
|
||||
['B', 'C'],
|
||||
[2, 3]
|
||||
]),
|
||||
['bB2', 'cC3']
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function loopSimult(A) {
|
||||
@ -53,12 +118,7 @@ function loopSimult(A) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function loopSimult(A) {
|
||||
@ -72,5 +132,3 @@ function loopSimult(A) {
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
@ -5,75 +5,227 @@ challengeType: 5
|
||||
forumTopicId: 385280
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Every square matrix $A$ can be decomposed into a product of a lower triangular matrix $L$ and a upper triangular matrix $U$, as described in <a href="https://en.wikipedia.org/wiki/LU decomposition">LU decomposition</a>.
|
||||
# --description--
|
||||
|
||||
Every square matrix $A$ can be decomposed into a product of a lower triangular matrix $L$ and a upper triangular matrix $U$, as described in [LU decomposition](<https://en.wikipedia.org/wiki/LU decomposition>).
|
||||
|
||||
$A = LU$
|
||||
|
||||
It is a modified form of Gaussian elimination.
|
||||
While the <a href="http://rosettacode.org/wiki/Cholesky decomposition">Cholesky decomposition</a> only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix.
|
||||
|
||||
While the [Cholesky decomposition](<http://rosettacode.org/wiki/Cholesky decomposition>) only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix.
|
||||
|
||||
There are several algorithms for calculating $L$ and $U$.
|
||||
To derive <i>Crout's algorithm</i> for a 3x3 example, we have to solve the following system:
|
||||
\begin{align}A = \begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{21} & a_{22} & a_{23}\\ a_{31} & a_{32} & a_{33}\\ \end{pmatrix}= \begin{pmatrix} l_{11} & 0 & 0 \\ l_{21} & l_{22} & 0 \\ l_{31} & l_{32} & l_{33}\\ \end{pmatrix} \begin{pmatrix} u_{11} & u_{12} & u_{13} \\ 0 & u_{22} & u_{23} \\ 0 & 0 & u_{33} \end{pmatrix} = LU\end{align}
|
||||
|
||||
To derive *Crout's algorithm* for a 3x3 example, we have to solve the following system:
|
||||
|
||||
\\begin{align}A = \\begin{pmatrix} a\_{11} & a\_{12} & a\_{13}\\\\ a\_{21} & a\_{22} & a\_{23}\\\\ a\_{31} & a\_{32} & a\_{33}\\\\ \\end{pmatrix}= \\begin{pmatrix} l\_{11} & 0 & 0 \\\\ l\_{21} & l\_{22} & 0 \\\\ l\_{31} & l\_{32} & l\_{33}\\\\ \\end{pmatrix} \\begin{pmatrix} u\_{11} & u\_{12} & u\_{13} \\\\ 0 & u\_{22} & u\_{23} \\\\ 0 & 0 & u\_{33} \\end{pmatrix} = LU\\end{align}
|
||||
|
||||
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of $L$ are set to 1
|
||||
$l_{11}=1$
|
||||
$l_{22}=1$
|
||||
$l_{33}=1$
|
||||
|
||||
$l\_{11}=1$
|
||||
|
||||
$l\_{22}=1$
|
||||
|
||||
$l\_{33}=1$
|
||||
|
||||
so we get a solvable system of 9 unknowns and 9 equations.
|
||||
\begin{align}A = \begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{21} & a_{22} & a_{23}\\ a_{31} & a_{32} & a_{33}\\ \end{pmatrix} = \begin{pmatrix} 1 & 0 & 0 \\ l_{21} & 1 & 0 \\ l_{31} & l_{32} & 1\\ \end{pmatrix} \begin{pmatrix} u_{11} & u_{12} & u_{13} \\ 0 & u_{22} & u_{23} \\ 0 & 0 & u_{33} \end{pmatrix} = \begin{pmatrix} u_{11} & u_{12} & u_{13} \\ u_{11}l_{21} & u_{12}l_{21}+u_{22} & u_{13}l_{21}+u_{23} \\ u_{11}l_{31} & u_{12}l_{31}+u_{22}l_{32} & u_{13}l_{31} + u_{23}l_{32}+u_{33} \end{pmatrix} = LU\end{align}
|
||||
|
||||
\\begin{align}A = \\begin{pmatrix} a\_{11} & a\_{12} & a\_{13}\\\\ a\_{21} & a\_{22} & a\_{23}\\\\ a\_{31} & a\_{32} & a\_{33}\\\\ \\end{pmatrix} = \\begin{pmatrix} 1 & 0 & 0 \\\\ l\_{21} & 1 & 0 \\\\ l\_{31} & l\_{32} & 1\\\\ \\end{pmatrix} \\begin{pmatrix} u\_{11} & u\_{12} & u\_{13} \\\\ 0 & u\_{22} & u\_{23} \\\\ 0 & 0 & u\_{33} \\end{pmatrix} = \\begin{pmatrix} u\_{11} & u\_{12} & u\_{13} \\\\ u\_{11}l\_{21} & u\_{12}l\_{21}+u\_{22} & u\_{13}l\_{21}+u\_{23} \\\\ u\_{11}l\_{31} & u\_{12}l\_{31}+u\_{22}l\_{32} & u\_{13}l\_{31} + u\_{23}l\_{32}+u\_{33} \\end{pmatrix} = LU\\end{align}
|
||||
|
||||
Solving for the other $l$ and $u$, we get the following equations:
|
||||
$u_{11}=a_{11}$
|
||||
$u_{12}=a_{12}$
|
||||
$u_{13}=a_{13}$
|
||||
$u_{22}=a_{22} - u_{12}l_{21}$
|
||||
$u_{23}=a_{23} - u_{13}l_{21}$
|
||||
$u_{33}=a_{33} - (u_{13}l_{31} + u_{23}l_{32})$
|
||||
|
||||
$u\_{11}=a\_{11}$
|
||||
|
||||
$u\_{12}=a\_{12}$
|
||||
|
||||
$u\_{13}=a\_{13}$
|
||||
|
||||
$u\_{22}=a\_{22} - u\_{12}l\_{21}$
|
||||
|
||||
$u\_{23}=a\_{23} - u\_{13}l\_{21}$
|
||||
|
||||
$u\_{33}=a\_{33} - (u\_{13}l\_{31} + u\_{23}l\_{32})$
|
||||
|
||||
and for $l$:
|
||||
$l_{21}=\frac{1}{u_{11}} a_{21}$
|
||||
$l_{31}=\frac{1}{u_{11}} a_{31}$
|
||||
$l_{32}=\frac{1}{u_{22}} (a_{32} - u_{12}l_{31})$
|
||||
|
||||
$l\_{21}=\\frac{1}{u\_{11}} a\_{21}$
|
||||
|
||||
$l\_{31}=\\frac{1}{u\_{11}} a\_{31}$
|
||||
|
||||
$l\_{32}=\\frac{1}{u\_{22}} (a\_{32} - u\_{12}l\_{31})$
|
||||
|
||||
We see that there is a calculation pattern, which can be expressed as the following formulas, first for $U$
|
||||
$u_{ij} = a_{ij} - \sum_{k=1}^{i-1} u_{kj}l_{ik}$
|
||||
|
||||
$u\_{ij} = a\_{ij} - \\sum\_{k=1}^{i-1} u\_{kj}l\_{ik}$
|
||||
|
||||
and then for $L$
|
||||
$l_{ij} = \frac{1}{u_{jj}} (a_{ij} - \sum_{k=1}^{j-1} u_{kj}l_{ik})$
|
||||
We see in the second formula that to get the $l_{ij}$ below the diagonal, we have to divide by the diagonal element (pivot) $u_{jj}$, so we get problems when $u_{jj}$ is either 0 or very small, which leads to numerical instability.
|
||||
The solution to this problem is <i>pivoting</i> $A$, which means rearranging the rows of $A$, prior to the $LU$ decomposition, in a way that the largest element of each column gets onto the diagonal of $A$. Rearranging the rows means to multiply $A$ by a permutation matrix $P$:
|
||||
$PA \Rightarrow A'$
|
||||
|
||||
$l\_{ij} = \\frac{1}{u\_{jj}} (a\_{ij} - \\sum\_{k=1}^{j-1} u\_{kj}l\_{ik})$
|
||||
|
||||
We see in the second formula that to get the $l\_{ij}$ below the diagonal, we have to divide by the diagonal element (pivot) $u\_{jj}$, so we get problems when $u\_{jj}$ is either 0 or very small, which leads to numerical instability.
|
||||
|
||||
The solution to this problem is *pivoting* $A$, which means rearranging the rows of $A$, prior to the $LU$ decomposition, in a way that the largest element of each column gets onto the diagonal of $A$. Rearranging the rows means to multiply $A$ by a permutation matrix $P$:
|
||||
|
||||
$PA \\Rightarrow A'$
|
||||
|
||||
Example:
|
||||
\begin{align} \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \begin{pmatrix} 1 & 4 \\ 2 & 3 \end{pmatrix} \Rightarrow \begin{pmatrix} 2 & 3 \\ 1 & 4 \end{pmatrix} \end{align}
|
||||
|
||||
\\begin{align} \\begin{pmatrix} 0 & 1 \\\\ 1 & 0 \\end{pmatrix} \\begin{pmatrix} 1 & 4 \\\\ 2 & 3 \\end{pmatrix} \\Rightarrow \\begin{pmatrix} 2 & 3 \\\\ 1 & 4 \\end{pmatrix} \\end{align}
|
||||
|
||||
The decomposition algorithm is then applied on the rearranged matrix so that
|
||||
|
||||
$PA = LU$
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
The task is to implement a routine which will take a square nxn matrix $A$ and return a lower triangular matrix $L$, a upper triangular matrix $U$ and a permutation matrix $P$, so that the above equation is fullfilled. The returned value should be in the form <code>[L, U, P]</code>.
|
||||
</section>
|
||||
# --instructions--
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
The task is to implement a routine which will take a square nxn matrix $A$ and return a lower triangular matrix $L$, a upper triangular matrix $U$ and a permutation matrix $P$, so that the above equation is fullfilled. The returned value should be in the form `[L, U, P]`.
|
||||
|
||||
``` yml
|
||||
tests:
|
||||
- text: <code>luDecomposition</code> should be a function.
|
||||
testString: assert(typeof luDecomposition == 'function');
|
||||
- text: <code>luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])</code> should return a array.
|
||||
testString: assert(Array.isArray(luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])));
|
||||
- text: <code>luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])</code> should return <code>[[[1, 0, 0], [0.5, 1, 0], [0.5, -1, 1]], [[2, 4, 7], [0, 1, 1.5], [0, 0, -2]], [[0, 1, 0], [1, 0, 0], [0, 0, 1]]]</code>.
|
||||
testString: assert.deepEqual(luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]]), [[[1, 0, 0], [0.5, 1, 0], [0.5, -1, 1]], [[2, 4, 7], [0, 1, 1.5], [0, 0, -2]], [[0, 1, 0], [1, 0, 0], [0, 0, 1]]]);
|
||||
- text: <code>luDecomposition([[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]])</code> should return <code>[[[1, 0, 0, 0], [0.2727272727272727, 1, 0, 0], [0.09090909090909091, 0.2875, 1, 0], [0.18181818181818182, 0.23124999999999996, 0.0035971223021580693, 1]], [[11, 9, 24, 2], [0, 14.545454545454547, 11.454545454545455, 0.4545454545454546], [0, 0, -3.4749999999999996, 5.6875], [0, 0, 0, 0.510791366906476]], [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]]</code>.
|
||||
testString: assert.deepEqual(luDecomposition([[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]]), [[[1, 0, 0, 0], [0.2727272727272727, 1, 0, 0], [0.09090909090909091, 0.2875, 1, 0], [0.18181818181818182, 0.23124999999999996, 0.0035971223021580693, 1]], [[11, 9, 24, 2], [0, 14.545454545454547, 11.454545454545455, 0.4545454545454546], [0, 0, -3.4749999999999996, 5.6875], [0, 0, 0, 0.510791366906476]], [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]]);
|
||||
- text: <code>luDecomposition([[1, 1, 1], [4, 3, -1], [3, 5, 3]])</code> should return <code>[[[1, 0, 0], [0.75, 1, 0], [0.25, 0.09090909090909091, 1]], [[4, 3, -1], [0, 2.75, 3.75], [0, 0, 0.9090909090909091]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]</code>.
|
||||
testString: assert.deepEqual(luDecomposition([[1, 1, 1], [4, 3, -1], [3, 5, 3]]), [[[1, 0, 0], [0.75, 1, 0], [0.25, 0.09090909090909091, 1]], [[4, 3, -1], [0, 2.75, 3.75], [0, 0, 0.9090909090909091]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]);
|
||||
- text: <code>luDecomposition([[1, -2, 3], [2, -5, 12], [0, 2, -10]])</code> should return <code>[[[1, 0, 0], [0, 1, 0], [0.5, 0.25, 1]], [[2, -5, 12], [0, 2, -10], [0, 0, -0.5]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]</code>.
|
||||
testString: assert.deepEqual(luDecomposition([[1, -2, 3], [2, -5, 12], [0, 2, -10]]), [[[1, 0, 0], [0, 1, 0], [0.5, 0.25, 1]], [[2, -5, 12], [0, 2, -10], [0, 0, -0.5]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]);
|
||||
# --hints--
|
||||
|
||||
`luDecomposition` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof luDecomposition == 'function');
|
||||
```
|
||||
|
||||
</section>
|
||||
`luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])` should return a array.
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
```js
|
||||
assert(
|
||||
Array.isArray(
|
||||
luDecomposition([
|
||||
[1, 3, 5],
|
||||
[2, 4, 7],
|
||||
[1, 1, 0]
|
||||
])
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
<div id='js-seed'>
|
||||
`luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])` should return `[[[1, 0, 0], [0.5, 1, 0], [0.5, -1, 1]], [[2, 4, 7], [0, 1, 1.5], [0, 0, -2]], [[0, 1, 0], [1, 0, 0], [0, 0, 1]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
luDecomposition([
|
||||
[1, 3, 5],
|
||||
[2, 4, 7],
|
||||
[1, 1, 0]
|
||||
]),
|
||||
[
|
||||
[
|
||||
[1, 0, 0],
|
||||
[0.5, 1, 0],
|
||||
[0.5, -1, 1]
|
||||
],
|
||||
[
|
||||
[2, 4, 7],
|
||||
[0, 1, 1.5],
|
||||
[0, 0, -2]
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 0, 0],
|
||||
[0, 0, 1]
|
||||
]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]])` should return `[[[1, 0, 0, 0], [0.2727272727272727, 1, 0, 0], [0.09090909090909091, 0.2875, 1, 0], [0.18181818181818182, 0.23124999999999996, 0.0035971223021580693, 1]], [[11, 9, 24, 2], [0, 14.545454545454547, 11.454545454545455, 0.4545454545454546], [0, 0, -3.4749999999999996, 5.6875], [0, 0, 0, 0.510791366906476]], [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
luDecomposition([
|
||||
[11, 9, 24, 2],
|
||||
[1, 5, 2, 6],
|
||||
[3, 17, 18, 1],
|
||||
[2, 5, 7, 1]
|
||||
]),
|
||||
[
|
||||
[
|
||||
[1, 0, 0, 0],
|
||||
[0.2727272727272727, 1, 0, 0],
|
||||
[0.09090909090909091, 0.2875, 1, 0],
|
||||
[0.18181818181818182, 0.23124999999999996, 0.0035971223021580693, 1]
|
||||
],
|
||||
[
|
||||
[11, 9, 24, 2],
|
||||
[0, 14.545454545454547, 11.454545454545455, 0.4545454545454546],
|
||||
[0, 0, -3.4749999999999996, 5.6875],
|
||||
[0, 0, 0, 0.510791366906476]
|
||||
],
|
||||
[
|
||||
[1, 0, 0, 0],
|
||||
[0, 0, 1, 0],
|
||||
[0, 1, 0, 0],
|
||||
[0, 0, 0, 1]
|
||||
]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[1, 1, 1], [4, 3, -1], [3, 5, 3]])` should return `[[[1, 0, 0], [0.75, 1, 0], [0.25, 0.09090909090909091, 1]], [[4, 3, -1], [0, 2.75, 3.75], [0, 0, 0.9090909090909091]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
luDecomposition([
|
||||
[1, 1, 1],
|
||||
[4, 3, -1],
|
||||
[3, 5, 3]
|
||||
]),
|
||||
[
|
||||
[
|
||||
[1, 0, 0],
|
||||
[0.75, 1, 0],
|
||||
[0.25, 0.09090909090909091, 1]
|
||||
],
|
||||
[
|
||||
[4, 3, -1],
|
||||
[0, 2.75, 3.75],
|
||||
[0, 0, 0.9090909090909091]
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 0, 1],
|
||||
[1, 0, 0]
|
||||
]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[1, -2, 3], [2, -5, 12], [0, 2, -10]])` should return `[[[1, 0, 0], [0, 1, 0], [0.5, 0.25, 1]], [[2, -5, 12], [0, 2, -10], [0, 0, -0.5]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
luDecomposition([
|
||||
[1, -2, 3],
|
||||
[2, -5, 12],
|
||||
[0, 2, -10]
|
||||
]),
|
||||
[
|
||||
[
|
||||
[1, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0.5, 0.25, 1]
|
||||
],
|
||||
[
|
||||
[2, -5, 12],
|
||||
[0, 2, -10],
|
||||
[0, 0, -0.5]
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 0, 1],
|
||||
[1, 0, 0]
|
||||
]
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function luDecomposition(A) {
|
||||
@ -81,12 +233,7 @@ function luDecomposition(A) {
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function luDecomposition(A) {
|
||||
@ -168,5 +315,3 @@ function luDecomposition(A) {
|
||||
return [L, U, P];
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user