Problem Solving: Cross Product of Sets

Learn to create a program that computes the cross-product of sets.

We'll cover the following

In this lesson, we’ll compute the cross product of two sets where the cross product of A and B is the set of all the possible ordered pairsThe combination of elements where the position of each element matters and switching their positions would result in a different ordered pair. of the elements from both sets. For example, if A = {1, 4, 7} and B = {5, 8}, then A x B = {(1,5), (1,8), (4,5), (4,8), (7,5), (7,8)}.

Instruction: Use the following playground to write the complete code for the task in this lesson.

We have already added code for loading, sorting, and displaying sets, so you do not need to include that.

Press + to interact
main.cpp
Sets.txt
/* The code for loading, sorting, and displaying sets has already
been implemented, so we can now concentrate solely on calculating
the cross product.*/
{
/*
Variables A, sizeA, B, sizeB have been declared
sets are available, and both are sorted now.
*/
// Task 1: AXB
cout << "\nA x B: = {\n";
// Write code for AXB
cout << "\n\t\t}";
// Task 1: BXA
cout << "\nB x A: = {\n";
// Write code for BXA
cout << "\n\t\t}";
}

Cross product

Task: Print the cross product of sets A and B on the console.

Your program should print the following:

A = {2, 3, 4, 5, 10}
B = {2, 3, 4, 7, 8, 10}
A x B: = {
             (2, 2), (2, 3), (2, 4), (2, 7), (2, 8), (2, 10), 
             (3, 2), (3, 3), (3, 4), (3, 7), (3, 8), (3, 10), 
             (4, 2), (4, 3), (4, 4), (4, 7), (4, 8), (4, 10), 
             (5, 2), (5, 3), (5, 4), (5, 7), (5, 8), (5, 10), 
             (10, 2), (10, 3), (10, 4), (10, 7), (10, 8), (10, 10)

          }

The idea is the following:

  • Print each element of set A with all the elements of set B.

Let’s write down the code:

Press + to interact
cout << "\nA x B: = {\n";
for (int ai = 0; ai <= sizeA-1; ai++)
{
cout << "\t\t\t";
for (int bi = 0; bi <= sizeB - 1; bi++)
{
cout << "(" << A[ai] << ", " << B[bi] << ")";
// This check will not print comma after last pair
if (bi != (sizeB - 1) || ai != (sizeA - 1))
cout << ", ";
}
cout << endl;
}
  • Lines 1–14: We use the nested loop to print the result of sets A and B on a console. The nested loop will print each element of set A with all the elements of set B.
  • Line 10: We include a condition under which the comma after the last pair of the cross product will not be printed.

Instruction: Add the above computing cross product code in the playground to complete the entire lesson.

Exercise: B x A

Write the code in the above playground for BxA. The output should be the following.

A = {2, 3, 4, 5, 10}
B = {2, 3, 4}
B x A: = {
             (2, 2), (2, 3), (2, 4), (2, 5), (2, 10), 
             (3, 2), (3, 3), (3, 4), (3, 3), (3, 10), 
             (4, 2), (4, 3), (4, 4), (4, 5), (4, 10)

          }