Created
April 28, 2020 05:34
-
-
Save ShinNoNoir/8c4a7ad755490fe27c69fec20a61bdb4 to your computer and use it in GitHub Desktop.
Project Euler 14
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
// Project Euler 14, but in JS (longest Collatz chain for starting n < 1e6) | |
// Take a cup of ☕, this is going to take a while... (because it's slow) | |
function* collatzSeq(n) { | |
yield n; | |
if (n<=1) return; | |
yield* collatzSeq(n%2==0 ? n/2 : 3*n+1); | |
} | |
function seqLength(s) { | |
let i=0; | |
for (const _ of s) ++i; | |
return i; | |
} | |
function* range(start, end) { | |
for (let i=start; i != end; yield(i++)); | |
} | |
function* map(s, f) { | |
for (const x of s) yield f(x); | |
} | |
function maxBy(s, by) { | |
let maxValue = Number.MIN_VALUE; | |
let res = undefined; | |
for (const x of s) { | |
const cmpValue = by(x); | |
if (cmpValue > maxValue) { | |
maxValue = cmpValue; | |
res = x; | |
} | |
} | |
return res; | |
} | |
let [length, n] = maxBy(map(range(1,1000000), n => [seqLength(collatzSeq(n)), n]), x=>x[0]) | |
console.log(`seqLength(collatzSeq(${n})) == ${length}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment