Skip to content

Instantly share code, notes, and snippets.

@Danjb1
Created March 9, 2020 12:27
Show Gist options
  • Save Danjb1/0564b8acd2f6e8b3e6ff625e268d9624 to your computer and use it in GitHub Desktop.
Save Danjb1/0564b8acd2f6e8b3e6ff625e268d9624 to your computer and use it in GitHub Desktop.
Programming challenge to find an element within a sequence.
/*
* TASK:
* Calculate the 15th element for this sequence: 2, 2, 4, 6, 10, 16, ...
*/
const sequence = (n) => {
if (n < 0) {
throw new Error('n must be >= 0');
}
return _sequence(n, 0, 0, 0);
}
const _sequence = (n, i, prev1, prev2) => {
const thisElem = (i <= 1)
? 2
: prev1 + prev2;
return i == n
? thisElem
: _sequence(n, i + 1, prev2, thisElem);
}
for (let i = 0; i < 15; i++) {
console.log(i + ' -> ' + sequence(i));
}
/*
* QUESTIONS:
*
* 1) What is the 15th element of the sequence?
*
* 1220
*
* 2) What is your solution time and space complexity, for the n(th) element
* of the sequence?
* Time complexity = O(n)
* Space complexity = O(n), due to the recursive call stack
*
* This could become O(1) if a loop was used instead.
*
* 3) What clean code principles have been used, and why?
*
* - Line breaks to enhance readability
* - Sensible variable names for readability
* - Clean public interface (sequence), with the internal implementation
* details kept private (_sequence), for ease of use
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment