Permutations: Difference between revisions

→‎JS ES6: Updated and pruned primitives, confined recursion to local scope, tidied slightly.
(→‎Functional Python: Shed one pair of redundant brackets)
(→‎JS ES6: Updated and pruned primitives, confined recursion to local scope, tidied slightly.)
Line 3,235:
 
===ES6===
Recursively, in terms of concatMap and delete:
 
<lang JavaScript>(() => {
'use strict';
 
// permutations :: [a] -> [[a]]
const permutations = xs => {
xs.lengthconst ? concatMap(xgo => concatMap(ysxs => [xs.length ? (
[x].concatconcatMap(ys)
], x => concatMap(
permutations(delete_(x, xs))), xs) : ys => [[x].concat(ys)],
[] go(delete_(x, xs))), xs
]; )
) : [[]];
return go(xs);
//};
 
// GENERIC FUNCTIONS ----------------------------------
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
// deleteByxs.reduce((a, bx) => a === b, .concat(f(x)), xs[]);
//
// // delete :: Eq a => a -> [a] -> [a]
// const delete_ = (x, xs) =>
// deleteBy((a, b) => a === b, x, xs);
 
// delete_ :: Eq a => a -> [a] -> [a]
const delete_ = (x, xs) =>
xs.length > 0 ? (
(x === xs[0]) ? (
xs.slice(1)
) : [xs[0]].concat(delete_(x, xs.slice(1)))
) : [];
 
// rangedelete :: IntEq a => a -> Int[a] -> [Inta]
const rangedelete_ = (mx, nxs) => {
Array.from(const go = xs => {
length:return Math.floor(n0 -< m)xs.length +? 1(
}, (_, i) => m + i (x === xs[0]); ? (
xs.slice(1)
) : [xs[0]].concat(delete_go(x, xs.slice(1)))
(x) ===: xs[0]) ? (;
}
return go(xs);
};
 
// TEST
return permutationsJSON.stringify(['Aardvarks', 'eat', 'ants']);
permutations(['Aardvarks', 'eat', 'ants'])
);
})();</lang>
 
 
{{Out}}
<lang JavaScript>[["Aardvarks", "eat", "ants"], ["Aardvarks", "ants", "eat"],
9,659

edits