Function that returns array of array combinations

核能气质少年 提交于 2019-12-09 17:12:24

问题


I'm trying to make a _.combinations function (underscore mixin) that takes three parameters arr, pockets, duplicates. Here's a test that I designed to show how the behavior should be.

expect(_.combinations([1, 2], 1, false)).to.be.equal([[1],[2]])
expect(_.combinations([1, 2], 1, true)).to.be.equal([[1],[2]])
expect(_.combinations([1, 2, 3], 2, false)).to.be.equal([[1,2],[1,3],[2,3]])
expect(_.combinations([1, 2, 3], 2, true)).to.be.equal([[1,2],[1,3],[2,3],[2,1],[3,1],[3,2]])
expect(_.combinations([1, 2, 3, 4], 3, false)).to.be.equal([[1,2,3],[1,2,4],[1,3,4],[2,1,4],[2,3,4],[3,4,1]])
expect(_.combinations([1, 2, 3, 4], 3, true)).to.be.equal([[1,2,3],[1,2,4],[1,3,4],[2,1,4],[2,3,1],[2,3,4],[3,1,2],[3,4,1],[3,4,2],[4,1,2],[4,1,3],[4,2,3]])

I was wondering before I go and create this function if it existed within a library already. Perhaps this specific function already has a name that I'm not familiar with.

Is there something out there that does this?


回答1:


This library has good function. I think its pretty much got what you need.

var combinatorics=require('/path/to/combinatorics');

var a = [1,2,3];

var ans1=combinatorics.permutation(a,2); 
console.log(ans1.toArray());// [[1,2],[2,1],[1,3],[3,1],[2,3],[3,2]] like when duplicates is set to true


var ans2=combinatorics.combination(a,2); 
console.log(ans2.toArray());//[[1,2],[2,1],[1,3],[3,1],[2,3],[3,2]] like when duplicates is set to false


来源:https://stackoverflow.com/questions/31362207/function-that-returns-array-of-array-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!