Open In App

Cartesian Product of any number of sets

Improve
Improve
Like Article
Like
Save
Share
Report

Given N number of sets. The task is to write a program to perform a cartesian product of all the sets in a given order.
Example

Input:
1st set: 1 2
2nd set: A
3rd set: x
4th set: 5 6
Output:
[['1', 'A', 'x', '5'],
['1', 'A', 'x', '6'],
['2', 'A', 'x', '5'],
['2', 'A', 'x', '6']]

Input:
1st set: 1 2
2nd set: A
3rd set: x y z
Output:
[['1', 'A', 'x'],
['1', 'A', 'y'],
['1', 'A', 'z'],
['2', 'A', 'x'],
['2', 'A', 'y'],
['2', 'A', 'z']]

Approach: The approach is to compute the product of set-1 and set-2 at the beginning and then the resultant of set-1 and set-2 will have a product with set-3 and then the resultant of set-1, set-2, and set-3 will have a Cartesian product with set-4 and so on till set-n.
Below is the implementation of the above approach. 
 

C++




#include <iostream>
#include <vector>
#include <string>
 
using namespace std;
 
// Function to find cartesian product of two sets
vector<vector<string>> cartesianProduct(vector<vector<string>>& setA, vector<string>& setB) {
    vector<vector<string>> result;
    for (const vector<string>& a : setA) {
        for (const string& b : setB) {
            vector<string> temp = a;
            temp.push_back(b);
            result.push_back(temp);
        }
    }
    return result;
}
 
// Function to do cartesian product of N sets
void cartesian(vector<vector<string>>& sets) {
    vector<vector<string>> temp(1, vector<string>());
    for (int i = 0; i < sets.size(); i++) {
        vector<vector<string>> newTemp;
        for (const vector<string>& product : temp) {
            for (const string& element : sets[i]) {
                vector<string> tempCopy = product;
                tempCopy.push_back(element);
                newTemp.push_back(tempCopy);
            }
        }
        temp = newTemp;
    }
    for (const vector<string>& product : temp) {
        for (const string& element : product) {
            cout << element << " ";
        }
        cout << endl;
    }
}
 
int main() {
    vector<vector<string>> sets = {{"1", "2"}, {"A"}, {"x", "y", "z"}};
    cartesian(sets);
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
 
    // Function to find cartesian product of two sets
    static List<List<String>> cartesianProduct(List<List<String>> setA, List<String> setB) {
        List<List<String>> result = new ArrayList<>();
        for (List<String> a : setA) {
            for (String b : setB) {
                List<String> temp = new ArrayList<>(a);
                temp.add(b);
                result.add(temp);
            }
        }
        return result;
    }
 
    // Function to do cartesian product of N sets
    static void cartesian(List<List<String>> sets) {
        List<List<String>> temp = new ArrayList<>();
        for (String element : sets.get(0)) {
            List<String> list = new ArrayList<>();
            list.add(element);
            temp.add(list);
        }
        for (int i = 1; i < sets.size(); i++) {
            temp = cartesianProduct(temp, sets.get(i));
        }
        for (List<String> product : temp) {
            for (String element : product) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
 
    public static void main(String[] args) {
        List<List<String>> sets = new ArrayList<>();
        sets.add(List.of("1", "2"));
        sets.add(List.of("A"));
        sets.add(List.of("x", "y", "z"));
        cartesian(sets);
    }
}


Python3




# Python program for cartesian
# product of N-sets
 
# function to find cartesian product of two sets
def cartesianProduct(set_a, set_b):
    result =[]
    for i in range(0, len(set_a)):
        for j in range(0, len(set_b)):
 
            # for handling case having cartesian
            # product first time of two sets
            if type(set_a[i]) != list:        
                set_a[i] = [set_a[i]]
                 
            # copying all the members
            # of set_a to temp
            temp = [num for num in set_a[i]]
             
            # add member of set_b to
            # temp to have cartesian product    
            temp.append(set_b[j])            
            result.append(temp) 
             
    return result
 
# Function to do a cartesian
# product of N sets
def Cartesian(list_a, n):
     
    # result of cartesian product
    # of all the sets taken two at a time
    temp = list_a[0]
     
    # do product of N sets
    for i in range(1, n):
        temp = cartesianProduct(temp, list_a[i])
         
    print(temp)
 
# Driver Code
list_a = [[1, 2],          # set-1
          ['A'],          # set-2
          ['x', 'y', 'z']]   # set-3
           
# number of sets
n = len(list_a)
 
# Function is called to perform
# the cartesian product on list_a of size n
Cartesian(list_a, n)


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find cartesian product of two sets
    static List<List<string>> CartesianProduct(List<List<string>> setA, List<string> setB)
    {
        List<List<string>> result = new List<List<string>>();
        foreach (List<string> a in setA)
        {
            foreach (string b in setB)
            {
                List<string> temp = new List<string>(a);
                temp.Add(b);
                result.Add(temp);
            }
        }
        return result;
    }
 
    // Function to do cartesian product of N sets
    static void Cartesian(List<List<string>> sets)
    {
        List<List<string>> temp = new List<List<string>> { new List<string>() };
        for (int i = 0; i < sets.Count; i++)
        {
            List<List<string>> newTemp = new List<List<string>>();
            foreach (List<string> product in temp)
            {
                foreach (string element in sets[i])
                {
                    List<string> tempCopy = new List<string>(product);
                    tempCopy.Add(element);
                    newTemp.Add(tempCopy);
                }
            }
            temp = newTemp;
        }
        foreach (List<string> product in temp)
        {
            Console.WriteLine(string.Join(" ", product));
        }
    }
 
    static void Main(string[] args)
    {
        List<List<string>> sets = new List<List<string>>
        {
            new List<string> { "1", "2" },
            new List<string> { "A" },
            new List<string> { "x", "y", "z" }
        };
        Cartesian(sets);
    }
}


Javascript




// Function to find cartesian product of two sets
function cartesianProduct(setA, setB) {
    const result = [];
    for (const a of setA) {
        for (const b of setB) {
            const temp = [...a];
            temp.push(b);
            result.push(temp);
        }
    }
    return result;
}
 
// Function to do cartesian product of N sets
function cartesian(sets) {
    let temp = sets[0];
    for (let i = 1; i < sets.length; i++) {
        temp = cartesianProduct(temp, sets[i]);
    }
    for (const product of temp) {
        console.log(product.join(" "));
    }
}
 
const sets = [
    ["1", "2"],
    ["A"],
    ["x", "y", "z"]
];
 
cartesian(sets);


Output

[[1, 'A', 'x'],
 [1, 'A', 'y'],
 [1, 'A', 'z'], 
 [2, 'A', 'x'], 
 [2, 'A', 'y'], 
 [2, 'A', 'z']]

Time Complexity: O(n3)
Auxiliary Space: O(n*m), Here n is the number of sets and m is the maximum element in a set. The extra space is used to store the result.



Last Updated : 08 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads