1

The following is a function for calculating all the possible combinations of a given array:

function combinations(arr, k) {
   var i, subI, sub, combinationsArray = [], next;
   for (i = 0; i < arr.length; i++) {
       if (k === 1) {
           combinationsArray.push([arr[i]]);
       } else {
           sub = combinations(arr.slice(i + 1, arr.length), k - 1);
           for (subI = 0; subI < sub.length; subI++) {
               next = sub[subI];
               next.unshift(arr[i]);
               combinationsArray.push(next);
           }
       }
   }
   return combinationsArray;
};

For example:

 combinations([1,2,3],2);

returns:

[[1,2],[1,3],[2,3]]

I have a nested for loop which modifies a copy of an array of 12 objects (splicing certain elements,depending on the iteration of the loop), before using it as a parameter to the combinations function and storing certain elements of the array returned.

var resultArray = [];
var paramArray = [obj1,obj2,obj3,obj4,obj5,obj6,obj7,obj8,obj9,obj10,obj11,obj12];
for(i=0;i<length1;i++){
  for(n=0;n<length2;n++){
    paramArray.splice(...);//modifying array
    resultArray[n] = combinations(paramArray,2)[i].slice();//storing an element, there are multiples of each element in the resultArray obviously
  }
}

The browser crashes with the above type of code (firefox returns the messege: "A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.") The breakpoint is always the part where the combinations function thats being called.

Because the array parameter is different in each iteration, I cant assign the combinations function call to a variable to optimize the code. Is there a more efficient way of writing this?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
  • See [http://stackoverflow.com/questions/2196654/running-a-long-operation-in-javascript][1] [1]: http://stackoverflow.com/questions/2196654/running-a-long-operation-in-javascript – James Sumners Jun 27 '12 at 15:26
  • I think the only way to make this truly better would be to find an algorithm to compute just the combination you need. You've got a big-O involving a significantly large exponent (4 I think), so that's always going to cause problems no matter how clever the code is. – Pointy Jun 27 '12 at 15:51
  • 1
    The browser doesn't crash; it merely thinks your script is taking too long. Try using a [web worker](https://developer.mozilla.org/Using_DOM_workers) for this. – Martijn Jul 03 '12 at 03:30

0 Answers0