![]() |
VOOZH | about |
Let A and B be two sets, Cartesian productA × B is the set of all ordered pair of elements from A and B
A × B = {{x, y} : x ? A, y ? B}
Let A = {a, b, c} and B = {d, e, f}
The Cartesian product of two sets is
A x B = {a, d}, {a, e}, {a, f}, {b, d}, {b, e}, {b, f}, {c, d}, {c, e}, {c, f}}
A has 3 elements and B also has 3 elements. The Cartesian Product has 3 x 3 = 9 elements.
In general, if there are m elements in set A and n elements in B, the number of elements in the Cartesian Product is m x n
Given two finite non-empty sets, write a program to print Cartesian Product.
Examples :
Input : A = {1, 2}, B = {3, 4}
Output : A × B = {{1, 3}, {1, 4}, {2, 3}, {2, 4}}Input : A = {1, 2, 3} B = {4, 5, 6}
Output : A × B = {{1, 4}, {1, 5}, {1, 6}, {2, 4},
{2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}}
{1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}, Time complexity: O(M*N) where M and N are size of given sets
Auxiliary space: O(1) because it is using constant space for variables
Practical Examples:
1) A set of playing cards is Cartesian product of a four element set to a set of 13 elements.
2) A two dimensional coordinate system is a Cartesian product of two sets of real numbers.
Reference:
https://en.wikipedia.org/wiki/Cartesian_product