Skip to main content

Cartesian Product

Definition​

The Cartesian Product Algorithm is a computational method used to find the Cartesian product of two or more sets. It generates all possible combinations of elements from these sets, creating a new set of tuples

Practice​

cartesianProduct(sets):
// Initialize an empty list to store the Cartesian product
cartesianSet = []

// Initialize a list to keep track of the current index of each set
currentIndex = [0] * length(sets)

// Start with the first element of the first set
generateCartesianProduct(sets, cartesianSet, currentIndex, 0)

return cartesianSet

generateCartesianProduct(sets, cartesianSet, currentIndex, setIndex):
// Base case: if all sets have been traversed, add the current combination to the Cartesian product
if setIndex == length(sets):
cartesianSet.append(getCurrentCombination(sets, currentIndex))
return

// Iterate over each element in the current set
for i from 0 to length(sets[setIndex]) - 1:
// Update the current index for the current set
currentIndex[setIndex] = i

// Recursively generate combinations for the next set
generateCartesianProduct(sets, cartesianSet, currentIndex, setIndex + 1)

getCurrentCombination(sets, currentIndex):
// Initialize an empty list to store the current combination
combination = []

// Iterate over each set and append the element at the current index to the combination
for i from 0 to length(sets) - 1:
combination.append(sets[i][currentIndex[i]])

return combination