Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

bagIntersection: The intersection of two bags is a new bag containing the entrie

ID: 3872358 • Letter: B

Question

bagIntersection: The intersection of two bags is a new bag containing the entries that occur in both of the original bags. Design and specify a method intersection for the ArrayBag that returns as a new bag the intersection of the bag receiving the call to the method and the bag that is the method's parameter. The method signature is:

ArrayBag bagIntersection(const ArrayBag &otherBag) const;

Note that the intersection of two bags might contain duplicate items. For example, if object x occurs five times in one bag and twice in another, the intersection of these bags contains x two times. The intersection does not affect the contents of the original bags.

Example run: https://i.imgur.com/2fDipPM.png

Explanation / Answer

Given below is the code that finds the intersection of the 2 bags. Since the defintion of the ArragBag class is not given, I have made the following assumptions

Assumptions about ArrayBag

1. Looking at hte output screen you have given, I guess the ArrayBag should support multiple data types and hence is templated class. Its a template with ItemType template parameter.

2. The following functions exist in the class - contains(), getFrequencyOf(), getCurrentSize().

3. The name of array holding the data is items[]

template<class ItemType>
ArrayBag<ItemType> ArrayBag<ItemType>::bagIntersection(const ArrayBag<ItemType> &otherBag) const
{
ArrayBag<ItemType> result;
int count1, count2, lowest;
for(int i = 0; i < getCurrentSize(); i++)
{
if(otherBag.contains(items[i]) && !result.contains(items[i])) //if the intersection item is not in result
{
count1 = getFrequencyOf(items[i]); //get the items frequency in this bag
count2 = otherBag.getFrequencyOf(items[i]); //get the item's frequency in otherBag
if(count1 < count2) //we need to find the lowest of the 2 occurences
lowest = count1;
else
lowest = count2;

for(int j = 0; j < lowest; j++) //add as many occurences as needed
result.add(items[i]);
  
}
}
return result;
}

In case of any issues with the code, please let me know through comments, I will help. But I will need the structure of your existing class so that I can use the correct member varialbe/ function names. If the answer helped, please do rate it. Thank you.