Skip to content

Instantly share code, notes, and snippets.

@gspalato
Last active February 12, 2020 20:07
Show Gist options
  • Save gspalato/9a016d5f6ad1857851dda562c88cfc5a to your computer and use it in GitHub Desktop.
Save gspalato/9a016d5f6ad1857851dda562c88cfc5a to your computer and use it in GitHub Desktop.
Unefficient and incomplete mathematical set implementation in C#.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Arpa.Structures
{
public class Set<T> : IEnumerable<T>
{
public T[] array = new T[] { };
public Set(T[] array)
{
this.array = array;
}
public int n
{
get
{
return array.Length;
}
}
public bool Contains(T value) => this.array.Contains(value); // Contains
public bool Contains(Set<T> set) => (set % this) == set;
public static Set<T> operator +(Set<T> first, Set<T> second) // Union
{
T[] newSetArray = first.array.Union(second.array).ToArray();
return new Set<T>(newSetArray);
}
public static Set<T> operator -(Set<T> first, Set<T> second) // Difference
{
List<T> firstList = new List<T>(first.array);
List<T> secondList = new List<T>(second.array);
T[] subtractedArray = firstList.Except(secondList).ToArray();
return new Set<T>(subtractedArray);
}
public static Set<T> operator %(Set<T> first, Set<T> second) // Intersection
{
List<T> firstList = new List<T>(first.array);
List<T> secondList = new List<T>(second.array);
T[] intersectedArray = firstList.Intersect(secondList).ToArray();
return new Set<T>(intersectedArray);
}
public static bool Equals(Set<T> first, Set<T> second) // Equality
=> first.array == second.array;
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)array).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)array).GetEnumerator();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment