1

Can anyone suggest an easy way of getting all combinations without repeats, and with a varying length ?

[0,1,2,3,4]

(2's) : [0,1],[0,2],[0,3] ... [3,4]

(3's) : [0,1,2],[0,1,3] ... [2,3,4]

(4's) : [0,1,2,3],[0,1,2,4] ... [1,2,3,4]

Daniel
  • 34,125
  • 17
  • 102
  • 150
  • Sounds very similar to http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n – RandomEtc Jan 02 '11 at 06:10
  • I just found the function/routine to solve the problem, the problem is similar, and looks like Adam Hughes' solution is pretty similar. to fit that problem, `if (a.length > 1)` should be changed to == 3(or whatever the desired length. – Daniel Jan 02 '11 at 06:25

1 Answers1

2

took me a while but I think I've got it here...

this has all the combinations without repeats

var arr:Array = [0, 1, 2, 3, 4];
var $allcombos:Array = [];
findCombos($allcombos,[],arr);

function findCombos($root:Array, $base:Array, $rem:Array):void {
    for (var i:int = 0; i < $rem.length; i++) {
        var a:Array = $base.concat();
        a.push($rem[i]);
        findCombos($root, a, $rem.slice(i + 1));
        if (a.length > 1) {
            $root.push(a);
        }
    }
}
Daniel
  • 34,125
  • 17
  • 102
  • 150