find the cartesian product of multiple sets in typescript

To find the cartesian product of multiple sets in TypeScript, we can use nested loops over arrays. The approach is to iterate over each element of the first set, and for each element, iterate over each element of the second set and so on, until we have iterated over all sets.

Here's an example implementation of finding the cartesian product of three sets:

index.ts
function cartesianProduct<T>(...sets: T[][]): T[][] {
  if (sets.length < 2) {
    throw new Error('At least two sets are required');
  }

  const result = sets[0].map(value => [value]);

  for (let i = 1; i < sets.length; i++) {
    const temp = [];
    for (let j = 0; j < result.length; j++) {
      for (let k = 0; k < sets[i].length; k++) {
        temp.push([...result[j], sets[i][k]]);
      }
    }
    result.splice(0, result.length, ...temp);
  }

  return result;
}

// Example usage
const set1 = [1, 2];
const set2 = ['a', 'b', 'c'];
const set3 = [true, false];

const result = cartesianProduct(set1, set2, set3);
console.log(result); // Output: [[1, 'a', true], [1, 'a', false], [1, 'b', true], [1, 'b', false], [1, 'c', true], [1, 'c', false], [2, 'a', true], [2, 'a', false], [2, 'b', true], [2, 'b', false], [2, 'c', true], [2, 'c', false]]
857 chars
28 lines

In this implementation, we take variable number of arrays as input to the function. First, we check if the number of arrays is atleast 2, otherwise we return an error. We start by initializing the result with the first array. We then loop over the other arrays, and on each iteration, we create a new temporary array and loop over the current result and current array, and push a new array by concatenating the current result and current value from the array. Finally, we set the result array to the temporary array at the end of the loop.

The output is an array of arrays representing the cartesian product of all the input sets.

gistlibby LogSnag