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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With