find the cartesian product of of these sets: [1, 2, 3], ['primary', 'secondary'], ['isbold'] in typescript

To find the cartesian product of the given sets in TypeScript, we can use nested loops or the reduce method to iterate through all the possible combinations of elements from each set.

Here is an example of using nested loops to find the cartesian product of the given sets:

index.ts
const set1 = [1, 2, 3];
const set2 = ['primary', 'secondary'];
const set3 = ['isbold'];

const cartesianProduct: Array<Array<any>> = [];

for (let i = 0; i < set1.length; i++) {
  for (let j = 0; j < set2.length; j++) {
    for (let k = 0; k < set3.length; k++) {
      cartesianProduct.push([set1[i], set2[j], set3[k]]);
    }
  }
}

console.log(cartesianProduct);
// Output: [[1, 'primary', 'isbold'], [1, 'secondary', 'isbold'], [2, 'primary', 'isbold'], [2, 'secondary', 'isbold'], ...]
491 chars
17 lines

We use three nested for loops to iterate through each set element and create an array containing all the combinations. Finally, we push each combination to a new array cartesianProduct.

Alternatively, you can use the reduce method to achieve the same result:

index.ts
const set1 = [1, 2, 3];
const set2 = ['primary', 'secondary'];
const set3 = ['isbold'];

const cartesianProduct = set1.reduce((acc, val1) =>
  acc.concat(set2.reduce((acc, val2) =>
    acc.concat(set3.map((val3) =>
      [val1, val2, val3]
    ))
  , []))
, []);

console.log(cartesianProduct);
// Output: [[1, 'primary', 'isbold'], [1, 'secondary', 'isbold'], [2, 'primary', 'isbold'], [2, 'secondary', 'isbold'], ...]
420 chars
15 lines

Here, we use the reduce method to iterate through each set and create an array containing all the combinations. The first reduce call is used to iterate through set1. For each element in set1, we concat its corresponding elements created by the inner reduce call. The inner reduce call iterates through set2 and returns an array of all combinations with val1. Finally, we map each element in the resulting array of set2 combinations to also include the corresponding val3 from set3.

gistlibby LogSnag