Pythagorean triples: Difference between revisions
Content added Content deleted
No edit summary |
(→JS ES6: Updated primitives, tidied.) |
||
Line 2,927: | Line 2,927: | ||
Exhaustive search of a full cartesian product. Not scalable. |
Exhaustive search of a full cartesian product. Not scalable. |
||
<lang JavaScript>(() => { |
<lang JavaScript>(() => { |
||
"use strict"; |
|||
// Arguments: predicate, maximum perimeter |
// Arguments: predicate, maximum perimeter |
||
// pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int |
// pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int |
||
const pythTripleCount = |
const pythTripleCount = p => |
||
maxPerim => { |
|||
⚫ | |||
⚫ | |||
xs = enumFromTo(1)( |
|||
⚫ | |||
⚫ | |||
return xs.flatMap( |
|||
x => xs.slice(x).flatMap( |
|||
y => xs.slice(y).flatMap( |
|||
((x + y + z <= maxPerim) && |
z => ((x + y + z <= maxPerim) && |
||
(x * x + y * y === z * z) && |
((x * x) + (y * y) === z * z) && |
||
p(x, y, z)) ? [ |
p(x, y, z)) ? [ |
||
[x, y, z] |
[x, y, z] |
||
] : [] |
] : [] |
||
) |
|||
) |
) |
||
.length; |
).length; |
||
}; |
}; |
||
// |
// ---------------------- TEST ----------------------- |
||
⚫ | |||
⚫ | |||
maxPerimeter: n, |
|||
⚫ | |||
primitives: pythTripleCount( |
|||
(x, y) => gcd(x)(y) === 1 |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
xs.length > 0 ? [].concat.apply([], xs.map(f)) : []; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
(typeof m !== 'number' ? ( |
|||
⚫ | |||
⚫ | |||
⚫ | |||
// |
// abs :: Num -> Num |
||
const |
const abs = |
||
// Absolute value of a given number |
|||
// without the sign. |
|||
x => 0 > x ? ( |
|||
-x |
|||
) : x; |
|||
// gcd :: Int -> Int -> Int |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
const enumFromTo = m => |
|||
n => Array.from({ |
|||
length: 1 + n - m |
|||
}, (_, i) => m + i); |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
y => { |
|||
const zero = x.constructor(0); |
|||
⚫ | |||
zero === b ? ( |
|||
a |
|||
⚫ | |||
⚫ | |||
}; |
|||
// MAIN --- |
|||
return main(); |
|||
})();</lang> |
})();</lang> |
||
{{Out}} |
{{Out}} |