Skip to content Skip to sidebar Skip to footer

Derive Every Possible Combination Of Elements In Array

Given an array and a length, I want to derive every possible combination of elements (non-repeating) at the specific length. So given an array of: arr = ['a','b','c','d'] and a le

Solution 1:

The following code uses a brute-force approach. It generates every permutation of every combination of the desired length. Permutations are checked against a dictionary to avoid repeating them in the result.

function makePermutations(data, length) {
  var current = new Array(length), used = new Array(length),
      seen = {}, result = [];
  function permute(pos) {
    if (pos == length) {      // Do we have a complete combination?
      if (!seen[current]) {   // Check whether we've seen it before.
        seen[current] = true; // If not, save it.
        result.push(current.slice());
      }
      return;
    }
    for (var i = 0; i < data.length; ++i) {
      if (!used[i]) {         // Have we used this element before?
        used[i] = true;       // If not, insert it and recurse.
        current[pos] = data[i];
        permute(pos+1);
        used[i] = false;      // Reset after the recursive call.
      }
    }
  }
  permute(0);
  return result;
}

var permutations = makePermutations(['a', 'a', 'b', 'b'], 3);
for (var i = 0; i < permutations.length; ++i) {
  document.write('['+permutations[i].join(', ')+']<br />');
}

Post a Comment for "Derive Every Possible Combination Of Elements In Array"