Computing the Cartesian Product of Two Sets in JavaScript


Cartesian Product 

Inset theory a Cartesian product is a mathematical operation that returns a set (or product set or simply product) from multiple sets.

That is, for sets A and B, the Cartesian product A × B is the set of all ordered pairs (a, b) where a ∈ A and b ∈ B.

We are required to write a JavaScript function that takes in two arrays let us call them arr1 and arr2, they both represent two distinct sets.

The function should construct a 2-D array that contains the cartesian product of those two sets and finally return that array.

Example

Following is the code −

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
const cartesianProduct = (arr1 = [], arr2 = []) => {
   if (!arr1 || !arr2 || !arr1.length || !arr2.length) {
      return null;
   };
   const res = [];
   for (let i = 0; i < arr1.length; i += 1) {
      for (let j = 0; j < arr2.length; j += 1) {
         res.push([arr1[i], arr2[j]]);
      };
   };
   return res;
};
console.log(cartesianProduct(arr1, arr2));

Output

Following is the output on console −

[
   [ 1, 5 ], [ 1, 6 ],
   [ 1, 7 ], [ 1, 8 ],
   [ 2, 5 ], [ 2, 6 ],
   [ 2, 7 ], [ 2, 8 ],
   [ 3, 5 ], [ 3, 6 ],
   [ 3, 7 ], [ 3, 8 ],
   [ 4, 5 ], [ 4, 6 ],
   [ 4, 7 ], [ 4, 8 ]
]

Updated on: 31-Mar-2023

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements