Skip to content

Instantly share code, notes, and snippets.

@rinchik
Last active December 31, 2016 16:35
Show Gist options
  • Select an option

  • Save rinchik/1125ccec91a68e326790b618ee3dbda2 to your computer and use it in GitHub Desktop.

Select an option

Save rinchik/1125ccec91a68e326790b618ee3dbda2 to your computer and use it in GitHub Desktop.
Collatz Conjecture with JavaScript: Simple link-less levels
function collatz(maxLevels){
let levels = [[1]]
while (levels.length < maxLevels) {
let level = [];
levels[levels.length-1].forEach(function(num){
const mod6 = ((num-4)%6);
const odd = (num-1)/3;
if (!mod6 && odd != 1) {
level.push(odd)
}
level.push(num*2);
})
levels.push(level);
}
return levels;
}
console.log(collatz(5))
// [[1], [2], [4], [8], [16]]
console.log(collatz(6))
// [[1], [2], [4], [8], [16], [5, 32]]
console.log(collatz(8))
// [[1], [2], [4], [8], [16], [5, 32], [10, 64], [3, 20, 21, 128]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment