2.8 KiB
2.8 KiB
title | id | challengeType |
---|---|---|
Hofstadter Q sequence | 59637c4d89f6786115efd814 | 5 |
Description
Instructions
n
, and return an integer.
Tests
tests:
- text: <code>hofstadterQ</code> is a function.
testString: assert(typeof hofstadterQ === 'function', '<code>hofstadterQ</code> is a function.');
- text: <code>hofstadterQ()</code> should return <code>integer</code>
testString: assert(Number.isInteger(hofstadterQ(1000)), '<code>hofstadterQ()</code> should return <code>integer</code>');
- text: <code>hofstadterQ(1000)</code> should return <code>502</code>
testString: assert.equal(hofstadterQ(testCase[0]), res[0], '<code>hofstadterQ(1000)</code> should return <code>502</code>');
- text: <code>hofstadterQ(1500)</code> should return <code>755</code>
testString: assert.equal(hofstadterQ(testCase[1]), res[1], '<code>hofstadterQ(1500)</code> should return <code>755</code>');
- text: <code>hofstadterQ(2000)</code> should return <code>1005</code>
testString: assert.equal(hofstadterQ(testCase[2]), res[2], '<code>hofstadterQ(2000)</code> should return <code>1005</code>');
- text: <code>hofstadterQ(2500)</code> should return <code>1261</code>
testString: assert.equal(hofstadterQ(testCase[3]), res[3], '<code>hofstadterQ(2500)</code> should return <code>1261</code>');
Challenge Seed
function hofstadterQ(n) {
// Good luck!
return n;
}
After Test
const testCase = [1000, 1500, 2000, 2500];
const res = [502, 755, 1005, 1261];
Solution
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);
}