Jump to content

Department numbers: Difference between revisions

m
m (→‎JS ES6: Tidied.)
Line 2,334:
{{Trans|Haskell}}
<lang JavaScript>(() => {
'"use strict'";
 
// NUMBERING CONSTRAINTS ------------------------------------ NUMBERING CONSTRAINTS --------------
 
// options :: Int -> Int -> Int -> [(Int, Int, Int)]
const options = (lo, => hi, => total) => {
const
bind = flipxs => f => xs.flatMap(concatMapf),
ds = enumFromTo(lo, )(hi);
 
return bind(ds.filter(even, ds),)(
x => bind(ds.filter(d => d !== x, ds),)(
y => bind([total - (x + y)],)(
z => (z !== y && lo <= z && z <= hi) ? [
[x, y, z]
Line 2,352:
)
)
);
};
 
// GENERIC FUNCTIONS ------------------------------- TEST -----------------------
const mapmain = (f, xs) => xs.map(f);{
const
return ' label = "(Police, Sanitation, Fire)\n\n' +",
const xs solutions = options(1, )(7, )(12);,
n = solutions.length,
list = solutions
.map(JSON.stringify)
const unlines = xs => xs .join('"\n'");
 
return (
// concatMap :: (a -> [b]) -> [a] -> [b]
' `${label}\n\n${list}\n\nNumber of options: ' + length(xs);${n}`
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
);
};
 
// TEST --------------------------------------------------- GENERIC FUNCTIONS ----------------
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
n => Array.from({
length: Math.floor(1 + n - m) + 1
}, (_, i) => m + i);
 
Line 2,369 ⟶ 2,381:
const even = n => n % 2 === 0;
 
// filter :: (aMAIN -> Bool) -> [a] -> [a]
return main();
const filter = (f, xs) => xs.filter(f);
 
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f => (a, b) => f.apply(null, [b, a]);
 
// length :: [a] -> Int
const length = xs => xs.length;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// show :: a -> String
const show = x => JSON.stringify(x) //, null, 2);
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// TEST -------------------------------------------------------------------
const xs = options(1, 7, 12);
return '(Police, Sanitation, Fire)\n\n' +
unlines(map(show, xs)) +
'\n\nNumber of options: ' + length(xs);
})();</lang>
{{Out}}
9,658

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.