Home > Blockchain >  Generating all combinations of elements from array in array
Generating all combinations of elements from array in array

Time:12-06

i want to generate all the combinations possible by this rule: take one element from every inner array and max combination is 4 element for combination example:

i have array like this one:

[ [ '9', '8' ], [ '7', '10' ], [ 'Q', 'K' ], [ '7', 'K' ] ] 
[
['9','7','Q','7'],
['9','10','K','7'],
['9','7','Q','7'],
]

and so on until all combinations has been generated

tried to use lodash but it didnt go well.

let data = [ [ '9', '8' ], [ '7', '10' ], [ 'Q', 'K' ], [ '7', 'K' ] ];
let combinations = [];

    for (let i = 0; i < data[0].length; i  ) {
        for (let j = i   1; j < data[1].length; j  ) {
            for (let k = j   1; k < data[2].length; k  ) {
                for (let l = j   1; l < data[3].length; l  ) {
                    combinations.push([data[0][i], data[1][j], data[2][k], data[3][l]]);
                }
            }
        }
    }
    console.log(combinations);

CodePudding user response:

You can use a recursive function to generate all the combinations possible by the given rule. Inside the function, you can iterate over each inner array and get the current element. Then, you can add the current element to a temporary array and call the recursive function again with the remaining inner arrays and the updated temporary array. When there are no more inner arrays left, you can add the temporary array to the combinations array.

Here is an example implementation:

const data = [[ '9', '8' ], [ '7', '10' ], [ 'Q', 'K' ], [ '7', 'K' ]];

const combinations = [];

const generateCombinations = (innerArrays, temp) => {
  if (innerArrays.length === 0) {
    combinations.push(temp);
    return;
  }

  const currentArray = innerArrays[0];
  for (let i = 0; i < currentArray.length; i  ) {
    const currentElement = currentArray[i];
    generateCombinations(innerArrays.slice(1), [...temp, currentElement]);
  }
};

generateCombinations(data, []);

console.log(combinations);

The generateCombinations function will be called with the data array and an empty array as the initial arguments. Inside the function, you can check if the length of the innerArrays array is 0, which means that all the combinations have been generated. If that's the case, you can add the temp array to the combinations array and return.

If there are more inner arrays left, you can get the first array from the innerArrays array, which is the current array that you need to generate combinations from. Then, you can iterate over the current array and get the current element. You can add the current element to the temp array and call the generateCombinations function again with the remaining inner arrays (all the inner arrays except the first one) and the updated temp array.

This will generate all the possible combinations using one element from each inner array. The resulting combinations array will look like this:

[  ['9', '7', 'Q', '7'],
  ['9', '7', 'K', '7'],
  ['9', '10', 'Q', '7'],

CodePudding user response:

You can use backtracking, where 'build' your solution, while iterating over all possible viable options. Think of it like a depth first search.

Procedure

  1. Declare output = []
  2. Declare combo = [] <- current solution
  3. Load Inner Array <-
  4. For Each Value,
    1. Add the value to combo
    2. Check if there's a deeper level i.e. Another inner array
      1. If yes, repeat from step 2 on that level with the current combo as the initial combo
      2. If not, we've reached the end, so push combo to output
    3. Pop the value from combo

Brief example with Input: [[9,8],[7]]

Loaded: [9,8]
Combo: []
For each value [9,8]:
       Current Value: 9
       Combo: [9] // Push current value
       Check Next: [7] // Go deeper
            Loaded: [7]
            Combo: [9]
            For each value [7]:
               Current Value: 7
               Combo: [9,7] // Push 7 into combo
               Check Next: null // Cant go deeper
               Output: [[9,7]] // Push current combo
               Combo: [9] // Pop 7 out of combo
        Combo: [] // Pop 9 out of combo
        /* -------- Iterate -------- */
        Current Value: 8
        Combo: [8] // Push 8 into combo
        Check Next: [7] // Go deeper
            Loaded: [7]
            Combo: [8]
            For each value [7]:
               Current Value: 7
               Combo: [8,7] // Push 7 into combo
               Check Next: null // Cant go deeper
               Output: [[9,7],[8,7]] // Push current combo
               Combo: [8] // Pop 7 out of combo
         Combo: [] // Pop 8 out of combo
return Output = [[9,7],[8,7]]

const input = [ [ '9', '8' ], [ '7', '10' ], [ 'Q', 'K' ], [ '7', 'K' ] ] 

function getCombos(array) {
  const output = []
  extend(array);
  return output;
  
  function extend(array, combo = []) {
    const current = array[0]
    for (let i = 0; i < current.length; i  ){
      combo.push(current[i])
      if (array[1]) {
        extend(array.slice(1), combo)
      } else {
        output.push(combo.slice())
      }
      combo.pop();
    }
  }
}

console.log(getCombos(input))

  • Related