Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that returns array of array combinations

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?

like image 534
ThomasReggi Avatar asked Jul 11 '15 21:07

ThomasReggi


1 Answers

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
like image 69
Pravin Avatar answered Oct 12 '22 02:10

Pravin