Skip to content

Examples: RankedSet

Kasey O edited this page Oct 12, 2017 · 2 revisions

This page contains several examples showing usage of the RankedSet class. Each example is a complete C# program with output included as comments. For complete documentation on the Kaos.Collections namespace including this class, see:

https://kaosborn.github.io/help/KaosCollections/


The first example of the RankedSet class shows some advanced operations such as comparing sets.

using System;
using System.Collections.Generic;
using Kaos.Collections;

namespace ChartApp
{
    class RsExample01
    {
        static bool IsMononymous (string name) => ! name.Contains (" ");

        static void Main()
        {
            var names1 = new string[] { "Falco", "Nico", "David Bowie", "Tom Petty", "Joni Mitchell", "Warren Zevon" };
            var names2 = new string[] { "Michelangelo", "Rembrandt", "Joni Mitchell", "David Bowie" };

            var musicians = new RankedSet<string> (names1);

            // Remove mononymous items.
            Console.WriteLine ("Remove single names from the set...");
            Console.WriteLine ("  Count before: " + musicians.Count);
            musicians.RemoveWhere (IsMononymous);
            Console.WriteLine ("  Count after: " + musicians.Count + "\n");

            // List names starting with 'J'.
            Console.WriteLine ("Musicians J-T");
            foreach (var name in musicians.ElementsBetween ("J", "U"))
                Console.WriteLine ("  " + name);

            // Create another RankedSet.
            var painters = new RankedSet<string> (names2);

            // Remove elements in musicians that are also in painters.
            Console.WriteLine ("\nRemove duplicates (of painters) from the musicians...");
            Console.WriteLine ("  Count before: " + musicians.Count);
            musicians.ExceptWith (painters);
            Console.WriteLine ("  Count after: " + musicians.Count + "\n");

            Console.WriteLine ("List of musicians that are not painters:");
            foreach (string name in musicians)
                Console.WriteLine ("  " + name);

            var comp = RankedSet<string>.CreateSetComparer();

            HashSet<RankedSet<string>> setOfSets = new HashSet<RankedSet<string>> (comp);
            setOfSets.Add (musicians);
            setOfSets.Add (painters);

            Console.WriteLine ("\nAll sets in hash set:");
            foreach (var set in setOfSets)
            {
                Console.WriteLine ("  " + set.Count + " items:");
                foreach (var item in set)
                    Console.WriteLine ("    " + item);
            }

            // Create a 3rd RankedSet.
            var people = new RankedSet<string> (new string[] { "Tom Petty", "Warren Zevon" });

            // Create a set equality comparer.
            var comparer = RankedSet<string>.CreateSetComparer();

            Console.WriteLine ("\nSet comparison 1: " + comparer.Equals (musicians, people));
            Console.WriteLine ("Set comparison 2: " + comparer.Equals (painters, people));
        }

        /* Output:

        Remove single names from the set...
          Count before: 6
          Count after: 4

        Musicians J-T
          Joni Mitchell
          Tom Petty

        Remove duplicates (of painters) from the musicians...
          Count before: 4
          Count after: 2

        List of musicians that are not painters:
          Tom Petty
          Warren Zevon

        All sets in bag:
          2 items:
            Tom Petty
            Warren Zevon
          4 items:
            David Bowie
            Joni Mitchell
            Michelangelo
            Rembrandt

        Set comparison 1: True
        Set comparison 2: False

        */
    }
}

The next example contrasts the boolean operations of the ISet interface.

using System;
using Kaos.Collections;

namespace ExampleApp
{
    class RsExample03
    {
        static string Text<T> (System.Collections.Generic.IEnumerable<T> arr)
        { return "{ " + String.Join (" ", arr) + " }"; }

        static void Main()
        {
            var set1 = new RankedSet<int>( new int[] { 3, 5, 7 });
            var set2 = new RankedSet<int>( new int[] { 5, 7 });
            var set3 = new RankedSet<int>( new int[] { 1, 9 });
            var set4 = new RankedSet<int> (new int[] { 5, 9 });
            var arg5 = new int[] { 5, 9, 9 };

            bool isSub1 = set2.IsSubsetOf (set1);
            bool isSub2 = set2.IsSubsetOf (set2);
            bool isSub3 = set4.IsSubsetOf (set2);
            bool isSup1 = set1.IsSupersetOf (set2);
            bool isSup2 = set2.IsSupersetOf (set2);
            bool isSup3 = set2.IsSupersetOf (set4);
            bool isPSub1 = set2.IsProperSubsetOf (set1);
            bool isPSub2 = set2.IsProperSubsetOf (set2);
            bool isPSup1 = set1.IsProperSupersetOf (set2);
            bool isPSup2 = set2.IsProperSupersetOf (set2);
            bool isOlap1 = set1.Overlaps (set4);
            bool isOlap2 = set1.Overlaps (set3);
            bool isEq1 = set4.SetEquals (set4);
            bool isEq2 = set4.SetEquals (set3);
            bool isEq3 = set4.SetEquals (arg5);

            Console.WriteLine (Text(set2) + " IsSubsetOf " + Text(set1) + " = " + isSub1);
            Console.WriteLine (Text(set2) + " IsSubsetOf " + Text(set2) + " = " + isSub2);
            Console.WriteLine (Text(set4) + " IsSubsetOf " + Text(set2) + " = " + isSub3);
            Console.WriteLine ();

            Console.WriteLine (Text(set1) + " IsSupersetOf " + Text(set2) + " = " + isSup1);
            Console.WriteLine (Text(set2) + " IsSupersetOf " + Text(set2) + " = " + isSup2);
            Console.WriteLine (Text(set2) + " IsSupersetOf " + Text(set4) + " = " + isSup3);
            Console.WriteLine ();

            Console.WriteLine (Text(set2) + " IsProperSubsetOf " + Text(set1) + " = " + isPSub1);
            Console.WriteLine (Text(set2) + " IsProperSubsetOf " + Text(set2) + " = " + isPSub2);
            Console.WriteLine ();

            Console.WriteLine (Text(set1) + " IsProperSupersetOf " + Text(set2) + " = " + isPSup1);
            Console.WriteLine (Text(set2) + " IsProperSupersetOf " + Text(set2) + " = " + isPSup2);
            Console.WriteLine ();

            Console.WriteLine (Text(set1) + " Overlaps " + Text(set4) + " = " + isOlap1);
            Console.WriteLine (Text(set1) + " Overlaps " + Text(set3) + " = " + isOlap2);
            Console.WriteLine ();

            Console.WriteLine (Text(set4) + " SetEquals " + Text(set4) + " = " + isEq1);
            Console.WriteLine (Text(set4) + " SetEquals " + Text(set3) + " = " + isEq2);
            Console.WriteLine (Text(set4) + " SetEquals " + Text(arg5) + " = " + isEq3);
            Console.WriteLine ();
        }

        /* Output:

        { 5 7 } IsSubsetOf { 3 5 7 } = True
        { 5 7 } IsSubsetOf { 5 7 } = True
        { 5 9 } IsSubsetOf { 5 7 } = False

        { 3 5 7 } IsSupersetOf { 5 7 } = True
        { 5 7 } IsSupersetOf { 5 7 } = True
        { 5 7 } IsSupersetOf { 5 9 } = False

        { 5 7 } IsProperSubsetOf { 3 5 7 } = True
        { 5 7 } IsProperSubsetOf { 5 7 } = False

        { 3 5 7 } IsProperSupersetOf { 5 7 } = True
        { 5 7 } IsProperSupersetOf { 5 7 } = False

        { 3 5 7 } Overlaps { 5 9 } = True
        { 3 5 7 } Overlaps { 1 9 } = False

        { 5 9 } SetEquals { 5 9 } = True
        { 5 9 } SetEquals { 1 9 } = False
        { 5 9 } SetEquals { 5 9 9 } = True

        */
    }
}

The next example shows more ISet examples. This time the mutator methods are contrasted.

using System;
using Kaos.Collections;

namespace ExampleApp
{
    class RsExample04
    {
        static string Text<T> (System.Collections.Generic.IEnumerable<T> data)
        { return "{ " + String.Join (" ", data) + " }"; }

        static void Main()
        {
            var set = new RankedSet<int>(new int[] { 3, 5, 7 });
            var arg = new int[] { 5, 7, 9 };

            var ew = new RankedSet<int> (set);
            var iw = new RankedSet<int> (set);
            var se = new RankedSet<int> (set);
            var uw = new RankedSet<int> (set);

            ew.ExceptWith (arg);
            iw.IntersectWith (arg);
            se.SymmetricExceptWith (arg);
            uw.UnionWith (arg);

            Console.WriteLine (Text(set) + " ExceptWith " + Text(arg) + " = " + Text(ew));
            Console.WriteLine (Text(set) + " IntersectWith " + Text(arg) + " = " + Text(iw));
            Console.WriteLine (Text(set) + " SymmetricExceptWith " + Text(arg) + " = " + Text(se));
            Console.WriteLine (Text(set) + " UnionWith " + Text(arg) + " = " + Text(uw));
        }

        /* Output:

        { 3 5 7 } ExceptWith { 5 7 9 } = { 3 }
        { 3 5 7 } IntersectWith { 5 7 9 } = { 5 7 }
        { 3 5 7 } SymmetricExceptWith { 5 7 9 } = { 3 9 }
        { 3 5 7 } UnionWith { 5 7 9 } = { 3 5 7 9 }

        */
    }
}

The next example shows using a BinaryFormatter to serialize a set to a file stream and read it back.

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Kaos.Collections;

namespace ExampleApp
{
    [Serializable]
    public class PersonComparer : Comparer<Person>
    {
        public override int Compare (Person x, Person y)
        { return x==null? (y==null? 0 : -1) : (y==null? 1 : String.Compare (x.ToString(), y.ToString())); }
    }

    [Serializable]
    public class Person : ISerializable
    {
        public string First { get; private set; }
        public string Last { get; private set; }

        public Person (string first, string last)
        { this.First = first; this.Last = last; }

        protected Person (SerializationInfo info, StreamingContext context)
        {
            this.First = (String) info.GetValue ("First", typeof (String));
            this.Last = (String) info.GetValue ("Last", typeof (String));
        }

        public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
        {
            info.AddValue ("First", First, typeof (String));
            info.AddValue ("Last", Last, typeof (String));
        }

        public override string ToString() => Last + ", " + First;
    }


    class RsExample05
    {
        static void Main()
        {
            var set1 = new RankedSet<Person> (new PersonComparer());
            set1.Add (new Person ("Hugh", "Mann"));
            set1.Add (new Person ("Hammond", "Egger"));

            string fileName = "Persons.bin";
            IFormatter formatter = new BinaryFormatter();

            SerializePersons (fileName, set1, formatter);
            Console.WriteLine ("Wrote " + set1.Count + " items to file '" + fileName + "'.");
            Console.WriteLine ();

            RankedSet<Person> set2 = DeserializePersons (fileName, formatter);
            Console.WriteLine ("Read back " + set2.Count + " items:");

            foreach (var p2 in set2)
                Console.WriteLine (p2);
        }

        public static void SerializePersons (string fn, RankedSet<Person> set, IFormatter formatter)
        {
            using (var fs = new FileStream (fn, FileMode.Create))
            { formatter.Serialize (fs, set); }
        }

        static RankedSet<Person> DeserializePersons (string fn, IFormatter formatter)
        {
            using (var fs = new FileStream (fn, FileMode.Open))
            { return (RankedSet<Person>) formatter.Deserialize (fs); }
        }

        /* Output:

        Wrote 2 items to file 'Persons.bin'.

        Read back 2 items:
        Egger, Hammond
        Mann, Hugh

        */
    }
}
Clone this wiki locally