Sum and product puzzle: Difference between revisions

→‎JS ES6: Updated primitives, tidied.
(→‎JS ES6: Updated primitives, tidied.)
Line 1,364:
{{Trans|Haskell}}
<lang JavaScript>(() => {
'"use strict'";
 
// lengthmain :: [a]IO -> Int()
const main = () => {
 
const
// xs :: [Int]
xs = enumFromTo(1, )(100),
 
// s1 s2, s3, s4 :: [(Int, Int)]
s1 = concatMapxs.flatMap(x => concatMap(y =>
((1 < x) &&=> xs.flatMap(x < y) && 100 => (x + y)) ? [
[(1 < x,) && (x < y]) && 100 > (x + y) ? [
] : []x, y]
xs), xs), ] : []
s2 = filter( )
p => all(q => 1 < length(mulEq(q, s1)), sumEq(p, s1)),
s1
),
s3s2 = s1.filter(
p => 1sumEq(p, === length(intersectBys1).every(
pairEQ,q => 1 < mulEq(pq, s1), s2.length
)),
s2),
s3 = s2.filter(
p => 1 === intersectBy(pairEQ)(
p => all(q => 1 < length(mulEq(q, s1)), sumEq(p, s1)),
s1)(s2).length
);
 
return s3.filter(
p => 1 === length(intersectBy(pairEQ)(
pairEQ, sumEq(p, s1), s3
)(s3).length
);
};
 
// PROBLEM FUNCTIONS ------------------ PROBLEM FUNCTIONS ----------------
 
// add, mul :: (Int, Int) -> Int
Line 1,403 ⟶ 1,405:
mul = xy => xy[0] * xy[1],
 
// sumEq, mulEq :: (Int, Int) -> [(Int, Int)] -> [(Int, Int)]
// [(Int, Int)] -> [(Int, Int)]
sumEq = (p, s) => {
const addP = add(p);
 
return s.filter(q => add(q) === addP, s);
},
mulEq = (p, s) => {
const mulP = mul(p);
 
return s.filter(q => mul(q) === mulP, s);
},
 
// pairEQ :: ((a, a) -> (a, a)) -> Bool
pairEQ = (a, b) => (a[0]b === b[0]) &&> (a[1] === b[1]);
xs.lengtha[0] === b[0]
) :&& Infinity(a[1] === b[1]);
 
 
// GENERIC FUNCTIONS ------------------ GENERIC FUNCTIONS ----------------
 
// all :: (a -> Bool) -> [a] -> Bool
const all = (p, xs) => xs.every(p);
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) =>
xs.reduce((a, x) => a.concat(f(x)), []);
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
 
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
 
// intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
const intersectBy = (eq, xs, ys)eqFn => {
const// ceqThe =intersection curry(eq);of the lists xs and ys
return// (0in <terms xs.lengthof &&the 0equality <defined ysby eq.length) ?
xs => ys => xs.filter(x => ys.some(ceq(x))) : [];
x => ys.some(eqFn(x))
} );
 
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
 
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
 
// MAIN ---
Line 1,460 ⟶ 1,446:
{{Out}}
<lang JavaScript>[[4, 13]]</lang>
(Finished in 0.307s)
 
=={{header|jq}}==
9,655

edits