编程语言
首页 > 编程语言> > javascript – 获取每个可能的元素组合

javascript – 获取每个可能的元素组合

作者:互联网

你如何获得数组中2个元素的所有可能组合?

例如:

[
    1, 
    2, 
    3, 
    4 
]

becomes

[
    [1, 2], 
    [1, 3], 
    [1, 4], 
    [2, 1], 
    [2, 3], 
    [2, 4],
    [3, 1],
    [3, 2],
    [3, 4],
    [4, 1],
    [4, 2],
    [4, 3] 
]

这个答案使用蛮力但是有一种功能性的方式与Ramda和或currying? Derive every possible combination of elements in array

解决方法:

这是一个优雅的解决方案:

//    permutations :: Number -> [a] -> [[a]]
const permutations = R.compose(R.sequence(R.of), R.flip(R.repeat));

用法示例:

permutations(2, [1, 2, 3, 4]);
// => [[1, 1], [1, 2], ..., [4, 3], [4, 4]]

permutations(3, [1, 2, 3, 4]);
// => [[1, 1, 1], [1, 1, 2], ..., [4, 4, 3], [4, 4, 4]]

标签:ramda-js,javascript
来源: https://codeday.me/bug/20190722/1503243.html