In set theory, the intersect operation determines which elements from a set intersect with elements from any given sets.

The ∩ symbol denotes an intersect, we write the expression as:

X ∩ Y

For example:

X = { 1, 2, 3, 4 } Y = { 3, 4, 5, 6 } X ∩ Y = { 3, 4 }

By lining up the individual elements in the above example against a union of the sets, it can be easier to visualise what an intersection is:

X = { 1, 2, 3, 4 } Y = { 3, 4, 5, 6 } X ∪ Y => { 1, 2, 3, 4, 5, 6} X = { 1, 2, 3, 4 } Y = { 3, 4, 5, 6 } X ∩ Y = { 3, 4 }

Intersections are elements shared by either set, indices where the sets join, meet, or intersect.

Here's an intersect extension method in C# you can use to add set intersects to your code:

/// <summary> /// Generates an array of the valus contained in both X and Y /// </summary> /// <param name="X">An array of integers</param> /// <param name="Y">An array of integers</param> /// <returns>Returns a distinct, sorted intersected array</returns> public static int[] Intersect(this int[] X, int[] Y) { return new List<int>(X.Where(m => (Y.Contains(m)))).Distinct<int>().OrderBy(m => (m)).ToArray<int>(); }

LINQ makes this type of operation very trivial, in fact, we can return our result using only one line of code.

Here's the code rewritten in Python:

class SetTheory(object): def Distinct(self, Values): iDistinct = [] for i in range(len(Values)): iValue = Values[i] bIsValueFound = False for j in range(len(iDistinct)): if (iDistinct[j] == iValue): bIsValueFound = True break if (bIsValueFound == False): iDistinct.append(iValue) return iDistinct def Intersect(self, X, Y): iIntersect = [] X = self.Distinct(X) Y = self.Distinct(Y) for i in range(len(X)): iValue = X[i] for j in range(len(Y)): if (Y[j] == iValue): iIntersect.append(iValue) break return iIntersect

Copyright © 2019 carlbelle.com