Skip to content

Examples: RankedBag

Kasey O edited this page Oct 12, 2017 · 1 revision

This page contains several examples showing usage of the RankedBag 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 RankedBag class shows some basic operations.

using System;
using Kaos.Collections;

namespace ExampleApps
{
    class RbExample01
    {
        static void Main()
        {
            var crayons = new RankedBag<string> (StringComparer.InvariantCultureIgnoreCase)
            { "red", "yellow", "black", "BLACK" };

            crayons.Add ("blue");

            Console.WriteLine ("There are " + crayons.Count + " total crayons:");
            foreach (var crayon in crayons)
                Console.WriteLine ("  " + crayon);

            Console.WriteLine ("\nThere are " + crayons.GetDistinctCount() + " distinct colors:");
            foreach (var crayon in crayons.Distinct())
                Console.WriteLine ("  " + crayon);

            Console.WriteLine ("\nGot 'gold' crayon? " + crayons.Contains ("gold"));

            // RetainAll respects cardinality so the oldest 'black' is removed:
            crayons.RetainAll (new string[] { "white", "grey", "Black", "red" });

            Console.WriteLine ("\nAfter RetainAll: ");
            foreach (var crayon in crayons)
                Console.WriteLine ("  " + crayon);
        }

        /* Output:

        There are 5 total crayons:
          black
          BLACK
          blue
          red
          yellow

        There are 4 distinct colors:
          black
          blue
          red
          yellow

        Got 'gold' crayon? False

        After RetainAll:
          BLACK
          red

        */
    }
}

The next example shows using a RankedBag as a multimap.

using System;
using Kaos.Collections;

namespace ExampleApp
{
    public class CharMap : IComparable<CharMap>
    {
        public char Ch { get; private set; }
        public int Pos { get; private set; }
        public CharMap (char ch, int pos) { Ch = ch; Pos = pos; }
        public int CompareTo (CharMap other) => Ch.CompareTo (other.Ch);
        public override string ToString() => Ch + " :: " + Pos;
    }

    class RbExample02
    {
        static void Main()
        {
            var map = new RankedBag<CharMap>();
            string s1 = "this is it";

            for (int pos = 0; pos < s1.Length; ++pos)
                if (! Char.IsWhiteSpace (s1[pos]))
                    map.Add (new CharMap (s1[pos], pos));

            foreach (var mapItem in map)
                Console.WriteLine (mapItem);
        }

        /* Output:

        h :: 1
        i :: 2
        i :: 5
        i :: 8
        s :: 3
        s :: 6
        t :: 0
        t :: 9

        */
    }
}

The next example shows using this class for statistical calculations.

using System;
using System.Linq;
using Kaos.Collections;

namespace ExampleApp
{
    class RbExample03
    {
        static double Median (RankedBag<int> vals)
        {
            if (vals.Count == 0) return 0D;
            if (vals.Count % 2 == 1) return (double) vals.ElementAt (vals.Count/2);
            return (vals.ElementAt (vals.Count/2-1) + vals.ElementAt (vals.Count/2)) / 2D;
        }

        static double Mean (RankedBag<int> vals) => vals.Sum() / (double) vals.Count;
        static double Variance (RankedBag<int> vals) => vals.Sum (x => Math.Pow (Mean (vals) - x, 2)) / vals.Count;
        static double StandardDeviation (RankedBag<int> vals) => Math.Sqrt (Variance (vals));

        static void Main()
        {
            var scores = new RankedBag<int> (new int[] { 2, 5, 4, 4, 5, 4, 7, 9 });

            var mean = Mean (scores);
            var stddev = StandardDeviation (scores);

            Console.WriteLine ("Count = " + scores.Count + ", median = " + Median (scores) + ", mean = " + Mean (scores));
            Console.WriteLine ("Variance = " + Variance (scores));
            Console.WriteLine ("Standard deviation = " + StandardDeviation (scores));

            Console.WriteLine ("\nLow score: " + scores.Min);
            Console.WriteLine ("High score: " + scores.Max);

            Console.Write ("Scores within 1 standard deviation:");
            foreach (var score in scores.ElementsBetween ((int) (mean-stddev+0.5), (int) (mean+stddev+0.5)))
                Console.Write (" " + score);
            Console.WriteLine();
        }

        /* Output:

        Count = 8, median = 4.5, mean = 5
        Variance = 4
        Standard deviation = 2

        Low score: 2
        High score: 9
        Scores within 1 standard deviation: 4 4 4 5 5 7

        */
    }
}

The final example demonstrates round tripping binary serialization.

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 ExamComparer : Comparer<Exam>
    {
        public override int Compare (Exam x1, Exam x2) => x1.Score - x2.Score;
    }

    [Serializable]
    public class Exam : ISerializable
    {
        public int Score { get; private set; }
        public string Name { get; private set; }

        public Exam (int score, string name)
        { this.Score = score; this.Name = name; }

        protected Exam (SerializationInfo info, StreamingContext context)
        {
            this.Score = (int) info.GetValue ("Score", typeof (int));
            this.Name = (String) info.GetValue ("Name", typeof (String));
        }

        public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
        {
            info.AddValue ("Score", Score, typeof (int));
            info.AddValue ("Name", Name, typeof (String));
        }

        public override string ToString() => Score + ", " + Name;
    }


    class RbExample05
    {
        static void Main()
        {
            var bag1 = new RankedBag<Exam> (new ExamComparer());
            bag1.Add (new Exam (5, "Jack"));
            bag1.Add (new Exam (2, "Ned"));
            bag1.Add (new Exam (2, "Betty"));
            bag1.Add (new Exam (3, "Paul"));
            bag1.Add (new Exam (5, "John"));

            Console.WriteLine ("Items are inserted after other items that compare equally:");
            foreach (var item in bag1)
                Console.WriteLine ("  " + item);

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

            SerializeExams (fileName, bag1, formatter);
            Console.WriteLine ("\nWrote " + bag1.Count + " items to file '" + fileName + "'.");
            Console.WriteLine ();

            RankedBag<Exam> bag2 = DeserializeExams (fileName, formatter);
            Console.WriteLine ("Read back " + bag2.Count + " items:");

            foreach (var p2 in bag2)
                Console.WriteLine ("  " + p2);
        }

        static void SerializeExams (string fn, RankedBag<Exam> bag, IFormatter formatter)
        {
            using (var fs = new FileStream (fn, FileMode.Create))
            { formatter.Serialize (fs, bag); }
        }

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

        /* Output:

        Items are inserted after other items that compare equally:
          2, Ned
          2, Betty
          3, Paul
          5, Jack
          5, John

        Wrote 5 items to file 'Exams.bin'.

        Read back 5 items:
          2, Ned
          2, Betty
          3, Paul
          5, Jack
          5, John

        */
    }
}
Clone this wiki locally