-1

Assume I've got an array:

var arr = [1, 1, 2, 3, 3];

I need to compute all unique possible combinations in order out of this array that use the most numbers possible, provided each is unique. I don't care so much about the values but instead a matrix of indices that match:

[0, 2, 3]
[0, 2, 4]
[1, 2, 3]
[1, 2, 4]

I looked at this answer, however when I do that:

var arr = [1, 1, 2, 3, 3];
console.log(allPossibleCases(arr));

I get:

["1 1 2 3 3"]

Which does make sense according to what that function does, but I've been unable to tweak it enough to suit what I want.

Edit:

Note the part where I said IN ORDER. This is not a complete set of permutations and none of the answers in this question do what I'm asking.

Community
  • 1
  • 1
brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • you just need do a bit preparation for calling `allPossibleCases` - from this `[1, 1, 2, 3, 3]` do array `[[0,1],2,[3,4]]`. You can do this with `Array.reduce` function – Grundy Jul 16 '15 at 19:08
  • No, @Alexander I specifically said IN ORDER. This is not a complete set of permutations. – brandonscript Jul 16 '15 at 19:10
  • @Grundy not sure how `Array.reduce()` translates to that? Can you elaborate? – brandonscript Jul 16 '15 at 19:18
  • sure, something like this `[1, 1, 2, 3, 3].reduce(function(acc,el,index){ var cur = acc.map[el]; if(!cur) { acc.map[el] = cur = []; acc.res.push(cur); } cur.push(index); return acc; },{res:[],map:{}}).res` moved `[1, 1, 2, 3, 3]` to `[[0,1],[2],[3,4]]` – Grundy Jul 16 '15 at 19:24
  • Slick @Grundy! If you want to slap that in as an answer I'll accept it. – brandonscript Jul 16 '15 at 19:27

1 Answers1

1

For using function from this answer you just need a bit prepare your array with Array.reduce something like this

var prepared = [1, 1, 2, 3, 3].reduce(function(acc,el,index){
    var cur = acc.map[el]; 
    if(!cur) { 
        acc.map[el] = cur = []; 
        acc.res.push(cur); 
    } 
    cur.push(index); 
    return acc; 
},{res:[],map:{}}).res;

and prepared looks like [[0,1],[2],[3,4]]

here just group index for duplicated items.

Community
  • 1
  • 1
Grundy
  • 13,356
  • 3
  • 35
  • 55