Set Theory: Union

03 Mar 2014

C#, Maths, Python


In set theory, the union operation is a enumerative combinatorial function that combines distinct elements found in any of the given sets.

The ∪ symbol denotes a union, we write the expression as:

X ∪ Y

For example:

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

X ∪ Y = { 1, 2, 3, 4, 5, 6 }
Keep in mind that a union is a distinct operation:
X = { 1, 2, 3 }
Y = { 2, 2, 4 }

X ∪ Y = { 1, 2, 3, 4 }

Note that even though 2 appears 3 times, and appears in both lists, it is only included once in the output.

Here's a union extension method in C# you can use to add set unions to your code:

/// /// Generates an array where the values contained in the X array are unioned with the values contained in Y array /// /// An array of integers /// An array of integers /// Returns a distinct, sorted, unioned array public static int[] Union(this int[] X, int[] Y) { List oUnion = new List(X); oUnion.AddRange(Y); return oUnion.Distinct().OrderBy(m => (m)).ToArray(); }

Here's similar code 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 Union(self, X, Y):
        iUnion = []

        X = self.Distinct(X);
        Y = self.Distinct(Y);

        for i in range(len(X)):
            iUnion.append(X[i])

        for i in range(len(Y)):
            iUnion.append(Y[i])

        iUnion = self.Distinct(iUnion)

        return iUnion

 


 

Copyright © 2024 carlbelle.com