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有功能性的方式吗? 推导数组中元素的所有可能组合
这是一个优雅的解决方案:
// 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)
| 归档时间: |
|
| 查看次数: |
782 次 |
| 最近记录: |