Nodejs Array Combination combinationsOf(k)

Here you can find the source of combinationsOf(k)

Method Source Code

Array.prototype.combinationsOf = function(k) {
   var result = [];
   //from w w w  . ja  v a 2s.  co  m
   if (k < 1) return result;
   if (k > this.length) return result;
   if (k == this.length) return this.slice(0);
   
   var indices = new Array(k), n = this.length;
   var total = n.factorial() / ((n - k).factorial() * k.factorial());
   
   // initialize the indices array
   indices.length.times(function(i) { indices[i] = i });
   
   // do the easy case first
   result.push(this.valuesAt(indices));
   total--;
   
   var ary = this;
   total.times(function() {
      var i = k - 1;
      while (indices[i] == n - k + i) i--;
      indices[i] += 1;
      for (var j = i + 1; j < k; j++) { indices[j] = indices[i] + j - i }

      result.push(ary.valuesAt(indices));
   });
   
   return result;
}

Related

  1. combinations()
    Array.prototype.combinations = function() {
      var array = this;
      var result = [];
      for(var i = 0; i < array.length; i++) {
        for (var j = i+1; j < array.length; j++) {
          if (i != j) {
            result.push( [array[i],array[j]] );
      return result;