0

I want get 3 element mix to string from array any. Example :

var arr = ['a', 'b', 'c'];

result : 
['a', 'a', 'a']
['a', 'a', 'b']
['a', 'a', 'c']
['a', 'b', 'a']
['a', 'b', 'b']
['a', 'b', 'c']
['a', 'c', 'a']
['a', 'c', 'b']
['a', 'c', 'c']

['b', 'a', 'a']
['b', 'a', 'b']
['b', 'a', 'c']
['b', 'b', 'a']
['b', 'b', 'b']
['b', 'b', 'c']
['b', 'c', 'a']
['b', 'c', 'b']
['b', 'c', 'c']

['c', 'a', 'a']
['c', 'a', 'b']
['c', 'a', 'c']
['c', 'b', 'a']
['c', 'b', 'b']
['c', 'b', 'c']
['c', 'c', 'a']
['c', 'c', 'b']
['c', 'c', 'c']

Please help me! I tried many ways still not success. Thanks very much!

toolshot ad
  • 23
  • 1
  • 2

2 Answers2

1

Use 3 nested for loops which will iterate for elements at each position.

var arr = ['a', 'b', 'c'];

for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < arr.length; j++) {
    for (var k = 0; k < arr.length; k++) {
      console.log([arr[i], arr[j], arr[k]])
    }
  }
}

A recursive approach which works for an array of arbitrary length.

var arr = ['a', 'b', 'c'];

function gen(arr, subArr) {
  // iterate over the elements for nth position
  for (var i = 0; i < arr.length; i++) {
    // check currently iterating for the last element
    if (subArr.length == arr.length - 1)
      // concat ith element with the array
      console.log(arr1.concat(arr[i]))
    else
      // otherwise recursively call the function
      gen(arr, subArr.concat(arr[i]))
  }
}

// call the function
gen(arr, []);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

You could use a recursive approach with an exit condition with checking the length of the wanted size.

This function works for an arbitrary length. Be aware, the result has a length of array.lengthsize.

function getCombinations(array, size) {

    function fork(t) {
        var i;

        if (t.length === size) {
            result.push(t);
            return;
        }
        for (i = 0; i < array.length; i++) {
            fork(t.concat([array[i]]));
        }
    }

    var result = [];
    fork([]);
    return result;
}

console.log(getCombinations(['a', 'b', 'c'], 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392