/// <summary> /// Computes the intersection of this bag with another bag. The intersection of two bags /// is all items that appear in both of the bags. If an item appears X times in one bag, /// and Y times in the other bag, the intersection contains the item Minimum(X,Y) times. A new bag is /// created with the intersection of the bags and is returned. This bag and the other bag /// are unchanged. /// </summary> /// <remarks> /// <para>When equal items appear in both bags, the intersection will include an arbitrary choice of one of the /// two equal items.</para> /// <para>The intersection of two bags is computed in time O(N), where N is the size of the smaller bag.</para> /// </remarks> /// <param name="otherBag">Bag to intersection with.</param> /// <returns>The intersection of the two bags.</returns> /// <exception cref="InvalidOperationException">This bag and <paramref name="otherBag"/> don't use the same method for comparing items.</exception> public Bag <T> Intersection(Bag <T> otherBag) { CheckConsistentComparison(otherBag); Bag <T> smaller, larger, result; if (otherBag.Count > this.Count) { smaller = this; larger = otherBag; } else { smaller = otherBag; larger = this; } int copiesInSmaller, copiesInLarger, copies; // Enumerate each of the items in the smaller bag. Add items that need to be // added to the intersection. result = new Bag <T>(keyEqualityComparer); foreach (T item in smaller.DistinctItems()) { copiesInLarger = larger.NumberOfCopies(item); copiesInSmaller = smaller.NumberOfCopies(item); copies = System.Math.Min(copiesInLarger, copiesInSmaller); if (copies > 0) { result.ChangeNumberOfCopies(item, copies); } } return(result); }