crate combination from the lists in javascript

To generate all combinations of elements present in multiple lists, we can use a recursive approach with backtracking. Here's the code implementation:

index.tsx
function generateCombinations(lists) {
  const combinations = [];

  function backtrack(combination, listIndex) {
    if (combination.length === lists.length) {
      // All lists have been processed
      combinations.push([...combination]);
      return;
    }

    const currentList = lists[listIndex];

    for (let i = 0; i < currentList.length; i++) {
      const element = currentList[i];
      combination.push(element);

      // Generate combinations with next list
      backtrack(combination, listIndex + 1);

      combination.pop(); // backtrack step
    }
  }

  backtrack([], 0); // Start with first list
  
  return combinations;
}

// Example usage
const lists = [['a', 'b'], [1, 2, 3], ['x', 'y']];
const combinations = generateCombinations(lists);
console.log(combinations); // [["a", 1, "x"], ["a", 1, "y"], ["a", 2, "x"], ...]
849 chars
33 lines

The generateCombinations function takes an array of lists as input and returns an array of all possible combinations. It uses the backtrack function to generate combinations recursively. At each level of recursion, the function loops through the elements of the current list and adds them to the combination. It then calls itself with the next list and backtracks by removing the last element added to the combination.

The function maintains an array combinations to store all valid combinations. Once all lists have been processed, a copy of the current combination is added to the combinations array.

This algorithm has a time complexity of O(n^m), where n is the length of the longest list and m is the number of lists.

gistlibby LogSnag