2018-09-30 22:01:58 +00:00
---
id: 59637c4d89f6786115efd814
2020-11-27 18:02:05 +00:00
title: Hofstadter Q sequence
2018-09-30 22:01:58 +00:00
challengeType: 5
2019-08-05 16:17:33 +00:00
forumTopicId: 302287
2021-01-13 02:31:00 +00:00
dashedName: hofstadter-q-sequence
2018-09-30 22:01:58 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
The [Hofstadter Q sequence ](https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence "wp: Hofstadter_sequence#Hofstadter_Q_sequence" ) is defined as:
$Q(1)=Q(2)=1, \\\\ Q(n)=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)), \\quad n>2.$
It is defined like the [Fibonacci sequence ](<https://rosettacode.org/wiki/Fibonacci sequence> "Fibonacci sequence" ), but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.
# --instructions--
Implement the Hofstadter Q Sequence equation as a function. The function should accept number, `n` , and return an integer.
# --hints--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`hofstadterQ` should be a function.
```js
assert(typeof hofstadterQ === 'function');
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
`hofstadterQ()` should return `integer`
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert(Number.isInteger(hofstadterQ(1000)));
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`hofstadterQ(1000)` should return `502`
2018-09-30 22:01:58 +00:00
```js
2020-11-27 18:02:05 +00:00
assert.equal(hofstadterQ(testCase[0]), res[0]);
```
2020-09-15 16:57:40 +00:00
2020-11-27 18:02:05 +00:00
`hofstadterQ(1500)` should return `755`
```js
assert.equal(hofstadterQ(testCase[1]), res[1]);
```
`hofstadterQ(2000)` should return `1005`
```js
assert.equal(hofstadterQ(testCase[2]), res[2]);
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
`hofstadterQ(2500)` should return `1261`
```js
assert.equal(hofstadterQ(testCase[3]), res[3]);
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --seed--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
## --after-user-code--
2018-09-30 22:01:58 +00:00
```js
2018-10-20 18:02:47 +00:00
const testCase = [1000, 1500, 2000, 2500];
const res = [502, 755, 1005, 1261];
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
function hofstadterQ(n) {
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
return n;
}
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-09-30 22:01:58 +00:00
```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);
}
```