获取元素的所有可能组合

sa5*_*555 4 javascript ramda.js

您将如何获得数组中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] 
]
Run Code Online (Sandbox Code Playgroud)

这个答案使用了蛮力,但是Ramda和或curring有功能性的方式吗? 推导数组中元素的所有可能组合

dav*_*ers 7

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

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

用法示例:

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]]
Run Code Online (Sandbox Code Playgroud)

  • 它很优雅,但是由于重复了元素,因此返回的内容与请求的有所不同。这将返回从列表中提取的n个元素序列。正如我所见,它是如此优雅。 (3认同)