feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
This commit is contained in:
committed by
GitHub
parent
0095583028
commit
ee1e8abd87
@ -3,6 +3,7 @@ id: 594810f028c0303b75339acb
|
||||
title: 100门
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: 100-doors
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -29,5 +30,34 @@ assert(Array.isArray(getFinalOpenedDoors(100)));
|
||||
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) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getFinalOpenedDoors(numDoors) {
|
||||
// this is the final pattern (always squares).
|
||||
// thus, the most efficient solution simply returns an array of squares up to numDoors).
|
||||
const finalState = [];
|
||||
let i = 1;
|
||||
while (Math.pow(i, 2) <= numDoors) {
|
||||
finalState.push(Math.pow(i, 2));
|
||||
i++;
|
||||
}
|
||||
return finalState;
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 5951e88f64ebf159166a1176
|
||||
title: 24场比赛
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: 24-game
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>实现一个以四位数字串为参数的函数,每个数字从1──►9(含),允许重复,并返回一个算术表达式,其值为24。如果不存在这样的解,则返回“没有解决方案。“ </p><p>规则: </p>只允许以下运算符/函数:乘法,除法,加法,减法除法应使用浮点或有理算术等来保留余数。不允许从提供的数字中形成多位数字。 (所以当给出1,2,2和1时,12 + 12的答案是错误的)。给定的数字顺序不必保留。 <p>示例输入: </p> <code>solve24("4878");</code> <code>solve24("1234");</code> <code>solve24("6789");</code> <code>solve24("1127");</code> <p>示例输出(字符串): </p> <code>(7-8/8)\*4</code> <code>3\*1\*4\*2</code> <code>(6\*8)/(9-7)</code> <code>(1+7)\*(2+1)</code>
|
||||
<p>实现一个以四位数字串为参数的函数,每个数字从1──►9(含),允许重复,并返回一个算术表达式,其值为24。如果不存在这样的解,则返回“没有解决方案。“ </p><p>规则: </p>只允许以下运算符/函数:乘法,除法,加法,减法除法应使用浮点或有理算术等来保留余数。不允许从提供的数字中形成多位数字。 (所以当给出1,2,2和1时,12 + 12的答案是错误的)。给定的数字顺序不必保留。 <p>示例输入: </p> <code>solve24("4878");</code> <code>solve24("1234");</code> <code>solve24("6789");</code> <code>solve24("1127");</code> <p>示例输出(字符串): </p> <code>(7-8/8)\*4</code> <code>3\*1\*4\*2</code> <code>(6\*8)/(9-7)</code> <code>(1+7)\*(2+1)</code>
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -41,5 +42,141 @@ assert(include(answers[2], solve24(testCases[2])));
|
||||
assert(include(answers[3], solve24(testCases[3])));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
'4878',
|
||||
'1234',
|
||||
'6789',
|
||||
'1127'
|
||||
];
|
||||
|
||||
const answers = [
|
||||
['(7-8/8)*4', '4*(7-8/8)', '(4-8+7)*8', '(4+7-8)*8', '(7+4-8)*8', '(7-8+4)*8', '8*(4-8+7)', '8*(4+7-8)', '8*(7+4-8)', '8*(7-8+4)'],
|
||||
['1*2*3*4', '1*2*4*3', '1*3*2*4', '1*3*4*2', '1*4*2*3', '1*4*3*2', '2*1*3*4', '2*1*4*3', '2*3*1*4', '2*3*4*1', '2*4*3*1', '2*4*1*3', '3*1*2*4', '3*1*4*2', '3*2*1*4', '3*2*4*1', '3*4*1*2', '3*4*2*1', '4*1*2*3', '4*1*3*2', '4*2*1*3', '4*2*3*1', '4*3*1*2', '4*3*2*1', '(1+2+3)*4', '(1+3+2)*4', '(2+1+3)*4', '(2+3+1)*4', '(3+1+2)*4', '(3+2+1)*4', '4*(1+2+3)', '4*(2+1+3)', '4*(2+3+1)', '4*(3+1+2)', '4*(3+2+1)'],
|
||||
['(6*8)/(9-7)', '(8*6)/(9-7)', '6*8/(9-7)', '8*6/(9-7)'],
|
||||
['(1+7)*(2+1)', '(1+7)*(1+2)', '(1+2)*(1+7)', '(1+2)*(7+1)', '(2+1)*(1+7)', '(7+1)*(2+1)']
|
||||
];
|
||||
|
||||
function include(ansArr, res) {
|
||||
const index = ansArr.indexOf(res);
|
||||
return index >= 0;
|
||||
}
|
||||
|
||||
//The main method for detecting single parentheses
|
||||
function removeParentheses(ans) {
|
||||
for (let i = 0; i < ans.length; i++) {
|
||||
if (!isNaN(ans[i])) {
|
||||
ans = removeParenthesesHelper(ans, i);
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
//Helper to remove left and right parantheses
|
||||
function removeParenthesesHelper(ans, i) {
|
||||
while (i > 0 && i < ans.length - 1) {
|
||||
if (ans[i - 1] === '(' && ans[i + 1] === ')') {
|
||||
//Paranthesis detected. Remove them.
|
||||
ans = replaceChar(ans, '', i - 1);
|
||||
ans = replaceChar(ans, '', i);
|
||||
i--;
|
||||
} else {
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
//Replace a character at a given index for the provided character
|
||||
function replaceChar(origString, replaceChar, index) {
|
||||
let firstPart = origString.substr(0, index);
|
||||
let lastPart = origString.substr(index + 1);
|
||||
let newString = firstPart + replaceChar + lastPart;
|
||||
return newString;
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function solve24 (numStr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function solve24(numStr) {
|
||||
const digitsArr = numStr.split('');
|
||||
const answers = [];
|
||||
|
||||
const digitPermutations = [];
|
||||
const operatorPermutations = [];
|
||||
|
||||
function generateDigitPermutations (digits, permutations = []) {
|
||||
if (digits.length === 0) {
|
||||
digitPermutations.push(permutations);
|
||||
}
|
||||
else {
|
||||
for (let i = 0; i < digits.length; i++) {
|
||||
const curr = digits.slice();
|
||||
const next = curr.splice(i, 1);
|
||||
generateDigitPermutations(curr.slice(), permutations.concat(next));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function generateOperatorPermutations (permutations = []) {
|
||||
const operators = ['+', '-', '*', '/'];
|
||||
if (permutations.length === 3) {
|
||||
operatorPermutations.push(permutations);
|
||||
}
|
||||
else {
|
||||
for (let i = 0; i < operators.length; i++) {
|
||||
const curr = permutations.slice();
|
||||
curr.push(operators[i]);
|
||||
generateOperatorPermutations(curr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
generateDigitPermutations(digitsArr);
|
||||
generateOperatorPermutations();
|
||||
|
||||
interleave();
|
||||
|
||||
return answers[0];
|
||||
|
||||
function interleave () {
|
||||
for (let i = 0; i < digitPermutations.length; i++) {
|
||||
for (let j = 0; j < operatorPermutations.length; j++) {
|
||||
const d = digitPermutations[i];
|
||||
const o = operatorPermutations[j];
|
||||
const perm = [
|
||||
`${d[0]}${o[0]}${d[1]}${o[1]}${d[2]}${o[2]}${d[3]}`,
|
||||
`(${d[0]}${o[0]}${d[1]})${o[1]}${d[2]}${o[2]}${d[3]}`,
|
||||
`${d[0]}${o[0]}(${d[1]}${o[1]}${d[2]})${o[2]}${d[3]}`,
|
||||
`${d[0]}${o[0]}${d[1]}${o[1]}(${d[2]}${o[2]}${d[3]})`,
|
||||
`${d[0]}${o[0]}(${d[1]}${o[1]}${d[2]}${o[2]}${d[3]})`,
|
||||
`(${d[0]}${o[0]}${d[1]}${o[1]}${d[2]})${o[2]}${d[3]}`,
|
||||
`(${d[0]}${o[0]}${d[1]})${o[1]}(${d[2]}${o[2]}${d[3]})`
|
||||
];
|
||||
|
||||
perm.forEach(combination => {
|
||||
const res = eval(combination);
|
||||
|
||||
if (res === 24) {
|
||||
return answers.push(combination);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5949b579404977fbaefcd736
|
||||
title: 90亿上帝的名字整数
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: 9-billion-names-of-god-the-integer
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -59,5 +60,33 @@ assert.equal(numberOfNames(42), 53174);
|
||||
assert.equal(numberOfNames(123), 2552338241);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function numberOfNames(num) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function numberOfNames(num) {
|
||||
const cache = [
|
||||
[1]
|
||||
];
|
||||
for (let l = cache.length; l < num + 1; l++) {
|
||||
let Aa;
|
||||
let Mi;
|
||||
const r = [0];
|
||||
for (let x = 1; x < l + 1; x++) {
|
||||
r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);
|
||||
}
|
||||
cache.push(r);
|
||||
}
|
||||
return cache[num][cache[num].length - 1];
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594810f028c0303b75339acc
|
||||
title: ABC问题
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: abc-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -59,5 +60,44 @@ assert(canMakeWord(words[4]));
|
||||
assert(canMakeWord(words[5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const words = ['bark', 'BooK', 'TReAT', 'COMMON', 'squAD', 'conFUSE'];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function canMakeWord(word) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function canMakeWord(word) {
|
||||
const characters = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM';
|
||||
const blocks = characters.split(' ').map(pair => pair.split(''));
|
||||
|
||||
const letters = [...word.toUpperCase()];
|
||||
let length = letters.length;
|
||||
const copy = new Set(blocks);
|
||||
|
||||
letters.forEach(letter => {
|
||||
for (let block of copy) {
|
||||
const index = block.indexOf(letter);
|
||||
|
||||
if (index !== -1) {
|
||||
length--;
|
||||
copy.delete(block);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
return !length;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594810f028c0303b75339acd
|
||||
title: 丰富,不足和完善的数字分类
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: abundant-deficient-and-perfect-number-classifications
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -35,5 +36,40 @@ assert(getDPA(100).length === 3);
|
||||
assert.deepEqual(getDPA(20000), solution);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const solution = [15043, 4, 4953];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getDPA(num) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getDPA(num) {
|
||||
const dpa = [1, 0, 0];
|
||||
for (let n = 2; n <= num; n += 1) {
|
||||
let ds = 1;
|
||||
const e = Math.sqrt(n);
|
||||
for (let d = 2; d < e; d += 1) {
|
||||
if (n % d === 0) {
|
||||
ds += d + (n / d);
|
||||
}
|
||||
}
|
||||
if (n % e === 0) {
|
||||
ds += e;
|
||||
}
|
||||
dpa[ds < n ? 0 : ds === n ? 1 : 2] += 1;
|
||||
}
|
||||
return dpa;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594810f028c0303b75339ace
|
||||
title: 蓄能器工厂
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: accumulator-factory
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -35,5 +36,32 @@ assert(typeof accumulator(0)(2) === 'number');
|
||||
assert(testFn(5) === 5.5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testFn = typeof accumulator(3) === 'function' && accumulator(3);
|
||||
if (testFn) {
|
||||
testFn(-4);
|
||||
testFn(1.5);
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function accumulator(sum) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function accumulator(sum) {
|
||||
return function(n) {
|
||||
return sum += n;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594810f028c0303b75339acf
|
||||
title: 阿克曼功能
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: ackermann-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -41,5 +42,20 @@ assert(ack(2, 5) === 13);
|
||||
assert(ack(3, 3) === 61);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function ack(m, n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function ack(m, n) {
|
||||
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594810f028c0303b75339ad0
|
||||
title: 对齐列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: align-columns
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -17,7 +18,7 @@ videoUrl: ''
|
||||
此外,$允许为$ $ $中的每个字$ $ A $ $列到$为$要么离开$ $
|
||||
对齐,右$ $有道理
|
||||
或$ $中心内$有道理$ $其列。
|
||||
</pre><p>注意: </p>示例输入文本行可以或可以不具有尾随美元字符。所有列应共享相同的对齐方式。为了完成任务,在行尾附近产生的连续空格字符是无关紧要的。输出文本将以纯文本编辑器或基本终端上的单行间隔字体查看。列之间的最小间距应根据文本计算,而不是硬编码。不需要在列之间或列周围添加分隔字符。
|
||||
</pre><p>注意: </p>示例输入文本行可以或可以不具有尾随美元字符。所有列应共享相同的对齐方式。为了完成任务,在行尾附近产生的连续空格字符是无关紧要的。输出文本将以纯文本编辑器或基本终端上的单行间隔字体查看。列之间的最小间距应根据文本计算,而不是硬编码。不需要在列之间或列周围添加分隔字符。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -45,5 +46,131 @@ assert.strictEqual(formatText(testInput, 'left'), leftAligned);
|
||||
assert.strictEqual(formatText(testInput, 'center'), centerAligned);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testInput = [
|
||||
'Given$a$text$file$of$many$lines',
|
||||
'where$fields$within$a$line$',
|
||||
'are$delineated$by$a$single$\"dollar\"$character',
|
||||
'write$a$program',
|
||||
'that$aligns$each$column$of$fields$',
|
||||
'by$ensuring$that$words$in$each$',
|
||||
'column$are$separated$by$at$least$one$space.',
|
||||
'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
|
||||
'justified,$right$justified',
|
||||
'or$center$justified$within$its$column.'
|
||||
];
|
||||
|
||||
const rightAligned = ' Given a text file of many lines\n' +
|
||||
' where fields within a line \n' +
|
||||
' are delineated by a single "dollar" character\n' +
|
||||
' write a program\n' +
|
||||
' that aligns each column of fields \n' +
|
||||
' by ensuring that words in each \n' +
|
||||
' column are separated by at least one space.\n' +
|
||||
' Further, allow for each word in a column to be either left \n' +
|
||||
'justified, right justified\n' +
|
||||
' or center justified within its column.';
|
||||
|
||||
const leftAligned = 'Given a text file of many lines \n' +
|
||||
'where fields within a line \n' +
|
||||
'are delineated by a single "dollar" character\n' +
|
||||
'write a program \n' +
|
||||
'that aligns each column of fields \n' +
|
||||
'by ensuring that words in each \n' +
|
||||
'column are separated by at least one space.\n' +
|
||||
'Further, allow for each word in a column to be either left \n' +
|
||||
'justified, right justified\n' +
|
||||
'or center justified within its column. ';
|
||||
|
||||
const centerAligned = ' Given a text file of many lines \n' +
|
||||
' where fields within a line \n' +
|
||||
' are delineated by a single \"dollar\" character\n' +
|
||||
' write a program \n' +
|
||||
' that aligns each column of fields \n' +
|
||||
' by ensuring that words in each \n' +
|
||||
' column are separated by at least one space.\n' +
|
||||
' Further, allow for each word in a column to be either left \n' +
|
||||
'justified, right justified\n' +
|
||||
' or center justified within its column. ';
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```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) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const testArr = [
|
||||
'Given$a$text$file$of$many$lines',
|
||||
'where$fields$within$a$line$',
|
||||
'are$delineated$by$a$single$"dollar"$character',
|
||||
'write$a$program',
|
||||
'that$aligns$each$column$of$fields$',
|
||||
'by$ensuring$that$words$in$each$',
|
||||
'column$are$separated$by$at$least$one$space.',
|
||||
'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
|
||||
'justified,$right$justified',
|
||||
'or$center$justified$within$its$column.'
|
||||
];
|
||||
|
||||
String.prototype.repeat = function (n) { return new Array(1 + parseInt(n)).join(this); };
|
||||
|
||||
function formatText(input, justification) {
|
||||
let x, y, max, cols = 0, diff, left, right;
|
||||
for (x = 0; x < input.length; x++) {
|
||||
input[x] = input[x].split('$');
|
||||
if (input[x].length > cols) {
|
||||
cols = input[x].length;
|
||||
}
|
||||
}
|
||||
for (x = 0; x < cols; x++) {
|
||||
max = 0;
|
||||
for (y = 0; y < input.length; y++) {
|
||||
if (input[y][x] && max < input[y][x].length) {
|
||||
max = input[y][x].length;
|
||||
}
|
||||
}
|
||||
for (y = 0; y < input.length; y++) {
|
||||
if (input[y][x]) {
|
||||
diff = (max - input[y][x].length) / 2;
|
||||
left = ' '.repeat(Math.floor(diff));
|
||||
right = ' '.repeat(Math.ceil(diff));
|
||||
if (justification === 'left') {
|
||||
right += left; left = '';
|
||||
}
|
||||
if (justification === 'right') {
|
||||
left += right; right = '';
|
||||
}
|
||||
input[y][x] = left + input[y][x] + right;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x = 0; x < input.length; x++) {
|
||||
input[x] = input[x].join(' ');
|
||||
}
|
||||
input = input.join('\n');
|
||||
return input;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5949b579404977fbaefcd737
|
||||
title: 友好的对
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: amicable-pairs
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -35,5 +36,78 @@ assert.deepEqual(amicablePairsUpTo(3000), answer3000);
|
||||
assert.deepEqual(amicablePairsUpTo(20000), answer20000);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const answer300 = [[220, 284]];
|
||||
const answer3000 = [
|
||||
[220, 284],
|
||||
[1184, 1210],
|
||||
[2620, 2924]
|
||||
];
|
||||
const answer20000 = [
|
||||
[220, 284],
|
||||
[1184, 1210],
|
||||
[2620, 2924],
|
||||
[5020, 5564],
|
||||
[6232, 6368],
|
||||
[10744, 10856],
|
||||
[12285, 14595],
|
||||
[17296, 18416]
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function amicablePairsUpTo(maxNum) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// amicablePairsUpTo :: Int -> [(Int, Int)]
|
||||
function amicablePairsUpTo(maxNum) {
|
||||
return range(1, maxNum)
|
||||
.map(x => properDivisors(x)
|
||||
.reduce((a, b) => a + b, 0))
|
||||
.reduce((a, m, i, lst) => {
|
||||
const n = i + 1;
|
||||
|
||||
return (m > n) && lst[m - 1] === n ?
|
||||
a.concat([
|
||||
[n, m]
|
||||
]) : a;
|
||||
}, []);
|
||||
}
|
||||
|
||||
// properDivisors :: Int -> [Int]
|
||||
function properDivisors(n) {
|
||||
if (n < 2) return [];
|
||||
|
||||
const rRoot = Math.sqrt(n);
|
||||
const intRoot = Math.floor(rRoot);
|
||||
const blnPerfectSquare = rRoot === intRoot;
|
||||
const lows = range(1, intRoot)
|
||||
.filter(x => (n % x) === 0);
|
||||
|
||||
return lows.concat(lows.slice(1)
|
||||
.map(x => n / x)
|
||||
.reverse()
|
||||
.slice(blnPerfectSquare | 0));
|
||||
}
|
||||
|
||||
// Int -> Int -> Maybe Int -> [Int]
|
||||
function range(m, n, step) {
|
||||
const d = (step || 1) * (n >= m ? 1 : -1);
|
||||
|
||||
return Array.from({
|
||||
length: Math.floor((n - m) / d) + 1
|
||||
}, (_, i) => m + (i * d));
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594d8d0ab97724821379b1e6
|
||||
title: 平均值模式
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: averagesmode
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -29,5 +30,46 @@ assert.deepEqual(mode(arr1), [6]);
|
||||
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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mode(arr) {
|
||||
const counter = {};
|
||||
let result = [];
|
||||
let max = 0;
|
||||
// for (const i in arr) {
|
||||
arr.forEach(el => {
|
||||
if (!(el in counter)) {
|
||||
counter[el] = 0;
|
||||
}
|
||||
counter[el]++;
|
||||
|
||||
if (counter[el] === max) {
|
||||
result.push(el);
|
||||
}
|
||||
else if (counter[el] > max) {
|
||||
max = counter[el];
|
||||
result = [el];
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594d966a1467eb84194f0086
|
||||
title: 平均值 - 毕达哥拉斯指的是
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: averagespythagorean-means
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -31,5 +32,93 @@ assert(typeof pythagoreanMeans === 'function');
|
||||
assert.deepEqual(pythagoreanMeans(range1), answer1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const range1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
const answer1 = {
|
||||
values: {
|
||||
Arithmetic: 5.5,
|
||||
Geometric: 4.528728688116765,
|
||||
Harmonic: 3.414171521474055
|
||||
},
|
||||
test: 'is A >= G >= H ? yes'
|
||||
};
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function pythagoreanMeans(rangeArr) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pythagoreanMeans(rangeArr) {
|
||||
// arithmeticMean :: [Number] -> Number
|
||||
const arithmeticMean = xs =>
|
||||
foldl((sum, n) => sum + n, 0, xs) / length(xs);
|
||||
|
||||
// geometricMean :: [Number] -> Number
|
||||
const geometricMean = xs =>
|
||||
raise(foldl((product, x) => product * x, 1, xs), 1 / length(xs));
|
||||
|
||||
// harmonicMean :: [Number] -> Number
|
||||
const harmonicMean = xs =>
|
||||
length(xs) / foldl((invSum, n) => invSum + (1 / n), 0, xs);
|
||||
|
||||
// GENERIC FUNCTIONS ------------------------------------------------------
|
||||
|
||||
// A list of functions applied to a list of arguments
|
||||
// <*> :: [(a -> b)] -> [a] -> [b]
|
||||
const ap = (fs, xs) => //
|
||||
Array.prototype.concat(...fs.map(f => //
|
||||
Array.prototype.concat(...xs.map(x => [f(x)]))));
|
||||
|
||||
// foldl :: (b -> a -> b) -> b -> [a] -> b
|
||||
const foldl = (f, a, xs) => xs.reduce(f, a);
|
||||
|
||||
// length :: [a] -> Int
|
||||
const length = xs => xs.length;
|
||||
|
||||
// mapFromList :: [(k, v)] -> Dictionary
|
||||
const mapFromList = kvs =>
|
||||
foldl((a, [k, v]) =>
|
||||
(a[(typeof k === 'string' && k)] = v, a), {}, kvs);
|
||||
|
||||
// raise :: Num -> Int -> Num
|
||||
const raise = (n, e) => Math.pow(n, e);
|
||||
/*
|
||||
// show :: a -> String
|
||||
// show :: a -> Int -> String
|
||||
const show = (...x) =>
|
||||
JSON.stringify.apply(
|
||||
null, x.length > 1 ? [x[0], null, x[1]] : x
|
||||
);
|
||||
*/
|
||||
// zip :: [a] -> [b] -> [(a,b)]
|
||||
const zip = (xs, ys) =>
|
||||
xs.slice(0, Math.min(xs.length, ys.length))
|
||||
.map((x, i) => [x, ys[i]]);
|
||||
|
||||
// TEST -------------------------------------------------------------------
|
||||
// mean :: Dictionary
|
||||
const mean = mapFromList(zip(
|
||||
['Arithmetic', 'Geometric', 'Harmonic'],
|
||||
ap([arithmeticMean, geometricMean, harmonicMean], [
|
||||
rangeArr
|
||||
])
|
||||
));
|
||||
|
||||
return {
|
||||
values: mean,
|
||||
test: `is A >= G >= H ? ${mean.Arithmetic >= mean.Geometric &&
|
||||
mean.Geometric >= mean.Harmonic ? 'yes' : 'no'}`
|
||||
};
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594da033de4190850b893874
|
||||
title: 平均值 - 均方根
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: averagesroot-mean-square
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -23,5 +24,28 @@ assert(typeof rms === 'function');
|
||||
assert.equal(rms(arr1), answer1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
const answer1 = 6.2048368229954285;
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function rms(arr) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function rms(arr) {
|
||||
const sumOfSquares = arr.reduce((s, x) => s + x * x, 0);
|
||||
return Math.sqrt(sumOfSquares / arr.length);
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594db4d0dedb4c06a2a4cefd
|
||||
title: 巴贝奇问题
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: babbage-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -23,5 +24,42 @@ assert(typeof babbage === 'function');
|
||||
assert.equal(babbage(babbageAns, endDigits), answer);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const babbageAns = 99736;
|
||||
const endDigits = 269696;
|
||||
const answer = 25264;
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function babbage(babbageNum, endDigits) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function babbage(babbageAns, endDigits) {
|
||||
const babbageNum = Math.pow(babbageAns, 2);
|
||||
const babbageStartDigits = parseInt(babbageNum.toString().replace('269696', ''));
|
||||
let answer = 99736;
|
||||
|
||||
// count down from this answer and save any sqrt int result. return lowest one
|
||||
for (let i = babbageStartDigits; i >= 0; i--) {
|
||||
const num = parseInt(i.toString().concat('269696'));
|
||||
const result = Math.sqrt(num);
|
||||
if (result === Math.floor(Math.sqrt(num))) {
|
||||
answer = result;
|
||||
}
|
||||
}
|
||||
|
||||
return answer;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594dc6c729e5700999302b45
|
||||
title: 平衡括号
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: balanced-brackets
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -125,5 +126,53 @@ assert(!isBalanced(testCases[16]));
|
||||
assert(isBalanced(testCases[17]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
'[]',
|
||||
']][[[][][][]][',
|
||||
'[][[[[][][[[]]]]]]',
|
||||
'][',
|
||||
'[[[]]]][[]',
|
||||
'][[]',
|
||||
'][[][]][[[]]',
|
||||
'[[][]]][',
|
||||
'[[[]]][[]]]][][[',
|
||||
'[]][[]]][[[[][]]',
|
||||
'][]][[][',
|
||||
'[[]][[][]]',
|
||||
'[[]]',
|
||||
']][]][[]][[[',
|
||||
'][]][][[',
|
||||
'][][',
|
||||
'[]]]',
|
||||
''
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isBalanced(str) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isBalanced(str) {
|
||||
if (str === '') return true;
|
||||
let a = str;
|
||||
let b;
|
||||
do {
|
||||
b = a;
|
||||
a = a.replace(/\[\]/g, '');
|
||||
} while (a !== b);
|
||||
return !a;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5951815dd895584b06884620
|
||||
title: 给定半径的圆圈通过两个点
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: circles-of-given-radius-through-two-points
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -53,5 +54,72 @@ assert.deepEqual(getCircles(...testCases[3]), answers[3]);
|
||||
assert.deepEqual(getCircles(...testCases[4]), answers[4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
[[0.1234, 0.9876], [0.8765, 0.2345], 2.0],
|
||||
[[0.0000, 2.0000], [0.0000, 0.0000], 1.0],
|
||||
[[0.1234, 0.9876], [0.1234, 0.9876], 2.0],
|
||||
[[0.1234, 0.9876], [0.8765, 0.2345], 0.5],
|
||||
[[0.1234, 0.9876], [0.1234, 0.9876], 0.0]
|
||||
];
|
||||
const answers = [
|
||||
[[1.8631, 1.9742], [-0.8632, -0.7521]],
|
||||
[0, 1],
|
||||
'Coincident point. Infinite solutions',
|
||||
'No intersection. Points further apart than circle diameter',
|
||||
'Radius Zero'
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getCircles(...args) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;
|
||||
const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1));
|
||||
const solveF = (p, r) => t => [parseFloat((r * Math.cos(t) + p[0]).toFixed(4)), parseFloat((r * Math.sin(t) + p[1]).toFixed(4))];
|
||||
const diamPoints = (p1, p2) => p1.map((e, i) => parseFloat((e + (p2[i] - e) / 2).toFixed(4)));
|
||||
|
||||
function getCircles(...args) {
|
||||
const [p1, p2, s] = args;
|
||||
const solve = solveF(p1, s);
|
||||
const halfDist = hDist(p1, p2);
|
||||
|
||||
let msg = [];
|
||||
switch (Math.sign(s - halfDist)) {
|
||||
case 0:
|
||||
msg = s ? diamPoints(p1, p2) :
|
||||
'Radius Zero';
|
||||
break;
|
||||
case 1:
|
||||
if (!halfDist) {
|
||||
msg = 'Coincident point. Infinite solutions';
|
||||
}
|
||||
else {
|
||||
const theta = pAng(p1, p2);
|
||||
const theta2 = Math.acos(halfDist / s);
|
||||
[1, -1].map(e => solve(theta + e * theta2)).forEach(
|
||||
e => msg.push(e));
|
||||
}
|
||||
break;
|
||||
case -1:
|
||||
msg = 'No intersection. Points further apart than circle diameter';
|
||||
break;
|
||||
default:
|
||||
msg = 'Reached the default';
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5951a53863c8a34f02bf1bdc
|
||||
title: 最近对的问题
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: closest-pair-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -103,5 +104,250 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
# --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)
|
||||
];
|
||||
|
||||
const points2 = [
|
||||
new Point(37100, 13118),
|
||||
new Point(37134, 1963),
|
||||
new Point(37181, 2008),
|
||||
new Point(37276, 21611),
|
||||
new Point(37307, 9320)
|
||||
];
|
||||
|
||||
const answer1 = {
|
||||
distance: 0.0894096443343775,
|
||||
pair: [
|
||||
{
|
||||
x: 7.46489,
|
||||
y: 4.6268
|
||||
},
|
||||
{
|
||||
x: 7.46911,
|
||||
y: 4.71611
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const answer2 = {
|
||||
distance: 65.06919393998976,
|
||||
pair: [
|
||||
{
|
||||
x: 37134,
|
||||
y: 1963
|
||||
},
|
||||
{
|
||||
x: 37181,
|
||||
y: 2008
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const benchmarkPoints = [
|
||||
new Point(16909, 54699),
|
||||
new Point(14773, 61107),
|
||||
new Point(95547, 45344),
|
||||
new Point(95951, 17573),
|
||||
new Point(5824, 41072),
|
||||
new Point(8769, 52562),
|
||||
new Point(21182, 41881),
|
||||
new Point(53226, 45749),
|
||||
new Point(68180, 887),
|
||||
new Point(29322, 44017),
|
||||
new Point(46817, 64975),
|
||||
new Point(10501, 483),
|
||||
new Point(57094, 60703),
|
||||
new Point(23318, 35472),
|
||||
new Point(72452, 88070),
|
||||
new Point(67775, 28659),
|
||||
new Point(19450, 20518),
|
||||
new Point(17314, 26927),
|
||||
new Point(98088, 11164),
|
||||
new Point(25050, 56835),
|
||||
new Point(8364, 6892),
|
||||
new Point(37868, 18382),
|
||||
new Point(23723, 7701),
|
||||
new Point(55767, 11569),
|
||||
new Point(70721, 66707),
|
||||
new Point(31863, 9837),
|
||||
new Point(49358, 30795),
|
||||
new Point(13041, 39745),
|
||||
new Point(59635, 26523),
|
||||
new Point(25859, 1292),
|
||||
new Point(1551, 53890),
|
||||
new Point(70316, 94479),
|
||||
new Point(48549, 86338),
|
||||
new Point(46413, 92747),
|
||||
new Point(27186, 50426),
|
||||
new Point(27591, 22655),
|
||||
new Point(10905, 46153),
|
||||
new Point(40408, 84202),
|
||||
new Point(52821, 73520),
|
||||
new Point(84865, 77388),
|
||||
new Point(99819, 32527),
|
||||
new Point(34404, 75657),
|
||||
new Point(78457, 96615),
|
||||
new Point(42140, 5564),
|
||||
new Point(62175, 92342),
|
||||
new Point(54958, 67112),
|
||||
new Point(4092, 19709),
|
||||
new Point(99415, 60298),
|
||||
new Point(51090, 52158),
|
||||
new Point(48953, 58567)
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const Point = function(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
};
|
||||
Point.prototype.getX = function() {
|
||||
return this.x;
|
||||
};
|
||||
Point.prototype.getY = function() {
|
||||
return this.y;
|
||||
};
|
||||
|
||||
const mergeSort = function mergeSort(points, comp) {
|
||||
if(points.length < 2) return points;
|
||||
|
||||
var n = points.length,
|
||||
i = 0,
|
||||
j = 0,
|
||||
leftN = Math.floor(n / 2),
|
||||
rightN = leftN;
|
||||
|
||||
var leftPart = mergeSort( points.slice(0, leftN), comp),
|
||||
rightPart = mergeSort( points.slice(rightN), comp );
|
||||
|
||||
var sortedPart = [];
|
||||
|
||||
while((i < leftPart.length) && (j < rightPart.length)) {
|
||||
if(comp(leftPart[i], rightPart[j]) < 0) {
|
||||
sortedPart.push(leftPart[i]);
|
||||
i += 1;
|
||||
}
|
||||
else {
|
||||
sortedPart.push(rightPart[j]);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
while(i < leftPart.length) {
|
||||
sortedPart.push(leftPart[i]);
|
||||
i += 1;
|
||||
}
|
||||
while(j < rightPart.length) {
|
||||
sortedPart.push(rightPart[j]);
|
||||
j += 1;
|
||||
}
|
||||
return sortedPart;
|
||||
};
|
||||
|
||||
const closestPair = function _closestPair(Px, Py) {
|
||||
if(Px.length < 2) return { distance: Infinity, pair: [ new Point(0, 0), new Point(0, 0) ] };
|
||||
if(Px.length < 3) {
|
||||
//find euclid distance
|
||||
var d = Math.sqrt( Math.pow(Math.abs(Px[1].x - Px[0].x), 2) + Math.pow(Math.abs(Px[1].y - Px[0].y), 2) );
|
||||
return {
|
||||
distance: d,
|
||||
pair: [ Px[0], Px[1] ]
|
||||
};
|
||||
}
|
||||
|
||||
var n = Px.length,
|
||||
leftN = Math.floor(n / 2),
|
||||
rightN = leftN;
|
||||
|
||||
var Xl = Px.slice(0, leftN),
|
||||
Xr = Px.slice(rightN),
|
||||
Xm = Xl[leftN - 1],
|
||||
Yl = [],
|
||||
Yr = [];
|
||||
//separate Py
|
||||
for(var i = 0; i < Py.length; i += 1) {
|
||||
if(Py[i].x <= Xm.x)
|
||||
Yl.push(Py[i]);
|
||||
else
|
||||
Yr.push(Py[i]);
|
||||
}
|
||||
|
||||
var dLeft = _closestPair(Xl, Yl),
|
||||
dRight = _closestPair(Xr, Yr);
|
||||
|
||||
var minDelta = dLeft.distance,
|
||||
closestPair = dLeft.pair;
|
||||
if(dLeft.distance > dRight.distance) {
|
||||
minDelta = dRight.distance;
|
||||
closestPair = dRight.pair;
|
||||
}
|
||||
|
||||
//filter points around Xm within delta (minDelta)
|
||||
var closeY = [];
|
||||
for(i = 0; i < Py.length; i += 1) {
|
||||
if(Math.abs(Py[i].x - Xm.x) < minDelta) closeY.push(Py[i]);
|
||||
}
|
||||
//find min within delta. 8 steps max
|
||||
for(i = 0; i < closeY.length; i += 1) {
|
||||
for(var j = i + 1; j < Math.min( (i + 8), closeY.length ); j += 1) {
|
||||
var d = Math.sqrt( Math.pow(Math.abs(closeY[j].x - closeY[i].x), 2) + Math.pow(Math.abs(closeY[j].y - closeY[i].y), 2) );
|
||||
if(d < minDelta) {
|
||||
minDelta = d;
|
||||
closestPair = [ closeY[i], closeY[j] ]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
distance: minDelta,
|
||||
pair: closestPair
|
||||
};
|
||||
};
|
||||
|
||||
function getClosestPair(points) {
|
||||
const sortX = function(a, b) { return (a.x < b.x) ? -1 : ((a.x > b.x) ? 1 : 0); }
|
||||
const sortY = function(a, b) { return (a.y < b.y) ? -1 : ((a.y > b.y) ? 1 : 0); }
|
||||
|
||||
const Px = mergeSort(points, sortX);
|
||||
const Py = mergeSort(points, sortY);
|
||||
|
||||
return closestPair(Px, Py);
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5958469238c0d8d2632f46db
|
||||
title: 组合
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: combinations
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -50,5 +51,50 @@ assert.deepEqual(combinations(testInput1[0], testInput1[1]), testOutput1);
|
||||
assert.deepEqual(combinations(testInput2[0], testInput2[1]), testOutput2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testInput1 = [3, 5];
|
||||
const testOutput1 = [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]];
|
||||
|
||||
const testInput2 = [4, 6];
|
||||
const testOutput2 = [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function combinations(m, n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function combinations(m, n) {
|
||||
const nArr = [...Array(n).keys()];
|
||||
|
||||
return (function generateCombinations (size, numArr) {
|
||||
const ret = [];
|
||||
|
||||
for (let i = 0; i < numArr.length; i++) {
|
||||
if (size === 1) {
|
||||
ret.push([numArr[i]]);
|
||||
}
|
||||
else {
|
||||
const sub = generateCombinations(size - 1, numArr.slice(i + 1, numArr.length));
|
||||
for (let subI = 0; subI < sub.length; subI++) {
|
||||
const next = sub[subI];
|
||||
next.unshift(numArr[i]);
|
||||
ret.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}(m, nArr));
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 596e414344c3b2872167f0fe
|
||||
title: 逗号狡猾
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: comma-quibbling
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -47,5 +48,32 @@ assert.equal(quibble(testCases[2]), results[2]);
|
||||
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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function quibble(words) {
|
||||
return "{" +
|
||||
words.slice(0, words.length - 1).join(",") +
|
||||
(words.length > 1 ? " and " : "") +
|
||||
(words[words.length - 1] || '') +
|
||||
"}";
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 596e457071c35c882915b3e4
|
||||
title: 比较字符串列表
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: compare-a-list-of-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>给定一个任意多个字符串的<a href='https://en.wikipedia.org/wiki/List_(abstract_data_type)' title='wp:List_(abstract_data_type)'>列表</a> ,为以下每个条件实现一个函数: </p>测试它们是否都是词法上相等的测试,如果每个字符串在词法上小于它之后的字符串(即列表是否按严格的升序排列)
|
||||
<p>给定一个任意多个字符串的<a href='https://en.wikipedia.org/wiki/List_(abstract_data_type)' title='wp:List_(abstract_data_type)'>列表</a> ,为以下每个条件实现一个函数: </p>测试它们是否都是词法上相等的测试,如果每个字符串在词法上小于它之后的字符串(即列表是否按严格的升序排列)
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -83,5 +84,44 @@ assert(!allEqual(testCases[4]));
|
||||
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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function azSorted(arr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function allEqual(a) {
|
||||
let out = true;
|
||||
let i = 0;
|
||||
while (++i < a.length) {
|
||||
out = out && (a[i - 1] === a[i]);
|
||||
} return out;
|
||||
}
|
||||
|
||||
function azSorted(a) {
|
||||
let out = true;
|
||||
let i = 0;
|
||||
while (++i < a.length) {
|
||||
out = out && (a[i - 1] < a[i]);
|
||||
} return out;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 596fd036dc1ab896c5db98b1
|
||||
title: 将秒转换为复合持续时间
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: convert-seconds-to-compound-duration
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -65,5 +66,54 @@ assert.equal(convertSeconds(testCases[1]), results[1]);
|
||||
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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function convertSeconds(sec) {
|
||||
const localNames = ['wk', 'd', 'hr', 'min', 'sec'];
|
||||
// compoundDuration :: [String] -> Int -> String
|
||||
const compoundDuration = (labels, intSeconds) =>
|
||||
weekParts(intSeconds)
|
||||
.map((v, i) => [v, labels[i]])
|
||||
.reduce((a, x) =>
|
||||
a.concat(x[0] ? [`${x[0]} ${x[1] || '?'}`] : []), []
|
||||
)
|
||||
.join(', ');
|
||||
|
||||
// weekParts :: Int -> [Int]
|
||||
const weekParts = intSeconds => [0, 7, 24, 60, 60]
|
||||
.reduceRight((a, x) => {
|
||||
const r = a.rem;
|
||||
const mod = x !== 0 ? r % x : r;
|
||||
|
||||
return {
|
||||
rem: (r - mod) / (x || 1),
|
||||
parts: [mod].concat(a.parts)
|
||||
};
|
||||
}, {
|
||||
rem: intSeconds,
|
||||
parts: []
|
||||
})
|
||||
.parts;
|
||||
|
||||
return compoundDuration(localNames, sec);
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 596fda99c69f779975a1b67d
|
||||
title: 计算子字符串的出现次数
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: count-occurrences-of-a-substring
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -47,5 +48,31 @@ assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
|
||||
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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countSubstring(str, subStr) {
|
||||
const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
|
||||
const matches = str.match(new RegExp(escapedSubStr, 'g'));
|
||||
return matches ? matches.length : 0;
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 59713bd26bdeb8a594fb9413
|
||||
title: 计算硬币
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: count-the-coins
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p> <a href='https://en.wikipedia.org/wiki/United_States' title='链接:https://en.wikipedia.org/wiki/United_States'>美国</a>货币有四种常见硬币: </p>季度(25美分)硬币(10美分)镍(5美分)和便士(1美分) <p>有六种方法可以换15美分: </p>一角钱和一角钱一角钱和5便士3镍2镍和5便士一镍和10便士15便士任务: <p>实现一个功能,以确定使用这些普通硬币改变一美元的方式有多少? (1美元= 100美分)。 </p>参考: <a href='http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52' title='链接:http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52'>麻省理工学院出版社的算法</a> 。
|
||||
<p> <a href='https://en.wikipedia.org/wiki/United_States' title='链接:https://en.wikipedia.org/wiki/United_States'>美国</a>货币有四种常见硬币: </p>季度(25美分)硬币(10美分)镍(5美分)和便士(1美分) <p>有六种方法可以换15美分: </p>一角钱和一角钱一角钱和5便士3镍2镍和5便士一镍和10便士15便士任务: <p>实现一个功能,以确定使用这些普通硬币改变一美元的方式有多少? (1美元= 100美分)。 </p>参考: <a href='http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52' title='链接:http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52'>麻省理工学院出版社的算法</a> 。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -23,5 +24,37 @@ assert(typeof countCoins === 'function');
|
||||
assert.equal(countCoins(), 242);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countCoins() {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countCoins() {
|
||||
let t = 100;
|
||||
const operands = [1, 5, 10, 25];
|
||||
const targetsLength = t + 1;
|
||||
const operandsLength = operands.length;
|
||||
t = [1];
|
||||
|
||||
for (let a = 0; a < operandsLength; a++) {
|
||||
for (let b = 1; b < targetsLength; b++) {
|
||||
// initialise undefined target
|
||||
t[b] = t[b] ? t[b] : 0;
|
||||
|
||||
// accumulate target + operand ways
|
||||
t[b] += (b < operands[a]) ? 0 : t[b - operands[a]];
|
||||
}
|
||||
}
|
||||
|
||||
return t[targetsLength - 1];
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59713da0a428c1a62d7db430
|
||||
title: 克莱默的统治
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: cramers-rule
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -29,5 +30,118 @@ assert.deepEqual(cramersRule(matrices[0], freeTerms[0]), answers[0]);
|
||||
assert.deepEqual(cramersRule(matrices[1], freeTerms[1]), answers[1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const matrices = [
|
||||
[
|
||||
[2, -1, 5, 1],
|
||||
[3, 2, 2, -6],
|
||||
[1, 3, 3, -1],
|
||||
[5, -2, -3, 3]
|
||||
],
|
||||
[
|
||||
[3, 1, 1],
|
||||
[2, 2, 5],
|
||||
[1, -3, -4]
|
||||
]
|
||||
];
|
||||
const freeTerms = [[-3, -32, -47, 49], [3, -1, 2]];
|
||||
|
||||
const answers = [[2, -12, -4, 1], [1, 1, -1]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function cramersRule(matrix, freeTerms) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
* Compute Cramer's Rule
|
||||
* @param {array} matrix x,y,z, etc. terms
|
||||
* @param {array} freeTerms
|
||||
* @return {array} solution for x,y,z, etc.
|
||||
*/
|
||||
function cramersRule(matrix, freeTerms) {
|
||||
const det = detr(matrix);
|
||||
const returnArray = [];
|
||||
let i;
|
||||
|
||||
for (i = 0; i < matrix[0].length; i++) {
|
||||
const tmpMatrix = insertInTerms(matrix, freeTerms, i);
|
||||
returnArray.push(detr(tmpMatrix) / det);
|
||||
}
|
||||
return returnArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts single dimensional array into
|
||||
* @param {array} matrix multidimensional array to have ins inserted into
|
||||
* @param {array} ins single dimensional array to be inserted vertically into matrix
|
||||
* @param {array} at zero based offset for ins to be inserted into matrix
|
||||
* @return {array} New multidimensional array with ins replacing the at column in matrix
|
||||
*/
|
||||
function insertInTerms(matrix, ins, at) {
|
||||
const tmpMatrix = clone(matrix);
|
||||
let i;
|
||||
for (i = 0; i < matrix.length; i++) {
|
||||
tmpMatrix[i][at] = ins[i];
|
||||
}
|
||||
return tmpMatrix;
|
||||
}
|
||||
/**
|
||||
* Compute the determinate of a matrix. No protection, assumes square matrix
|
||||
* function borrowed, and adapted from MIT Licensed numericjs library (www.numericjs.com)
|
||||
* @param {array} m Input Matrix (multidimensional array)
|
||||
* @return {number} result rounded to 2 decimal
|
||||
*/
|
||||
function detr(m) {
|
||||
let ret = 1;
|
||||
let j;
|
||||
let k;
|
||||
const A = clone(m);
|
||||
const n = m[0].length;
|
||||
let alpha;
|
||||
|
||||
for (j = 0; j < n - 1; j++) {
|
||||
k = j;
|
||||
for (let i = j + 1; i < n; i++) { if (Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } }
|
||||
if (k !== j) {
|
||||
const temp = A[k]; A[k] = A[j]; A[j] = temp;
|
||||
ret *= -1;
|
||||
}
|
||||
const Aj = A[j];
|
||||
for (let i = j + 1; i < n; i++) {
|
||||
const Ai = A[i];
|
||||
alpha = Ai[j] / Aj[j];
|
||||
for (k = j + 1; k < n - 1; k += 2) {
|
||||
const k1 = k + 1;
|
||||
Ai[k] -= Aj[k] * alpha;
|
||||
Ai[k1] -= Aj[k1] * alpha;
|
||||
}
|
||||
if (k !== n) { Ai[k] -= Aj[k] * alpha; }
|
||||
}
|
||||
if (Aj[j] === 0) { return 0; }
|
||||
ret *= Aj[j];
|
||||
}
|
||||
return Math.round(ret * A[j][j] * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone two dimensional Array using ECMAScript 5 map function and EcmaScript 3 slice
|
||||
* @param {array} m Input matrix (multidimensional array) to clone
|
||||
* @return {array} New matrix copy
|
||||
*/
|
||||
function clone(m) {
|
||||
return m.map(a => a.slice());
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e03
|
||||
title: Cumulative standard deviation
|
||||
challengeType: 5
|
||||
forumTopicId: 302240
|
||||
dashedName: cumulative-standard-deviation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e05
|
||||
title: CUSIP
|
||||
challengeType: 5
|
||||
forumTopicId: 302241
|
||||
dashedName: cusip
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e06
|
||||
title: Cut a rectangle
|
||||
challengeType: 5
|
||||
forumTopicId: 302242
|
||||
dashedName: cut-a-rectangle
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 59669d08d75b60482359409f
|
||||
title: 日期格式
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: date-format
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -43,5 +44,42 @@ assert(getDateFormats().length === 2);
|
||||
assert.deepEqual(getDateFormats(), dates, equalsMessage);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const getDateSolution = () => {
|
||||
const date = new Date();
|
||||
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
const fmt1 = `${date.getFullYear()}-${(1 + date.getMonth())}-${date.getDate()}`;
|
||||
const fmt2 = `${weekdays[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
|
||||
return [fmt1, fmt2];
|
||||
};
|
||||
|
||||
const dates = getDateSolution();
|
||||
const equalsMessage = `message: <code>getDataFormats()</code> should return <code>["${dates[0]}", "${dates[1]}"]</code>.`;
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getDateFormats() {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getDateFormats() {
|
||||
const date = new Date();
|
||||
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
const fmt1 = `${date.getFullYear()}-${(1 + date.getMonth())}-${date.getDate()}`;
|
||||
const fmt2 = `${weekdays[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
|
||||
return [fmt1, fmt2];
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5966c21cf732a95f1b67dd28
|
||||
title: 日期操纵
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: date-manipulation
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -69,5 +70,48 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function add12Hours(dateString) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function add12Hours(dateString) {
|
||||
const months = ['January', 'February', 'March', 'April', 'May', 'June',
|
||||
'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
// Get the parts of the string
|
||||
const parts = dateString.split(' ');
|
||||
const month = months.indexOf(parts[0]);
|
||||
const day = parseInt(parts[1], 10);
|
||||
const year = parseInt(parts[2], 10);
|
||||
const time = parts[3].split(':');
|
||||
let hours = parseInt(time[0], 10);
|
||||
if (time[1].slice(-2) === 'pm') {
|
||||
hours += 12;
|
||||
}
|
||||
const minutes = parseInt(time[1].slice(0, -2), 10);
|
||||
|
||||
// Create a date with given parts, and updated hours
|
||||
const date = new Date();
|
||||
date.setFullYear(year, month, day);
|
||||
date.setHours(hours + 12); // Add 12 hours
|
||||
date.setMinutes(minutes);
|
||||
|
||||
let hoursOutput = date.getHours();
|
||||
let abbreviation = 'am';
|
||||
if (hoursOutput > 12) {
|
||||
hoursOutput -= 12;
|
||||
abbreviation = 'pm';
|
||||
}
|
||||
|
||||
return `${months[date.getMonth()]} ${date.getDate()} ${date.getFullYear()} ${hoursOutput}:${date.getMinutes()}${abbreviation} EST`;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5966f99c45e8976909a85575
|
||||
title: 一周中的天
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: day-of-the-week
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -35,5 +36,35 @@ assert.deepEqual(findXmasSunday(1970, 2017), firstSolution);
|
||||
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) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findXmasSunday(start, end) {
|
||||
const xmasSunday = [];
|
||||
for (let year = start; year <= end; year++) {
|
||||
const xmas = new Date(year, 11, 25);
|
||||
if (xmas.getDay() === 0) {
|
||||
xmasSunday.push(year);
|
||||
}
|
||||
}
|
||||
return xmasSunday;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59694356a6e7011f7f1c5f4e
|
||||
title: FreeCell的交易卡
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: deal-cards-for-freecell
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -63,5 +64,98 @@ assert.deepEqual(dealFreeCell(1), game1);
|
||||
assert.deepEqual(dealFreeCell(617), game617);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const replaceThis = 3;
|
||||
const game1 = [
|
||||
['JD', '2D', '9H', 'JC', '5D', '7H', '7C', '5H'],
|
||||
['KD', 'KC', '9S', '5S', 'AD', 'QC', 'KH', '3H'],
|
||||
['2S', 'KS', '9D', 'QD', 'JS', 'AS', 'AH', '3C'],
|
||||
['4C', '5C', 'TS', 'QH', '4H', 'AC', '4D', '7S'],
|
||||
['3S', 'TD', '4S', 'TH', '8H', '2C', 'JH', '7D'],
|
||||
['6D', '8S', '8D', 'QS', '6C', '3D', '8C', 'TC'],
|
||||
['6S', '9C', '2H', '6H']
|
||||
];
|
||||
const game617 = [
|
||||
['7D', 'AD', '5C', '3S', '5S', '8C', '2D', 'AH'],
|
||||
['TD', '7S', 'QD', 'AC', '6D', '8H', 'AS', 'KH'],
|
||||
['TH', 'QC', '3H', '9D', '6S', '8D', '3D', 'TC'],
|
||||
['KD', '5H', '9S', '3C', '8S', '7H', '4D', 'JS'],
|
||||
['4C', 'QS', '9C', '9H', '7C', '6H', '2C', '2S'],
|
||||
['4S', 'TS', '2H', '5D', 'JC', '6C', 'JH', 'QH'],
|
||||
['JD', 'KS', 'KC', '4H']
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function dealFreeCell(seed) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// RNG
|
||||
function FreeCellRNG(seed) {
|
||||
return {
|
||||
lastNum: seed,
|
||||
next() {
|
||||
this.lastNum = ((214013 * this.lastNum) + 2531011) % (Math.pow(2, 31));
|
||||
return this.lastNum >> 16;
|
||||
}
|
||||
};
|
||||
}
|
||||
// Get cards
|
||||
function getDeck() {
|
||||
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
|
||||
const suits = ['C', 'D', 'H', 'S'];
|
||||
const cards = [];
|
||||
for (let i = 0; i < ranks.length; i += 1) {
|
||||
for (let j = 0; j < suits.length; j += 1) {
|
||||
cards.push(`${ranks[i]}${suits[j]}`);
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
function dealFreeCell(seed) {
|
||||
const rng = FreeCellRNG(seed);
|
||||
const deck = getDeck();
|
||||
|
||||
const deltCards = [[], [], [], [], [], [], []];
|
||||
let currentColumn = 0;
|
||||
let currentRow = 0;
|
||||
|
||||
let rand;
|
||||
let temp;
|
||||
let card;
|
||||
while (deck.length > 0) {
|
||||
// Choose a random card
|
||||
rand = rng.next() % deck.length;
|
||||
|
||||
// Swap this random card with the last card in the array
|
||||
temp = deck[deck.length - 1];
|
||||
deck[deck.length - 1] = deck[rand];
|
||||
deck[rand] = temp;
|
||||
|
||||
// Remove this card from the array
|
||||
card = deck.pop();
|
||||
|
||||
// Deal this card
|
||||
deltCards[currentRow].push(card);
|
||||
currentColumn += 1;
|
||||
if (currentColumn === 8) {
|
||||
currentColumn = 0;
|
||||
currentRow += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return deltCards;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 596a8888ab7c01048de257d5
|
||||
title: deepcopy的
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: deepcopy
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -49,5 +50,35 @@ assert.deepEqual(deepcopy(obj2), obj2);
|
||||
assert.deepEqual(deepcopy(obj3), obj3);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const obj1 = { test: 'test' };
|
||||
const obj2 = {
|
||||
t: 'test',
|
||||
a: ['an', 'array']
|
||||
};
|
||||
const obj3 = {
|
||||
t: 'try',
|
||||
o: obj2
|
||||
};
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function deepcopy(obj) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function deepcopy(obj) {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 597089c87eec450c68aa1643
|
||||
title: 定义原始数据类型
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: define-a-primitive-data-type
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -99,5 +100,30 @@ assert(!(new Num(3) > new Num(4)));
|
||||
assert.equal(new Num(5).toString(), '5');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function Num(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function Num(n) {
|
||||
if (isNaN(n)) {
|
||||
throw new TypeError('Not a Number');
|
||||
}
|
||||
if (n < 1 || n > 10) {
|
||||
throw new TypeError('Out of range');
|
||||
}
|
||||
|
||||
this._value = +n;
|
||||
}
|
||||
Num.prototype.valueOf = function() { return this._value; };
|
||||
Num.prototype.toString = function () { return this._value.toString(); };
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59f40b17e79dbf1ab720ed7a
|
||||
title: 部门编号
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: department-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -35,5 +36,67 @@ assert(combinations(nums, total).length === len);
|
||||
assert.deepEqual(combinations(nums, total), result);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const nums = [1, 2, 3, 4, 5, 6, 7];
|
||||
const total = 12;
|
||||
const len = 14;
|
||||
const result = [
|
||||
[2, 3, 7],
|
||||
[2, 4, 6],
|
||||
[2, 6, 4],
|
||||
[2, 7, 3],
|
||||
[4, 1, 7],
|
||||
[4, 2, 6],
|
||||
[4, 3, 5],
|
||||
[4, 5, 3],
|
||||
[4, 6, 2],
|
||||
[4, 7, 1],
|
||||
[6, 1, 5],
|
||||
[6, 2, 4],
|
||||
[6, 4, 2],
|
||||
[6, 5, 1]
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function combinations(possibleNumbers, total) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function combinations(possibleNumbers, total) {
|
||||
let firstNumber;
|
||||
let secondNumber;
|
||||
let thridNumber;
|
||||
const allCombinations = [];
|
||||
|
||||
for (let i = 0; i < possibleNumbers.length; i += 1) {
|
||||
firstNumber = possibleNumbers[i];
|
||||
|
||||
if (firstNumber % 2 === 0) {
|
||||
for (let j = 0; j < possibleNumbers.length; j += 1) {
|
||||
secondNumber = possibleNumbers[j];
|
||||
|
||||
if (j !== i && firstNumber + secondNumber <= total) {
|
||||
thridNumber = total - firstNumber - secondNumber;
|
||||
|
||||
if (thridNumber !== firstNumber && thridNumber !== secondNumber && possibleNumbers.includes(thridNumber)) {
|
||||
allCombinations.push([firstNumber, secondNumber, thridNumber]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return allCombinations;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59f4eafba0343628bb682785
|
||||
title: Discordian日期
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: discordian-date
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -82,5 +83,115 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function discordianDate(date) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
* All Hail Discordia! - this script prints Discordian date using system date.
|
||||
*
|
||||
* lang: JavaScript
|
||||
* author: jklu
|
||||
* contributors: JamesMcGuigan
|
||||
*
|
||||
* source: https://rosettacode.org/wiki/Discordian_date#JavaScript
|
||||
*/
|
||||
const seasons = [
|
||||
'Chaos', 'Discord', 'Confusion',
|
||||
'Bureaucracy', 'The Aftermath'
|
||||
];
|
||||
const weekday = [
|
||||
'Sweetmorn', 'Boomtime', 'Pungenday',
|
||||
'Prickle-Prickle', 'Setting Orange'
|
||||
];
|
||||
|
||||
const apostle = [
|
||||
'Mungday', 'Mojoday', 'Syaday',
|
||||
'Zaraday', 'Maladay'
|
||||
];
|
||||
|
||||
const holiday = [
|
||||
'Chaoflux', 'Discoflux', 'Confuflux',
|
||||
'Bureflux', 'Afflux'
|
||||
];
|
||||
|
||||
|
||||
Date.prototype.isLeapYear = function() {
|
||||
const year = this.getFullYear();
|
||||
if ((year & 3) !== 0) { return false; }
|
||||
return ((year % 100) !== 0 || (year % 400) === 0);
|
||||
};
|
||||
|
||||
// Get Day of Year
|
||||
Date.prototype.getDOY = function() {
|
||||
const dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
|
||||
const mn = this.getMonth();
|
||||
const dn = this.getDate();
|
||||
let dayOfYear = dayCount[mn] + dn;
|
||||
if (mn > 1 && this.isLeapYear()) { dayOfYear += 1; }
|
||||
return dayOfYear;
|
||||
};
|
||||
|
||||
Date.prototype.isToday = function() {
|
||||
const today = new Date();
|
||||
return this.getDate() === today.getDate()
|
||||
&& this.getMonth() === today.getMonth()
|
||||
&& this.getFullYear() === today.getFullYear()
|
||||
;
|
||||
};
|
||||
|
||||
function discordianDate(date) {
|
||||
if (!date) { date = new Date(); }
|
||||
|
||||
const y = date.getFullYear();
|
||||
const yold = y + 1166;
|
||||
let dayOfYear = date.getDOY();
|
||||
let celebrateHoliday = null;
|
||||
|
||||
if (date.isLeapYear()) {
|
||||
if (dayOfYear === 60) {
|
||||
celebrateHoliday = 'St. Tib\'s Day';
|
||||
}
|
||||
else if (dayOfYear > 60) {
|
||||
dayOfYear--;
|
||||
}
|
||||
}
|
||||
dayOfYear--;
|
||||
|
||||
const divDay = Math.floor(dayOfYear / 73);
|
||||
|
||||
const seasonDay = (dayOfYear % 73) + 1;
|
||||
if (seasonDay === 5) {
|
||||
celebrateHoliday = apostle[divDay];
|
||||
}
|
||||
if (seasonDay === 50) {
|
||||
celebrateHoliday = holiday[divDay];
|
||||
}
|
||||
|
||||
const season = seasons[divDay];
|
||||
const dayOfWeek = weekday[dayOfYear % 5];
|
||||
|
||||
const nth = (seasonDay % 10 === 1) ? 'st'
|
||||
: (seasonDay % 10 === 2) ? 'nd'
|
||||
: (seasonDay % 10 === 3) ? 'rd'
|
||||
: 'th';
|
||||
|
||||
return ''
|
||||
+ dayOfWeek
|
||||
+ ', the ' + seasonDay + nth
|
||||
+ ' day of ' + season
|
||||
+ ' in the YOLD ' + yold
|
||||
+ (celebrateHoliday ? '. Celebrate ' + celebrateHoliday + '!' : '')
|
||||
;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e1e
|
||||
title: Dot product
|
||||
challengeType: 5
|
||||
forumTopicId: 302251
|
||||
dashedName: dot-product
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 599c333915e0ea32d04d4bec
|
||||
title: 元素操作
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: element-wise-operations
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -168,5 +169,34 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function operation(op, arr1, arr2) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function operation(op, arr1, arr2) {
|
||||
const ops = {
|
||||
add: ((a, b) => a + b),
|
||||
sub: ((a, b) => a - b),
|
||||
mult: ((a, b) => a * b),
|
||||
div: ((a, b) => a / b),
|
||||
exp: ((a, b) => Math.pow(a, b))
|
||||
};
|
||||
const ifm = op.startsWith('m');
|
||||
const doOp = ops[op.substring(2)];
|
||||
for (let i = 0; i < arr1.length; i++) {
|
||||
for (let j = 0; j < arr1[0].length; j++) {
|
||||
arr1[i][j] = doOp(arr1[i][j], (ifm) ? (arr2[i][j]) : (arr2));
|
||||
}
|
||||
}
|
||||
return arr1;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 599d0ba974141b0f508b37d5
|
||||
title: Emirp奖金
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: emirp-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -74,5 +75,51 @@ assert.deepEqual(emirps([7700, 8000], true), [
|
||||
assert.deepEqual(emirps([7700, 8000], false), 11);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function emirps(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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; } }
|
||||
return true;
|
||||
};
|
||||
const is_emirp = function(n) {
|
||||
const r = parseInt(n.toString().split('').reverse().join(''));
|
||||
return r != n && is_prime(n) && is_prime(r);
|
||||
};
|
||||
|
||||
let i,
|
||||
arr = [];
|
||||
if (typeof num === 'number') {
|
||||
for (i = 0; arr.length < num; i++) if (is_emirp(i)) arr.push(i);
|
||||
// first x emirps
|
||||
if (showEmirps) return arr;
|
||||
// xth emirp
|
||||
return arr.pop();
|
||||
}
|
||||
|
||||
if (Array.isArray(num)) {
|
||||
for (i = num[0]; i <= num[1]; i++) if (is_emirp(i)) arr.push(i);
|
||||
// emirps between x .. y
|
||||
if (showEmirps) return arr;
|
||||
// number of emirps between x .. y
|
||||
return arr.length;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 599d15309e88c813a40baf58
|
||||
title: 熵
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: entropy
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -61,5 +62,37 @@ assert.equal(entropy('0123456789abcdef'), 4);
|
||||
assert.equal(entropy('1223334444'), 1.8464393446710154);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function entropy(s) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function entropy(s) {
|
||||
// Create a dictionary of character frequencies and iterate over it.
|
||||
function process(s, evaluator) {
|
||||
let h = Object.create(null),
|
||||
k;
|
||||
s.split('').forEach(c => {
|
||||
h[c] && h[c]++ || (h[c] = 1); });
|
||||
if (evaluator) for (k in h) evaluator(k, h[k]);
|
||||
return h;
|
||||
}
|
||||
// Measure the entropy of a string in bits per symbol.
|
||||
|
||||
let sum = 0,
|
||||
len = s.length;
|
||||
process(s, (k, f) => {
|
||||
const p = f / len;
|
||||
sum -= p * Math.log(p) / Math.log(2);
|
||||
});
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5987fd532b954e0f21b5d3f6
|
||||
title: 均衡指数
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: equilibrium-index
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -53,5 +54,43 @@ assert.deepEqual(equilibrium(equilibriumTests[4]), ans[4]);
|
||||
assert.deepEqual(equilibrium(equilibriumTests[5]), ans[5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const equilibriumTests =
|
||||
[[-7, 1, 5, 2, -4, 3, 0], // 3, 6
|
||||
[2, 4, 6], // empty
|
||||
[2, 9, 2], // 1
|
||||
[1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6
|
||||
[1], // 0
|
||||
[] // empty
|
||||
];
|
||||
const ans = [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function equilibrium(a) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function equilibrium(a) {
|
||||
let N = a.length,
|
||||
i,
|
||||
l = [],
|
||||
r = [],
|
||||
e = [];
|
||||
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i < N; i++)
|
||||
{ l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1]; }
|
||||
for (i = 0; i < N; i++)
|
||||
{ if (l[i] === r[i]) e.push(i); }
|
||||
return e;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 599d1566a02b571412643b84
|
||||
title: 埃塞俄比亚的乘法
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: ethiopian-multiplication
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -47,5 +48,36 @@ assert.equal(eth_mult(56, 98), 5488);
|
||||
assert.equal(eth_mult(63, 74), 4662);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function eth_mult(a, b) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function eth_mult(a, b) {
|
||||
let sum = 0; a = [a]; b = [b];
|
||||
|
||||
let half = a => a / 2,
|
||||
double = a => a * 2,
|
||||
is_even = a => a % 2 == 0;
|
||||
|
||||
while (a[0] !== 1) {
|
||||
a.unshift(Math.floor(half(a[0])));
|
||||
b.unshift(double(b[0]));
|
||||
}
|
||||
|
||||
for (let i = a.length - 1; i > 0; i -= 1) {
|
||||
if (!is_even(a[i])) {
|
||||
sum += b[i];
|
||||
}
|
||||
}
|
||||
return sum + b[0];
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59880443fb36441083c6c20e
|
||||
title: 欧拉方法
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: euler-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -41,5 +42,28 @@ assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907);
|
||||
assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function eulersMethod(x1, y1, x2, h) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function eulersMethod(x1, y1, x2, h) {
|
||||
let x = x1;
|
||||
let y = y1;
|
||||
|
||||
while ((x < x2 && x1 < x2) || (x > x2 && x1 > x2)) {
|
||||
y += h * (-0.07 * (y - 20));
|
||||
x += h;
|
||||
}
|
||||
|
||||
return y;
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 598de241872ef8353c58a7a2
|
||||
title: 评估二项式系数
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: evaluate-binomial-coefficients
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>写一个函数来计算给定n和k值的二项式系数。 </p><p>推荐这个公式: </p> $ \\ binom {n} {k} = \\ frac {n!} {(nk)!k!} = \\ frac {n(n-1)(n-2)\\ ldots(n-k + 1)} { k(k-1)(k-2)\\ ldots 1} $
|
||||
<p>写一个函数来计算给定n和k值的二项式系数。 </p><p>推荐这个公式: </p> $ \\ binom {n} {k} = \\ frac {n!} {(nk)!k!} = \\ frac {n(n-1)(n-2)\\ ldots(n-k + 1)} { k(k-1)(k-2)\\ ldots 1} $
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -47,5 +48,23 @@ assert.equal(binom(6, 1), 6);
|
||||
assert.equal(binom(12, 8), 495);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function binom(n, k) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function binom(n, k) {
|
||||
let coeff = 1;
|
||||
for (let i = n - k + 1; i <= n; i++) coeff *= i;
|
||||
for (let i = 1; i <= k; i++) coeff /= i;
|
||||
return coeff;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59e09e6d412c5939baa02d16
|
||||
title: 执行马尔可夫算法
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: execute-a-markov-algorithm
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -207,5 +208,61 @@ assert.deepEqual(markov(rules[3], tests[3]), outputs[3]);
|
||||
assert.deepEqual(markov(rules[4], tests[4]), outputs[4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function markov(rules,test) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function markov(rules,test) {
|
||||
let pattern = new RegExp("^([^#]*?)\\s+->\\s+(\\.?)(.*)");
|
||||
let origTest = test;
|
||||
|
||||
let captures = [];
|
||||
|
||||
rules.forEach(function(rule){
|
||||
let m = pattern.exec(rule);
|
||||
for (let j = 0; j < m.length; j++)
|
||||
m[j] = m[j + 1];
|
||||
captures.push(m);
|
||||
});
|
||||
|
||||
test = origTest;
|
||||
let copy = test;
|
||||
for (let j = 0; j < captures.length; j++) {
|
||||
let c = captures[j];
|
||||
test = test.replace(c[0], c[2]);
|
||||
if (c[1]==".")
|
||||
break;
|
||||
if (test!=copy) {
|
||||
j = -1;
|
||||
copy = test;
|
||||
}
|
||||
}
|
||||
return test;
|
||||
}
|
||||
|
||||
// tail:
|
||||
let rules=[["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
|
||||
["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
|
||||
["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
|
||||
["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],
|
||||
["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"]];
|
||||
let tests=["I bought a B of As from T S.",
|
||||
"I bought a B of As from T S.",
|
||||
"I bought a B of As W my Bgage from T S.",
|
||||
"_1111*11111_",
|
||||
"000000A000000"];
|
||||
let outputs=["I bought a bag of apples from my brother.",
|
||||
"I bought a bag of apples from T shop.",
|
||||
"I bought a bag of apples with my money from T shop.",
|
||||
"11111111111111111111",
|
||||
"00011H1111000"];
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59e0a8df964e4540d5abe599
|
||||
title: 执行大脑****
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: execute-brain
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -41,5 +42,142 @@ assert.equal(brain(hello), 'Hello World!\n');
|
||||
assert.equal(brain(fib), '1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
let fib=`+
|
||||
|
||||
++
|
||||
|
||||
+++
|
||||
|
||||
++++
|
||||
|
||||
+>+>>
|
||||
|
||||
>>++++
|
||||
|
||||
+++++++
|
||||
|
||||
++++++++
|
||||
|
||||
+++++++++
|
||||
|
||||
++++++++++
|
||||
|
||||
++++++>++++
|
||||
|
||||
++++++++++++
|
||||
|
||||
+++++++++++++
|
||||
|
||||
+++<<<<<<[>[>>
|
||||
|
||||
>>>>+>+<<<<<<<-
|
||||
|
||||
]>>>>>>>[<<<<<<<
|
||||
|
||||
+>>>>>>>-]<[>++++
|
||||
|
||||
++++++[-<-[>>+>+<<
|
||||
|
||||
<-]>>>[<<<+>>>-]+<[
|
||||
|
||||
>[-]<[-]]>[<<[>>>+<<
|
||||
|
||||
<-]>>[-]]<<]>>>[>>+>+
|
||||
|
||||
<<<-]>>>[<<<+>>>-]+<[>
|
||||
|
||||
[-]<[-]]>[<<+>>[-]]<<<<
|
||||
|
||||
<<<]>>>>>[++++++++++++++
|
||||
|
||||
+++++++++++++++++++++++++
|
||||
|
||||
+++++++++.[-]]++++++++++<[
|
||||
|
||||
->-<]>+++++++++++++++++++++
|
||||
|
||||
+++++++++++++++++++++++++++.
|
||||
|
||||
[-]<<<<<<<<<<<<[>>>+>+<<<<-]>
|
||||
|
||||
>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]
|
||||
|
||||
<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+
|
||||
|
||||
>-]>[<+>-]<<<-]`;
|
||||
let hello='++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'
|
||||
let bye='++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.<+++++++.--------.<<<<<+.<+++.---.';
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function brain(prog) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function brain(prog){
|
||||
var output="";
|
||||
var code; // formatted code
|
||||
var ip = 0; // current instruction within code
|
||||
var nest = 0; // current bracket nesting (for Out button)
|
||||
var ahead = []; // locations of matching brackets
|
||||
|
||||
var data = [0]; // data array (mod by +, -)
|
||||
var dp = 0; // index into data (mod by <, >)
|
||||
|
||||
var inp = 0; // current input character (fetch with ,)
|
||||
var quit = 0;
|
||||
var commands = {
|
||||
'>':function() { if (++dp >= data.length) data[dp]=0 },
|
||||
'<':function() { if (--dp < 0) quit++ },
|
||||
'+':function() { ++data[dp] },
|
||||
'-':function() { --data[dp] },
|
||||
'[':function() { if (!data[dp]) ip = ahead[ip]; else ++nest },
|
||||
']':function() { if ( data[dp]) ip = ahead[ip]; else --nest },
|
||||
',':function() {
|
||||
var c = document.getElementById("input").value.charCodeAt(inp++);
|
||||
data[dp] = isNaN(c) ? 0 : c; // EOF: other options are -1 or no change
|
||||
},
|
||||
'.':function() {
|
||||
output+=String.fromCharCode(data[dp]);
|
||||
/*var s = document.getElementById("output").innerHTML)
|
||||
+ String.fromCharCode(data[dp]);
|
||||
s = s.replace(/\n/g,"<br>").replace(/ /g,"&nbsp;");
|
||||
document.getElementById("output").innerHTML = s;*/
|
||||
},
|
||||
};
|
||||
|
||||
let ar=prog.split('');
|
||||
var st = [], back, error = -1;
|
||||
for (ip=0; ip<ar.length; ip++) {
|
||||
switch(ar[ip]) {
|
||||
case '[':
|
||||
st.push(ip);
|
||||
break;
|
||||
case ']':
|
||||
if (st.length == 0) error = ip;
|
||||
back = st.pop();
|
||||
ahead[ip] = back;
|
||||
ahead[back] = ip;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for(ip=0;ip<ar.length;ip++){
|
||||
if(commands.hasOwnProperty(ar[ip]))
|
||||
commands[ar[ip]]();
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 598ee8b91b410510ae82efef
|
||||
title: 可扩展的素发生器
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: extensible-prime-generator
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -73,5 +74,55 @@ assert.equal(primeGenerator([7700, 8000], false), 30);
|
||||
assert.equal(primeGenerator(10000, false), 104729);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function primeGenerator(num, showPrimes) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function primeGenerator(num, showPrimes) {
|
||||
let i,
|
||||
arr = [];
|
||||
|
||||
function isPrime(num) {
|
||||
// try primes <= 16
|
||||
if (num <= 16) { return (
|
||||
num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13
|
||||
); }
|
||||
// cull multiples of 2, 3, 5 or 7
|
||||
if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num % 7 == 0)
|
||||
{ return false; }
|
||||
// cull square numbers ending in 1, 3, 7 or 9
|
||||
for (let i = 10; i * i <= num; i += 10) {
|
||||
if (num % (i + 1) == 0) return false;
|
||||
if (num % (i + 3) == 0) return false;
|
||||
if (num % (i + 7) == 0) return false;
|
||||
if (num % (i + 9) == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof num === 'number') {
|
||||
for (i = 0; arr.length < num; i++) if (isPrime(i)) arr.push(i);
|
||||
// first x primes
|
||||
if (showPrimes) return arr;
|
||||
// xth prime
|
||||
return arr.pop();
|
||||
}
|
||||
|
||||
if (Array.isArray(num)) {
|
||||
for (i = num[0]; i <= num[1]; i++) if (isPrime(i)) arr.push(i);
|
||||
// primes between x .. y
|
||||
if (showPrimes) return arr;
|
||||
// number of primes between x .. y
|
||||
return arr.length;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 597b2b2a2702b44414742771
|
||||
title: 阶乘
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: factorial
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -41,5 +42,25 @@ assert.equal(factorial(5), 120);
|
||||
assert.equal(factorial(10), 3628800);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function factorial(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factorial(n) {
|
||||
let sum = 1;
|
||||
while (n > 1) {
|
||||
sum *= n;
|
||||
n--;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 598eea87e5cf4b116c3ff81a
|
||||
title: 梅森数的因素
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: factors-of-a-mersenne-number
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>梅森数是2 <sup>P</sup> -1形式的数字。 </p><p>如果P是素数,那么梅森数可能是梅森素数</p><p> (如果P不是素数,则梅森数也不是素数)。 </p><p>在搜索梅森素数时,通过在开始可能冗长的<a href='http://rosettacode.org/wiki/Lucas-Lehmer test' title='Lucas-Lehmer测试'>Lucas-Lehmer检验</a>之前找到一个小因子来消除指数是有利的。 </p><p>有非常有效的算法来确定数字是否除以2 <sup>P</sup> -1(或等效地,如果2 <sup>P</sup> mod(数字)= 1)。 </p><p>有些语言已经有了这个exponent-and-mod操作的内置实现(称为modPow或类似的)。 </p><p>以下是如何自己实现这个modPow: </p><p>例如,让我们计算2 <sup>23</sup> mod 47。 </p><p>将指数23转换为二进制,得到10111.从<tt>square</tt> = 1开始,重复平方。 </p><p>卸下指数的最高位,并且如果它是1 <tt>平方</tt>乘以由所述幂(2)的基础上,然后计算<tt>平方</tt>模47。 </p><p>在下一步中使用最后一步的模数结果作为<tt>square</tt>的初始值: </p><p>删除可选</p><p>方形顶部位乘以2 mod 47 </p><p> ------------ ------- ------------- ------ </p><p> 1 * 1 = 1 1 0111 1 * 2 = 2 2 </p><p> 2 * 2 = 4 0 111否4 </p><p> 4 * 4 = 16 1 11 16 * 2 = 32 32 </p><p> 32 * 32 = 1024 1 1 1024 * 2 = 2048 27 </p><p> 27 * 27 = 729 1 729 * 2 = 1458 1 </p><p>由于2 <sup>23</sup> mod 47 = 1,47是2 <sup>P</sup> -1的因子。 </p><p> (要看到这一点,从两边减去1:2 <sup>23</sup> -1 = 0 mod 47.) </p><p>由于我们已经证明47是一个因子,因此2 <sup>23</sup> -1不是素数。 </p><p> Mersenne数字的其他属性使我们能够进一步完善这一过程。 </p><p>任何因子q为2 <sup>P</sup> -1必须是2kP + 1的形式,k是正整数或零。此外,q必须是1或7 mod 8。 </p><p>最后任何潜在因素q必须是<a href='http://rosettacode.org/wiki/Primality by Trial Division' title='审判分庭的原始性'>素数</a> 。 </p><p>与其他试验划分算法一样,算法在2kP + 1> sqrt(N)时停止。 </p><p>这些素性测试仅适用于P为素数的Mersenne数。例如,M <sub>4</sub> = 15不使用这些技术产生因子,而是产生3和5的因子,两者都不符合2kP + 1。 </p>任务: <p>使用上述方法找到因子2 <sup>929</sup> -1(又名M929) </p>相关任务: <a href='http://rosettacode.org/wiki/count in factors' title='算上因素'>计数因素</a> <a href='http://rosettacode.org/wiki/prime decomposition' title='主要分解'>素数分解</a> <a href='http://rosettacode.org/wiki/factors of an integer' title='整数的因子'>的整数的因素</a> <a href='http://rosettacode.org/wiki/Sieve of Eratosthenes' title='Eratosthenes的筛子'>埃拉托塞尼的筛</a> <a href='http://rosettacode.org/wiki/primality by trial division' title='审判分裂的素性'>通过试验除法素性</a> <a href='http://rosettacode.org/wiki/trial factoring of a Mersenne number' title='试用Mensenne数的因式'>梅森数的试验理</a> <a href='http://rosettacode.org/wiki/partition an integer X into N primes' title='将整数X划分为N个素数'>分区的整数X为N个素数</a> <a href='http://rosettacode.org/wiki/sequence of primes by Trial Division' title='审判分庭的素数序列'>由审判庭素数的序列</a> <a href='https://www.youtube.com/watch?v=SNwvJ7psoow' title='链接:https://www.youtube.com/watch?v = SNwvJ7psoow'>在1948年计算机:2¹²⁷-1</a>
|
||||
<p>梅森数是2 <sup>P</sup> -1形式的数字。 </p><p>如果P是素数,那么梅森数可能是梅森素数</p><p> (如果P不是素数,则梅森数也不是素数)。 </p><p>在搜索梅森素数时,通过在开始可能冗长的<a href='http://rosettacode.org/wiki/Lucas-Lehmer test' title='Lucas-Lehmer测试'>Lucas-Lehmer检验</a>之前找到一个小因子来消除指数是有利的。 </p><p>有非常有效的算法来确定数字是否除以2 <sup>P</sup> -1(或等效地,如果2 <sup>P</sup> mod(数字)= 1)。 </p><p>有些语言已经有了这个exponent-and-mod操作的内置实现(称为modPow或类似的)。 </p><p>以下是如何自己实现这个modPow: </p><p>例如,让我们计算2 <sup>23</sup> mod 47。 </p><p>将指数23转换为二进制,得到10111.从<tt>square</tt> = 1开始,重复平方。 </p><p>卸下指数的最高位,并且如果它是1 <tt>平方</tt>乘以由所述幂(2)的基础上,然后计算<tt>平方</tt>模47。 </p><p>在下一步中使用最后一步的模数结果作为<tt>square</tt>的初始值: </p><p>删除可选</p><p>方形顶部位乘以2 mod 47 </p><p> ------------ ------- ------------- ------ </p><p> 1 * 1 = 1 1 0111 1 * 2 = 2 2 </p><p> 2 * 2 = 4 0 111否4 </p><p> 4 * 4 = 16 1 11 16 * 2 = 32 32 </p><p> 32 * 32 = 1024 1 1 1024 * 2 = 2048 27 </p><p> 27 * 27 = 729 1 729 * 2 = 1458 1 </p><p>由于2 <sup>23</sup> mod 47 = 1,47是2 <sup>P</sup> -1的因子。 </p><p> (要看到这一点,从两边减去1:2 <sup>23</sup> -1 = 0 mod 47.) </p><p>由于我们已经证明47是一个因子,因此2 <sup>23</sup> -1不是素数。 </p><p> Mersenne数字的其他属性使我们能够进一步完善这一过程。 </p><p>任何因子q为2 <sup>P</sup> -1必须是2kP + 1的形式,k是正整数或零。此外,q必须是1或7 mod 8。 </p><p>最后任何潜在因素q必须是<a href='http://rosettacode.org/wiki/Primality by Trial Division' title='审判分庭的原始性'>素数</a> 。 </p><p>与其他试验划分算法一样,算法在2kP + 1> sqrt(N)时停止。 </p><p>这些素性测试仅适用于P为素数的Mersenne数。例如,M <sub>4</sub> = 15不使用这些技术产生因子,而是产生3和5的因子,两者都不符合2kP + 1。 </p>任务: <p>使用上述方法找到因子2 <sup>929</sup> -1(又名M929) </p>相关任务: <a href='http://rosettacode.org/wiki/count in factors' title='算上因素'>计数因素</a> <a href='http://rosettacode.org/wiki/prime decomposition' title='主要分解'>素数分解</a> <a href='http://rosettacode.org/wiki/factors of an integer' title='整数的因子'>的整数的因素</a> <a href='http://rosettacode.org/wiki/Sieve of Eratosthenes' title='Eratosthenes的筛子'>埃拉托塞尼的筛</a> <a href='http://rosettacode.org/wiki/primality by trial division' title='审判分裂的素性'>通过试验除法素性</a> <a href='http://rosettacode.org/wiki/trial factoring of a Mersenne number' title='试用Mensenne数的因式'>梅森数的试验理</a> <a href='http://rosettacode.org/wiki/partition an integer X into N primes' title='将整数X划分为N个素数'>分区的整数X为N个素数</a> <a href='http://rosettacode.org/wiki/sequence of primes by Trial Division' title='审判分庭的素数序列'>由审判庭素数的序列</a> <a href='https://www.youtube.com/watch?v=SNwvJ7psoow' title='链接:https://www.youtube.com/watch?v = SNwvJ7psoow'>在1948年计算机:2¹²⁷-1</a>
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -44,5 +45,58 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function check_mersenne(p) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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 trial_factor(base, exp, mod){
|
||||
let square, bits;
|
||||
square = 1;
|
||||
bits = exp.toString(2).split('');
|
||||
for (let i=0,ln=bits.length; i<ln; i++){
|
||||
square = Math.pow(square, 2) * (bits[i] == 1 ? base : 1) % mod;
|
||||
}
|
||||
return (square == 1);
|
||||
}
|
||||
|
||||
function mersenne_factor(p){
|
||||
let limit, k, q;
|
||||
limit = Math.sqrt(Math.pow(2,p) - 1);
|
||||
k = 1;
|
||||
while ((2*k*p - 1) < limit){
|
||||
q = 2*k*p + 1;
|
||||
if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){
|
||||
return q; // q is a factor of 2**p-1
|
||||
}
|
||||
k++;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
let f, result;
|
||||
result="M"+p+" = 2^"+p+"-1 is ";
|
||||
f = mersenne_factor(p);
|
||||
result+=f == null ? "prime" : "composite with factor "+f;
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 597f1e7fbc206f0e9ba95dc4
|
||||
title: 整数因子
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: factors-of-an-integer
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>编写一个返回正整数因子的函数。 </p><p>这些因子是正整数,通过该正整数可以将被分解的数量除以产生正整数结果。 </p> ///
|
||||
<p>编写一个返回正整数因子的函数。 </p><p>这些因子是正整数,通过该正整数可以将被分解的数量除以产生正整数结果。 </p> ///
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -35,5 +36,37 @@ assert.deepEqual(factors(53), ans[1]);
|
||||
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) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factors(num)
|
||||
{
|
||||
let n_factors = [], i, sqr=Math.floor(Math.sqrt(num));
|
||||
|
||||
for (i = 1; i <=sqr ; i += 1)
|
||||
if (num % i === 0)
|
||||
{
|
||||
n_factors.push(i);
|
||||
if (num / i !== i)
|
||||
n_factors.push(num / i);
|
||||
}
|
||||
n_factors.sort(function(a, b){return a - b;});
|
||||
return n_factors;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 59c3ec9f15068017c96eb8a3
|
||||
title: Farey序列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: farey-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -52,5 +53,34 @@ assert.deepEqual(farey(5), [
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function farey(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 598eef80ba501f1268170e1e
|
||||
title: 斐波那契n步数序列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: fibonacci-n-step-number-sequences
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -59,5 +60,45 @@ assert.deepEqual(fib_luc(4, 15, 'l'), ans[5]);
|
||||
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],
|
||||
[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136],
|
||||
[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536],
|
||||
[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76],
|
||||
[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ],
|
||||
[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ],
|
||||
[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fib_luc(n, len, w) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 597f24c1dda4e70f53c79c81
|
||||
title: 斐波那契序列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: fibonacci-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>编写一个函数来生成第<big>n <sup>个</sup></big> Fibonacci数。 </p> /// <p>第<big>n <sup>个</sup></big> Fibonacci数由下式给出:/// </p><p> F <sub>n</sub> = F <sub>n-1</sub> + F <sub>n-2</sub> </p> /// <p>该系列的前两个术语是0,1。 </p> /// <p>因此,该系列是:0,1,1,2,3,5,8,13 ...... </p> ///
|
||||
<p>编写一个函数来生成第<big>n <sup>个</sup></big> Fibonacci数。 </p> /// <p>第<big>n <sup>个</sup></big> Fibonacci数由下式给出:/// </p><p> F <sub>n</sub> = F <sub>n-1</sub> + F <sub>n-2</sub> </p> /// <p>该系列的前两个术语是0,1。 </p> /// <p>因此,该系列是:0,1,1,2,3,5,8,13 ...... </p> ///
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -41,5 +42,26 @@ assert.equal(fibonacci(5), 3);
|
||||
assert.equal(fibonacci(10), 34);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fibonacci(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fibonacci(n) {
|
||||
let a = 0, b = 1, t;
|
||||
while (--n >= 0) {
|
||||
t = a;
|
||||
a = b;
|
||||
b += t;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5992e222d397f00d21122931
|
||||
title: 斐波那契字
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: fibonacci-word
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -29,5 +30,82 @@ assert(Array.isArray(fibWord(5)));
|
||||
assert.deepEqual(fibWord(5), ans);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let ans=[ { N: 1, Length: 1, Entropy: 0, Word: '1' },
|
||||
|
||||
{ N: 2, Length: 1, Entropy: 0, Word: '0' },
|
||||
|
||||
{ N: 3, Length: 2, Entropy: 1, Word: '01' },
|
||||
|
||||
{ N: 4, Length: 3, Entropy: 0.9182958340544896, Word: '010' },
|
||||
|
||||
{ N: 5, Length: 5, Entropy: 0.9709505944546688, Word: '01001' }];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fibWord(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fibWord(n) {
|
||||
function entropy(s) {
|
||||
//create an object containing each individual char
|
||||
//and the amount of iterations per char
|
||||
function prob(s) {
|
||||
var h = Object.create(null);
|
||||
s.split('').forEach(function(c) {
|
||||
h[c] && h[c]++ || (h[c] = 1);
|
||||
});
|
||||
return h;
|
||||
}
|
||||
|
||||
s = s.toString(); //just in case
|
||||
var e = 0, l = s.length, h = prob(s);
|
||||
|
||||
for (var i in h ) {
|
||||
var p = h[i]/l;
|
||||
e -= p * Math.log(p) / Math.log(2);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = [];
|
||||
|
||||
for (var i = 0; i < n; i++) {
|
||||
if (i === 0 || i === 1) {
|
||||
w = wNth[i];
|
||||
} else {
|
||||
w = wNth[i - 1] + wNth[i - 2];
|
||||
wNth.push(w);
|
||||
}
|
||||
var l = w.length;
|
||||
var e = entropy(w);
|
||||
|
||||
if (l <= 21) {
|
||||
o.push({
|
||||
N: i + 1,
|
||||
Length: l,
|
||||
Entropy: e,
|
||||
Word: w
|
||||
});
|
||||
} else {
|
||||
o.push({
|
||||
N: i + 1,
|
||||
Length: l,
|
||||
Entropy: e,
|
||||
Word: "..."
|
||||
});
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5e9ddb06ec35240f39657419
|
||||
title: FizzBuzz
|
||||
challengeType: 5
|
||||
forumTopicId: 385370
|
||||
dashedName: fizzbuzz
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a7dad05be01840e1778a0d1
|
||||
title: Fractran
|
||||
challengeType: 3
|
||||
videoUrl: ''
|
||||
dashedName: fractran
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -58,5 +59,54 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fractran(progStr) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fractran(progStr){
|
||||
var num = new Array();
|
||||
var den = new Array();
|
||||
var val ;
|
||||
var out="";
|
||||
function compile(prog){
|
||||
var regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
|
||||
while(regex.test(prog)){
|
||||
num.push(regex.exec(prog)[1]);
|
||||
den.push(regex.exec(prog)[2]);
|
||||
prog = regex.exec(prog)[3];
|
||||
}
|
||||
}
|
||||
|
||||
function step(val){
|
||||
var i=0;
|
||||
while(i<den.length && val%den[i] != 0) i++;
|
||||
return num[i]*val/den[i];
|
||||
}
|
||||
|
||||
var seq=[]
|
||||
|
||||
function exec(val){
|
||||
var i = 0;
|
||||
while(val && i<limit){
|
||||
seq.push(val)
|
||||
val = step(val);
|
||||
i ++;
|
||||
}
|
||||
}
|
||||
|
||||
// Main
|
||||
compile(progStr);
|
||||
var limit = 10;
|
||||
exec(2);
|
||||
return seq;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e76
|
||||
title: 伽玛功能
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: gamma-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -55,5 +56,47 @@ assert.equal(round(gamma(0.4)), round(2.218159543757687));
|
||||
assert.equal(round(gamma(0.5)), round(1.7724538509055159));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
function round(x) {
|
||||
return Number(x).toPrecision(13);
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gamma(x) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gamma(x) {
|
||||
var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
|
||||
771.32342877765313, -176.61502916214059, 12.507343278686905,
|
||||
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7
|
||||
];
|
||||
|
||||
var g = 7;
|
||||
if (x < 0.5) {
|
||||
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
|
||||
}
|
||||
|
||||
x -= 1;
|
||||
var a = p[0];
|
||||
var t = x + g + 0.5;
|
||||
for (var i = 1; i < p.length; i++) {
|
||||
a += p[i] / (x + i);
|
||||
}
|
||||
|
||||
var result=Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e77
|
||||
title: 高斯消除
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: gaussian-elimination
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -109,5 +110,117 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gaussianElimination(A,b) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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
|
||||
|
||||
for (var i=0; i<n; i++) {
|
||||
var max = 0
|
||||
for (var j=0; j<n; j++) {
|
||||
var temp = Math.abs(A[i][j])
|
||||
if (temp > max) max = temp
|
||||
}
|
||||
if (max == 0) return // Singular Matrix!
|
||||
vv[i] = 1 / max // Scaling
|
||||
}
|
||||
|
||||
var Acpy = new Array(n)
|
||||
for (var i=0; i<n; i++) {
|
||||
var Ai = A[i]
|
||||
let Acpyi = new Array(Ai.length)
|
||||
for (j=0; j<Ai.length; j+=1) Acpyi[j] = Ai[j]
|
||||
Acpy[i] = Acpyi
|
||||
}
|
||||
A = Acpy
|
||||
|
||||
var tiny = 1e-20 // in case pivot element is zero
|
||||
for (var i=0; ; i++) {
|
||||
for (var j=0; j<i; j++) {
|
||||
var sum = A[j][i]
|
||||
for (var k=0; k<j; k++) sum -= A[j][k] * A[k][i];
|
||||
A[j][i] = sum
|
||||
}
|
||||
var jmax = 0
|
||||
var max = 0;
|
||||
for (var j=i; j<n; j++) {
|
||||
var sum = A[j][i]
|
||||
for (var k=0; k<i; k++) sum -= A[j][k] * A[k][i];
|
||||
A[j][i] = sum
|
||||
var temp = vv[j] * Math.abs(sum)
|
||||
if (temp >= max) {
|
||||
max = temp
|
||||
jmax = j
|
||||
}
|
||||
}
|
||||
if (i <= jmax) {
|
||||
for (var j=0; j<n; j++) {
|
||||
var temp = A[jmax][j]
|
||||
A[jmax][j] = A[i][j]
|
||||
A[i][j] = temp
|
||||
}
|
||||
d = !d;
|
||||
vv[jmax] = vv[i]
|
||||
}
|
||||
idx[i] = jmax;
|
||||
if (i == n-1) break;
|
||||
var temp = A[i][i]
|
||||
if (temp == 0) A[i][i] = temp = tiny
|
||||
temp = 1 / temp
|
||||
for (var j=i+1; j<n; j++) A[j][i] *= temp
|
||||
}
|
||||
return {A:A, idx:idx, d:d}
|
||||
}
|
||||
|
||||
// Lower Upper Back Substitution
|
||||
function lubksb(lu, b) {
|
||||
// solves the set of n linear equations A*x = b.
|
||||
// lu is the object containing A, idx and d as determined by the routine ludcmp.
|
||||
var A = lu.A
|
||||
var idx = lu.idx
|
||||
var n = idx.length
|
||||
|
||||
var bcpy = new Array(n)
|
||||
for (var i=0; i<b.length; i+=1) bcpy[i] = b[i]
|
||||
b = bcpy
|
||||
|
||||
for (var ii=-1, i=0; i<n; i++) {
|
||||
var ix = idx[i]
|
||||
var sum = b[ix]
|
||||
b[ix] = b[i]
|
||||
if (ii > -1)
|
||||
for (var j=ii; j<i; j++) sum -= A[i][j] * b[j]
|
||||
else if (sum)
|
||||
ii = i
|
||||
b[i] = sum
|
||||
}
|
||||
for (var i=n-1; i>=0; i--) {
|
||||
var sum = b[i]
|
||||
for (var j=i+1; j<n; j++) sum -= A[i][j] * b[j]
|
||||
b[i] = sum / A[i][i]
|
||||
}
|
||||
return b // solution vector x
|
||||
}
|
||||
|
||||
var lu = ludcmp(A)
|
||||
if (lu === undefined) return // Singular Matrix!
|
||||
return lubksb(lu, b)
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e78
|
||||
title: 一般的FizzBuzz
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: general-fizzbuzz
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -137,5 +138,30 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function genFizzBuzz(rules, num) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function genFizzBuzz(rules, num) {
|
||||
let res='';
|
||||
rules.forEach(function (e) {
|
||||
if(num % e[0] == 0)
|
||||
res+=e[1];
|
||||
})
|
||||
|
||||
if(res==''){
|
||||
res=num.toString();
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e7a
|
||||
title: 生成小写ASCII字母表
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: generate-lower-case-ascii-alphabet
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -53,5 +54,46 @@ assert.deepEqual(lascii('k', 'n'), results[3]);
|
||||
assert.deepEqual(lascii('t', 'z'), results[4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let results=[
|
||||
[ 'a', 'b', 'c', 'd' ],
|
||||
[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ],
|
||||
[ 'm', 'n', 'o', 'p', 'q' ],
|
||||
[ 'k', 'l', 'm', 'n' ],
|
||||
[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]
|
||||
]
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function lascii(cFrom, cTo) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function lascii(cFrom, cTo) {
|
||||
|
||||
function cRange(cFrom, cTo) {
|
||||
var iStart = cFrom.charCodeAt(0);
|
||||
|
||||
return Array.apply(
|
||||
null, Array(cTo.charCodeAt(0) - iStart + 1)
|
||||
).map(function (_, i) {
|
||||
|
||||
return String.fromCharCode(iStart + i);
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
return cRange(cFrom, cTo);
|
||||
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e7b
|
||||
title: Generator/Exponential
|
||||
challengeType: 5
|
||||
forumTopicId: 302275
|
||||
dashedName: generatorexponential
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e80
|
||||
title: 格雷码
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: gray-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -63,5 +64,29 @@ assert.equal(gray(false, 381), 425);
|
||||
assert.equal(gray(false, 725), 870);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gray(enc, number) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gray(enc, number){
|
||||
if(enc){
|
||||
return number ^ (number >> 1);
|
||||
}else{
|
||||
let n = number;
|
||||
|
||||
while (number >>= 1) {
|
||||
n ^= number;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e82
|
||||
title: 最大公约数
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: greatest-common-divisor
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -59,5 +60,20 @@ assert.equal(gcd(13, 250), 1);
|
||||
assert.equal(gcd(1300, 250), 50);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gcd(a, b) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gcd(a, b) {
|
||||
return b==0 ? Math.abs(a):gcd(b, a % b);
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7e84
|
||||
title: 最重要的后续总和
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: greatest-subsequential-sum
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -70,5 +71,41 @@ assert.deepEqual(maximumSubsequence([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]), [
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function maximumSubsequence(population) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function maximumSubsequence(population) {
|
||||
function sumValues(arr) {
|
||||
var result = 0;
|
||||
for (var i = 0, len = arr.length; i < len; i++) {
|
||||
result += arr[i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
var greatest;
|
||||
var maxValue = 0;
|
||||
|
||||
for (var i = 0, len = population.length; i < len; i++) {
|
||||
for (var j = i; j <= len; j++) {
|
||||
var subsequence = population.slice(i, j);
|
||||
var value = sumValues(subsequence);
|
||||
if (value > maxValue) {
|
||||
maxValue = value;
|
||||
greatest = subsequence;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return greatest;
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 595608ff8bcd7a50bd490181
|
||||
title: 冰雹序列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: hailstone-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p> Hailstone数字序列可以从起始正整数n生成: </p>如果n为1,则序列结束。如果n是偶数,那么序列的下一个n <code>= n/2</code>如果n是奇数,那么序列的下一个n <code>= (3 \* n) + 1</code> <p> (未经证实的) <a href='https://en.wikipedia.org/wiki/Collatz conjecture' title='wp:Collatz猜想'>Collatz猜想</a>是任何起始编号的冰雹序列总是终止。 </p><p>冰雹序列也称为冰雹数(因为这些值通常受到多个下降和上升,如云中的冰雹),或者作为Collatz序列。 </p>任务:创建例程以生成数字的hailstone序列。使用例程表明,对于27号的冰雹序列具有开始与112个元件<code>27, 82, 41, 124</code> ,结束时用<code>8, 4, 2, 1</code>与显示具有最长冰雹序列的数目少于100,000一起序列的长度。 (但不要显示实际的序列!)参见: <a href='http://xkcd.com/710' title='链接:http://xkcd.com/710'>xkcd</a> (幽默)。
|
||||
<p> Hailstone数字序列可以从起始正整数n生成: </p>如果n为1,则序列结束。如果n是偶数,那么序列的下一个n <code>= n/2</code>如果n是奇数,那么序列的下一个n <code>= (3 \* n) + 1</code> <p> (未经证实的) <a href='https://en.wikipedia.org/wiki/Collatz conjecture' title='wp:Collatz猜想'>Collatz猜想</a>是任何起始编号的冰雹序列总是终止。 </p><p>冰雹序列也称为冰雹数(因为这些值通常受到多个下降和上升,如云中的冰雹),或者作为Collatz序列。 </p>任务:创建例程以生成数字的hailstone序列。使用例程表明,对于27号的冰雹序列具有开始与112个元件<code>27, 82, 41, 124</code> ,结束时用<code>8, 4, 2, 1</code>与显示具有最长冰雹序列的数目少于100,000一起序列的长度。 (但不要显示实际的序列!)参见: <a href='http://xkcd.com/710' title='链接:http://xkcd.com/710'>xkcd</a> (幽默)。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -23,5 +24,57 @@ assert(typeof hailstoneSequence === 'function');
|
||||
assert.deepEqual(hailstoneSequence(), res);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const res = [[27, 82, 41, 124, 8, 4, 2, 1], [351, 77031]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function hailstoneSequence() {
|
||||
const res = [];
|
||||
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hailstoneSequence () {
|
||||
const res = [];
|
||||
|
||||
function hailstone(n) {
|
||||
const seq = [n];
|
||||
while (n > 1) {
|
||||
n = n % 2 ? 3 * n + 1 : n / 2;
|
||||
seq.push(n);
|
||||
}
|
||||
return seq;
|
||||
}
|
||||
|
||||
const h = hailstone(27);
|
||||
const hLen = h.length;
|
||||
res.push([...h.slice(0, 4), ...h.slice(hLen - 4, hLen)]);
|
||||
|
||||
let n = 0;
|
||||
let max = 0;
|
||||
for (let i = 100000; --i;) {
|
||||
const seq = hailstone(i);
|
||||
const sLen = seq.length;
|
||||
|
||||
if (sLen > max) {
|
||||
n = i;
|
||||
max = sLen;
|
||||
}
|
||||
}
|
||||
res.push([max, n]);
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 594810f028c0303b75339ad1
|
||||
title: 快乐的数字
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: happy-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -89,5 +90,34 @@ assert(happy(32));
|
||||
assert(!happy(33));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function happy(number) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function happy (number) {
|
||||
let m;
|
||||
let digit;
|
||||
const cycle = [];
|
||||
|
||||
while (number !== 1 && cycle[number] !== true) {
|
||||
cycle[number] = true;
|
||||
m = 0;
|
||||
while (number > 0) {
|
||||
digit = number % 10;
|
||||
m += Math.pow(digit, 2);
|
||||
number = (number - digit) / 10;
|
||||
}
|
||||
number = m;
|
||||
}
|
||||
return (number === 1);
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 595668ca4cfe1af2fb9818d4
|
||||
title: Harshad或Niven系列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: harshad-or-niven-series
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -23,5 +24,65 @@ assert(typeof isHarshadOrNiven === 'function');
|
||||
assert.deepEqual(isHarshadOrNiven(), res);
|
||||
```
|
||||
|
||||
# --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() {
|
||||
const res = {
|
||||
firstTwenty: [],
|
||||
firstOver1000: undefined
|
||||
};
|
||||
// Only change code below this line
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isHarshadOrNiven() {
|
||||
const res = {
|
||||
firstTwenty: [],
|
||||
firstOver1000: undefined
|
||||
};
|
||||
|
||||
function isHarshad(n) {
|
||||
let s = 0;
|
||||
const nStr = n.toString();
|
||||
for (let i = 0; i < nStr.length; ++i) {
|
||||
s += parseInt(nStr.charAt(i), 10);
|
||||
}
|
||||
return n % s === 0;
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
const harshads = [];
|
||||
|
||||
for (let n = 1; count < 20; ++n) {
|
||||
if (isHarshad(n)) {
|
||||
count++;
|
||||
harshads.push(n);
|
||||
}
|
||||
}
|
||||
|
||||
res.firstTwenty = harshads;
|
||||
|
||||
let h = 1000;
|
||||
while (!isHarshad(++h));
|
||||
res.firstOver1000 = h;
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 595671d4d2cdc305f0d5b36f
|
||||
title: 来自两个数组的哈希
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: hash-from-two-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -57,5 +58,46 @@ assert.deepEqual(arrToObj(...testCases[4]), res[4]);
|
||||
assert.deepEqual(arrToObj(...testCases[5]), res[5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [
|
||||
[[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd', 'e']],
|
||||
[[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd']],
|
||||
[[1, 2, 3], ['a', 'b', 'c', 'd', 'e']],
|
||||
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]],
|
||||
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4]],
|
||||
[['a', 'b', 'c'], [1, 2, 3, 4, 5]]
|
||||
];
|
||||
|
||||
const res = [
|
||||
{ 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e' },
|
||||
{ 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: undefined },
|
||||
{ 1: 'a', 2: 'b', 3: 'c' },
|
||||
{ a: 1, b: 2, c: 3, d: 4, e: 5 },
|
||||
{ a: 1, b: 2, c: 3, d: 4, e: undefined },
|
||||
{ a: 1, b: 2, c: 3 }
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function arrToObj (keys, vals) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function arrToObj (keys, vals) {
|
||||
return keys.reduce((map, key, index) => {
|
||||
map[key] = vals[index];
|
||||
return map;
|
||||
}, {});
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5956795bc9e2c415eb244de1
|
||||
title: 哈希加入
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: hash-join
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -35,5 +36,83 @@ assert(typeof hashJoin === 'function');
|
||||
assert.deepEqual(hashJoin(hash1, hash2), res);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const hash1 = [
|
||||
{ age: 27, name: 'Jonah' },
|
||||
{ age: 18, name: 'Alan' },
|
||||
{ age: 28, name: 'Glory' },
|
||||
{ age: 18, name: 'Popeye' },
|
||||
{ age: 28, name: 'Alan' }
|
||||
];
|
||||
|
||||
const hash2 = [
|
||||
{ character: 'Jonah', nemesis: 'Whales' },
|
||||
{ character: 'Jonah', nemesis: 'Spiders' },
|
||||
{ character: 'Alan', nemesis: 'Ghosts' },
|
||||
{ character: 'Alan', nemesis: 'Zombies' },
|
||||
{ character: 'Glory', nemesis: 'Buffy' },
|
||||
{ character: 'Bob', nemesis: 'foo' }
|
||||
];
|
||||
|
||||
const res = [
|
||||
{ A_age: 27, A_name: 'Jonah', B_character: 'Jonah', B_nemesis: 'Whales' },
|
||||
{ A_age: 27, A_name: 'Jonah', B_character: 'Jonah', B_nemesis: 'Spiders' },
|
||||
{ A_age: 18, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Ghosts' },
|
||||
{ A_age: 18, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Zombies' },
|
||||
{ A_age: 28, A_name: 'Glory', B_character: 'Glory', B_nemesis: 'Buffy' },
|
||||
{ A_age: 28, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Ghosts' },
|
||||
{ A_age: 28, A_name: 'Alan', B_character: 'Alan', B_nemesis: 'Zombies' }
|
||||
];
|
||||
|
||||
const bench1 = [{ name: 'u2v7v', num: 1 }, { name: 'n53c8', num: 10 }, { name: 'oysce', num: 9 }, { name: '0mto2s', num: 1 }, { name: 'vkh5id', num: 4 }, { name: '5od0cf', num: 8 }, { name: 'uuulue', num: 10 }, { name: '3rgsbi', num: 9 }, { name: 'kccv35r', num: 4 }, { name: '80un74', num: 9 }, { name: 'h4pp3', num: 6 }, { name: '51bit', num: 7 }, { name: 'j9ndf', num: 8 }, { name: 'vf3u1', num: 10 }, { name: 'g0bw0om', num: 10 }, { name: 'j031x', num: 7 }, { name: 'ij3asc', num: 9 }, { name: 'byv83y', num: 8 }, { name: 'bjzp4k', num: 4 }, { name: 'f3kbnm', num: 10 }];
|
||||
const bench2 = [{ friend: 'o8b', num: 8 }, { friend: 'ye', num: 2 }, { friend: '32i', num: 5 }, { friend: 'uz', num: 3 }, { friend: 'a5k', num: 4 }, { friend: 'uad', num: 7 }, { friend: '3w5', num: 10 }, { friend: 'vw', num: 10 }, { friend: 'ah', num: 4 }, { friend: 'qv', num: 7 }, { friend: 'ozv', num: 2 }, { friend: '9ri', num: 10 }, { friend: '7nu', num: 4 }, { friend: 'w3', num: 9 }, { friend: 'tgp', num: 8 }, { friend: 'ibs', num: 1 }, { friend: 'ss7', num: 6 }, { friend: 'g44', num: 9 }, { friend: 'tab', num: 9 }, { friend: 'zem', num: 10 }];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function hashJoin(hash1, hash2) {
|
||||
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hashJoin(hash1, hash2) {
|
||||
const hJoin = (tblA, tblB, strJoin) => {
|
||||
const [jA, jB] = strJoin.split('=');
|
||||
const M = tblB.reduce((a, x) => {
|
||||
const id = x[jB];
|
||||
return (
|
||||
a[id] ? a[id].push(x) : (a[id] = [x]),
|
||||
a
|
||||
);
|
||||
}, {});
|
||||
|
||||
return tblA.reduce((a, x) => {
|
||||
const match = M[x[jA]];
|
||||
return match ? (
|
||||
a.concat(match.map(row => dictConcat(x, row)))
|
||||
) : a;
|
||||
}, []);
|
||||
};
|
||||
|
||||
const dictConcat = (dctA, dctB) => {
|
||||
const ok = Object.keys;
|
||||
return ok(dctB).reduce(
|
||||
(a, k) => (a[`B_${k}`] = dctB[k]) && a,
|
||||
ok(dctA).reduce(
|
||||
(a, k) => (a[`A_${k}`] = dctA[k]) && a, {}
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
return hJoin(hash1, hash2, 'name=character');
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 595b98f8b5a2245e243aa831
|
||||
title: 苍鹭三角形
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: heronian-triangles
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -41,5 +42,92 @@ assert.deepEqual(heronianTriangle(testCases[2]), res[2]);
|
||||
assert.deepEqual(heronianTriangle(testCases[3]), res[3]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const testCases = [10, 15, 20, 25];
|
||||
|
||||
const res = [
|
||||
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]],
|
||||
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],
|
||||
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],
|
||||
[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37], [16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function heronianTriangle(n) {
|
||||
|
||||
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function heronianTriangle(n) {
|
||||
const list = [];
|
||||
const result = [];
|
||||
|
||||
let j = 0;
|
||||
for (let c = 1; c <= 200; c++) {
|
||||
for (let b = 1; b <= c; b++) {
|
||||
for (let a = 1; a <= b; a++) {
|
||||
if (gcd(gcd(a, b), c) === 1 && isHeron(heronArea(a, b, c))) {
|
||||
list[j++] = new Array(a, b, c, heronArea(a, b, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort(list);
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
result[i] = [list[i][0], list[i][1], list[i][2]];
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
function heronArea(a, b, c) {
|
||||
const s = (a + b + c) / 2;
|
||||
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
|
||||
}
|
||||
|
||||
function isHeron(h) { return h % 1 === 0 && h > 0; }
|
||||
|
||||
function gcd(a, b) {
|
||||
let leftover = 1;
|
||||
let dividend = a > b ? a : b;
|
||||
let divisor = a > b ? b : a;
|
||||
while (leftover !== 0) {
|
||||
leftover = dividend % divisor;
|
||||
if (leftover > 0) {
|
||||
dividend = divisor;
|
||||
divisor = leftover;
|
||||
}
|
||||
}
|
||||
return divisor;
|
||||
}
|
||||
|
||||
function sort(arg) {
|
||||
let swapped = true;
|
||||
let temp = [];
|
||||
while (swapped) {
|
||||
swapped = false;
|
||||
for (let i = 1; i < arg.length; i++) {
|
||||
if (arg[i][4] < arg[i - 1][4] || arg[i][4] === arg[i - 1][4] && arg[i][3] < arg[i - 1][3]) {
|
||||
temp = arg[i];
|
||||
arg[i] = arg[i - 1];
|
||||
arg[i - 1] = temp;
|
||||
swapped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 59622f89e4e137560018a40e
|
||||
title: Hofstadter图 - 图序列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: hofstadter-figure-figure-sequences
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p>这两个正整数序列定义为: </p><p> <big>$$ R(1)= 1 \; \ S(1)= 2 \\ R(n)= R(n-1)+ S(n-1),\ quad n> 1. $$</big> </p><p>序列<big>$ S(n)$</big>进一步定义为<big>$ R(n)$中</big>不存在的正整数序列。 </p><p>序列<big>$ R $</big>开始: </p><p> 1,3,7,12,18 ...... </p><p>序列<big>$ S $</big>开始: </p><p> 2,4,5,6,8 ...... </p>任务:创建两个名为ffr和ffs的函数,当给定n分别返回R(n)或S(n)时(注意R(1)= 1且S(1)= 2以避免逐个错误) 。不应假设n的最大值。 Sloane的<a href='http://oeis.org/A005228' title='链接:http://oeis.org/A005228'>A005228</a>和<a href='http://oeis.org/A030124' title='链接:http://oeis.org/A030124'>A030124</a> 。 <a href='http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html' title='链接:http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html'>Wolfram MathWorld</a>维基百科: <a href='https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences' title='wp:Hofstadter_sequence#Hofstadter_Figure-Figure_sequences'>Hofstadter图 - 图序列</a> 。
|
||||
<p>这两个正整数序列定义为: </p><p> <big>$$ R(1)= 1 \; \ S(1)= 2 \\ R(n)= R(n-1)+ S(n-1),\ quad n> 1. $$</big> </p><p>序列<big>$ S(n)$</big>进一步定义为<big>$ R(n)$中</big>不存在的正整数序列。 </p><p>序列<big>$ R $</big>开始: </p><p> 1,3,7,12,18 ...... </p><p>序列<big>$ S $</big>开始: </p><p> 2,4,5,6,8 ...... </p>任务:创建两个名为ffr和ffs的函数,当给定n分别返回R(n)或S(n)时(注意R(1)= 1且S(1)= 2以避免逐个错误) 。不应假设n的最大值。 Sloane的<a href='http://oeis.org/A005228' title='链接:http://oeis.org/A005228'>A005228</a>和<a href='http://oeis.org/A030124' title='链接:http://oeis.org/A030124'>A030124</a> 。 <a href='http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html' title='链接:http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html'>Wolfram MathWorld</a>维基百科: <a href='https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences' title='wp:Hofstadter_sequence#Hofstadter_Figure-Figure_sequences'>Hofstadter图 - 图序列</a> 。
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -83,5 +84,54 @@ assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1]);
|
||||
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) {
|
||||
return n;
|
||||
}
|
||||
|
||||
function ffs(n) {
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const R = [null, 1];
|
||||
const S = [null, 2];
|
||||
|
||||
function extendSequences (n) {
|
||||
let current = Math.max(R[R.length - 1], S[S.length - 1]);
|
||||
let i;
|
||||
while (R.length <= n || S.length <= n) {
|
||||
i = Math.min(R.length, S.length) - 1;
|
||||
current += 1;
|
||||
if (current === R[i] + S[i]) {
|
||||
R.push(current);
|
||||
} else {
|
||||
S.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ffr (n) {
|
||||
extendSequences(n);
|
||||
return R[n];
|
||||
}
|
||||
|
||||
function ffs (n) {
|
||||
extendSequences(n);
|
||||
return S[n];
|
||||
}
|
||||
```
|
||||
|
@ -3,11 +3,12 @@ id: 59637c4d89f6786115efd814
|
||||
title: Hofstadter Q序列
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: hofstadter-q-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<p> <a href='https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence' title='wp:Hofstadter_sequence#Hofstadter_Q_sequence'>Hofstadter Q序列</a>定义为: </p><p> $ Q(1)= Q(2)= 1,\\ Q(n)= Q \ big(nQ(n-1)\ big)+ Q \ big(nQ(n-2)),\ quad n> 2. $ </p><p>它定义为<a href='http://rosettacode.org/wiki/Fibonacci sequence' title='斐波那契序列'>Fibonacci序列</a> ,但<a href='http://rosettacode.org/wiki/Fibonacci sequence' title='斐波那契序列'>Fibonacci序列中</a>的下一个术语是前两个术语的总和,在Q序列中,前两个术语告诉您在Q序列中返回多远以找到两个数字总结以制作序列的下一个术语。 </p>任务:将Hofstadter Q Sequence方程实现为JavaScript
|
||||
<p> <a href='https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence' title='wp:Hofstadter_sequence#Hofstadter_Q_sequence'>Hofstadter Q序列</a>定义为: </p><p> $ Q(1)= Q(2)= 1,\\ Q(n)= Q \ big(nQ(n-1)\ big)+ Q \ big(nQ(n-2)),\ quad n> 2. $ </p><p>它定义为<a href='http://rosettacode.org/wiki/Fibonacci sequence' title='斐波那契序列'>Fibonacci序列</a> ,但<a href='http://rosettacode.org/wiki/Fibonacci sequence' title='斐波那契序列'>Fibonacci序列中</a>的下一个术语是前两个术语的总和,在Q序列中,前两个术语告诉您在Q序列中返回多远以找到两个数字总结以制作序列的下一个术语。 </p>任务:将Hofstadter Q Sequence方程实现为JavaScript
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -47,5 +48,37 @@ assert.equal(hofstadterQ(testCase[2]), res[2]);
|
||||
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) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hofstadterQ (n) {
|
||||
const memo = [1, 1, 1];
|
||||
const Q = function (i) {
|
||||
let result = memo[i];
|
||||
if (typeof result !== 'number') {
|
||||
result = Q(i - Q(i - 1)) + Q(i - Q(i - 2));
|
||||
memo[i] = result;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
return Q(n);
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7eb0
|
||||
title: 我在E之前除了C之后
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: i-before-e-except-after-c
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -64,5 +65,25 @@ assert.equal(IBeforeExceptC('insufficient'), false);
|
||||
assert.equal(IBeforeExceptC('omniscient'), false);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function IBeforeExceptC(word) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7eaf
|
||||
title: 他们
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: iban
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -59,5 +60,37 @@ assert.equal(isValid('GB82 TEST 1234 5698 7654 32'), false);
|
||||
assert.equal(isValid('SA03 8000 0000 6080 1016 7519'), true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isValid(iban) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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
|
||||
}
|
||||
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
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7eb1
|
||||
title: 身份矩阵
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: identity-matrix
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -47,5 +48,33 @@ assert.deepEqual(idMatrix(3), results[2]);
|
||||
assert.deepEqual(idMatrix(4), results[3]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
let results=[[ [ 1 ] ],
|
||||
[ [ 1, 0 ], [ 0, 1 ] ],
|
||||
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ],
|
||||
[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]]
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function idMatrix(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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;
|
||||
})
|
||||
});
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ec1
|
||||
title: 迭代的数字平方
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: iterated-digits-squaring
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -66,5 +67,29 @@ assert.equal(iteratedSquare(70), 1);
|
||||
assert.equal(iteratedSquare(100), 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function iteratedSquare(n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --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;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ec2
|
||||
title: Jaro距离
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: jaro-distance
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -65,5 +66,59 @@ assert.equal(jaro('HELLOS', 'CHELLO'), 0.888888888888889);
|
||||
assert.equal(jaro('ABCD', 'BCDA'), 0.8333333333333334);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function jaro(s, t) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function jaro(s, t) {
|
||||
var s_len = s.length;
|
||||
var t_len = t.length;
|
||||
|
||||
if (s_len == 0 && t_len == 0) return 1;
|
||||
|
||||
var match_distance = Math.max(s_len, t_len) / 2 - 1;
|
||||
|
||||
var s_matches = new Array(s_len);
|
||||
var t_matches = new Array(t_len);
|
||||
|
||||
var matches = 0;
|
||||
var transpositions = 0;
|
||||
|
||||
for (var i = 0; i < s_len; i++) {
|
||||
var start = Math.max(0, i - match_distance);
|
||||
var end = Math.min(i + match_distance + 1, t_len);
|
||||
|
||||
for (var j = start; j < end; j++) {
|
||||
if (t_matches[j]) continue;
|
||||
if (s.charAt(i) != t.charAt(j)) continue;
|
||||
s_matches[i] = true;
|
||||
t_matches[j] = true;
|
||||
matches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (matches == 0) return 0;
|
||||
|
||||
var k = 0;
|
||||
for (var i = 0; i < s_len; i++) {
|
||||
if (!s_matches[i]) continue;
|
||||
while (!t_matches[k]) k++;
|
||||
if (s.charAt(i) != t.charAt(k)) transpositions++;
|
||||
k++;
|
||||
}
|
||||
|
||||
return ((matches / s_len) +
|
||||
(matches / t_len) +
|
||||
((matches - transpositions / 2.0) / matches)) / 3.0;
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ec4
|
||||
title: JortSort
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: jortsort
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -59,5 +60,29 @@ assert.equal(jortsort([5, 4, 3, 2, 1]), false);
|
||||
assert.equal(jortsort([1, 1, 1, 1, 1]), true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function jortsort(array) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function jortsort(array) {
|
||||
// sort the array
|
||||
var originalArray = array.slice(0);
|
||||
array.sort( function(a,b){return a - b} );
|
||||
|
||||
// compare to see if it was originally sorted
|
||||
for (var i = 0; i < originalArray.length; ++i) {
|
||||
if (originalArray[i] !== array[i]) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ec5
|
||||
title: 约瑟夫斯问题
|
||||
challengeType: 5
|
||||
videoUrl: ''
|
||||
dashedName: josephus-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
@ -53,5 +54,50 @@ assert.equal(josephus(17, 6), 2);
|
||||
assert.equal(josephus(29, 4), 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function josephus(init, kill) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function josephus(init, kill) {
|
||||
var Josephus = {
|
||||
init: function(n) {
|
||||
this.head = {};
|
||||
var current = this.head;
|
||||
for (var i = 0; i < n - 1; i++) {
|
||||
current.label = i + 1;
|
||||
current.next = {
|
||||
prev: current
|
||||
};
|
||||
current = current.next;
|
||||
}
|
||||
current.label = n;
|
||||
current.next = this.head;
|
||||
this.head.prev = current;
|
||||
return this;
|
||||
},
|
||||
kill: function(spacing) {
|
||||
var current = this.head;
|
||||
while (current.next !== current) {
|
||||
for (var i = 0; i < spacing - 1; i++) {
|
||||
current = current.next;
|
||||
}
|
||||
current.prev.next = current.next;
|
||||
current.next.prev = current.prev;
|
||||
current = current.next;
|
||||
}
|
||||
return current.label;
|
||||
}
|
||||
}
|
||||
|
||||
return Josephus.init(init).kill(kill)
|
||||
}
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ecb
|
||||
title: K-d tree
|
||||
challengeType: 5
|
||||
forumTopicId: 302295
|
||||
dashedName: k-d-tree
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7eca
|
||||
title: Kaprekar numbers
|
||||
challengeType: 5
|
||||
forumTopicId: 302296
|
||||
dashedName: kaprekar-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ed1
|
||||
title: Knapsack problem/0-1
|
||||
challengeType: 5
|
||||
forumTopicId: 323649
|
||||
dashedName: knapsack-problem0-1
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ed2
|
||||
title: Knapsack problem/Bounded
|
||||
challengeType: 5
|
||||
forumTopicId: 323652
|
||||
dashedName: knapsack-problembounded
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ed3
|
||||
title: Knapsack problem/Continuous
|
||||
challengeType: 5
|
||||
forumTopicId: 323654
|
||||
dashedName: knapsack-problemcontinuous
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ed4
|
||||
title: Knapsack problem/Unbounded
|
||||
challengeType: 5
|
||||
forumTopicId: 323655
|
||||
dashedName: knapsack-problemunbounded
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ed5
|
||||
title: Knight's tour
|
||||
challengeType: 5
|
||||
forumTopicId: 302297
|
||||
dashedName: knights-tour
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7edb
|
||||
title: Largest int from concatenated ints
|
||||
challengeType: 5
|
||||
forumTopicId: 302298
|
||||
dashedName: largest-int-from-concatenated-ints
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7edc
|
||||
title: Last Friday of each month
|
||||
challengeType: 5
|
||||
forumTopicId: 302299
|
||||
dashedName: last-friday-of-each-month
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e4ce2b6ac708cc68c1df25e
|
||||
title: Last letter-first letter
|
||||
challengeType: 5
|
||||
forumTopicId: 385256
|
||||
dashedName: last-letter-first-letter
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ede
|
||||
title: Leap year
|
||||
challengeType: 5
|
||||
forumTopicId: 302300
|
||||
dashedName: leap-year
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7edf
|
||||
title: Least common multiple
|
||||
challengeType: 5
|
||||
forumTopicId: 302301
|
||||
dashedName: least-common-multiple
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5a23c84252665b21eecc7ee0
|
||||
title: Left factorials
|
||||
challengeType: 5
|
||||
forumTopicId: 302302
|
||||
dashedName: left-factorials
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e4ce2bbac708cc68c1df25f
|
||||
title: Letter frequency
|
||||
challengeType: 5
|
||||
forumTopicId: 385263
|
||||
dashedName: letter-frequency
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e4ce2eaac708cc68c1df260
|
||||
title: Levenshtein distance
|
||||
challengeType: 5
|
||||
forumTopicId: 385264
|
||||
dashedName: levenshtein-distance
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e4ce2f5ac708cc68c1df261
|
||||
title: Linear congruential generator
|
||||
challengeType: 5
|
||||
forumTopicId: 385266
|
||||
dashedName: linear-congruential-generator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e4ce2a1ac708cc68c1df25d
|
||||
title: Long multiplication
|
||||
challengeType: 5
|
||||
forumTopicId: 385269
|
||||
dashedName: long-multiplication
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e6dd1278e6ca105cde40ea9
|
||||
title: Longest common subsequence
|
||||
challengeType: 5
|
||||
forumTopicId: 385271
|
||||
dashedName: longest-common-subsequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e6dd139859c290b6ab80292
|
||||
title: Longest increasing subsequence
|
||||
challengeType: 5
|
||||
forumTopicId: 385272
|
||||
dashedName: longest-increasing-subsequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e6dd14192286d95fc43046e
|
||||
title: Longest string challenge
|
||||
challengeType: 5
|
||||
forumTopicId: 385275
|
||||
dashedName: longest-string-challenge
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e6dd14797f5ce267c2f19d0
|
||||
title: Look-and-say sequence
|
||||
challengeType: 5
|
||||
forumTopicId: 385277
|
||||
dashedName: look-and-say-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e6dd15004c88cf00d2a78b3
|
||||
title: Loop over multiple arrays simultaneously
|
||||
challengeType: 5
|
||||
forumTopicId: 385279
|
||||
dashedName: loop-over-multiple-arrays-simultaneously
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
@ -3,6 +3,7 @@ id: 5e6decd8ec8d7db960950d1c
|
||||
title: LU decomposition
|
||||
challengeType: 5
|
||||
forumTopicId: 385280
|
||||
dashedName: lu-decomposition
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user