3 ms·
Now that I think of it, even the flatMap version builds a lot of unnecessary arrays. The comprehension isn't just more readable, it's also more efficient. (Unle
by omaranto 7y ago
Now that I think of it, even the flatMap version builds a lot of unnecessary arrays. The comprehension isn't just more readable, it's also more efficient. (Unless you're using a fancy compiler like GHC that does deforestation, in which case the flatMap/filter version should be as efficient as the list comprehension.)
- 11235813213455 7y agoThose 2 solutions below, that currently work in JS, are equivalent to the python solution in terms of complexity But, yes I'm not satisfied in terms of readability, I linked to a proposal for iteration helpers, which would do this lazy-evaluation, I don't know if it can do it deeply like you say, interesting thing to see function gcd(a, b) { return b ? gcd(b, a % b) : Math.abs(a); } function isInteger(n) { return Math.abs(Math.floor(n + .5) - n) <= Number.EPSILON; } const range = (start, end) => Array.from({length: end-start}, (_,i) => start+i) console.log( range(1, 30) .flatMap(a => range(a+1, 30).filter(b => gcd(a,b)==1) .flatMap(b => range(b+1, 30).filter(c => gcd(a,c)==1 && gcd(b,c)==1 && isInteger((a**3+b**3+c**3)**(1/3))) .flatMap(c => [[a, b, c]]) ) ) ) function* tripleSortedRelPrimeCubes(start, end) { for (let a=start; a<end; a++) { for (let b=a+1; b<end; b++) { for (let c=b+1; c<end; c++) { if ( gcd(a,b)==1 && gcd(a,c)==1 && gcd(b,c)==1 && isInteger((a**3+b**3+c**3)**(1/3)) ) yield [a, b, c]; } } } } console.log( [...tripleSortedRelPrimeCubes(1, 30)] )