Created
June 15, 2018 02:03
-
-
Save chrisdothtml/fe91d19717a7c0e4ca19d2aa57b3c5fd to your computer and use it in GitHub Desktop.
Generate Recamán sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate Recamán sequence up to `maxNum` | |
* https://youtu.be/FGC5TdIiT9U | |
* | |
* @param {Number} maxNum | |
* @returns {Set} | |
*/ | |
function recaman (maxNum) { | |
const result = new Set([0]) | |
let current, hop | |
for (current = 0, hop = 1;;hop++) { | |
const backwardsHop = current - hop | |
const backwardsIsInvalid = result.has(backwardsHop) || backwardsHop < 0 | |
const next = backwardsIsInvalid ? (current + hop) : backwardsHop | |
if (next < maxNum) { | |
result.add(next) | |
current = next | |
} else { | |
break | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment