Answers to exercises in Advanced C# and .NET Library (Part 2)

Exercise : Provide operator functions for ==, !=, >, < and ++ for MyTime class. Add conversion operators to MyTime class to convert int (total seconds) to MyTime object


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class MyTime
    {
        private int hour, min, sec;
        public MyTime(int hour, int min, int sec)
        {
            this.hour = hour;
            this.min = min;
            this.sec = sec;
        }
        public int TotalSeconds
        {
            get
            {

                return hour * 3600 + min * 60 + sec;
            }

        }

        public static bool operator ==(MyTime t1, MyTime t2)
        {
            return t1.TotalSeconds == t2.TotalSeconds;
        }
        public static bool operator !=(MyTime t1, MyTime t2)
        {
            return t1.TotalSeconds != t2.TotalSeconds;
        }
        public static bool operator >(MyTime t1, MyTime t2)
        {
            return t1.TotalSeconds > t2.TotalSeconds;
        }
        public static bool operator <(MyTime t1, MyTime t2)
        {
            return t1.TotalSeconds < t2.TotalSeconds;
        }
        public static MyTime operator ++(MyTime t1)
        {
            t1.sec++;
            if (t1.sec == 60)
            {
                t1.sec = 0;
                t1.min++;
                if (t1.min == 60)
                {
                    t1.min = 0;
                    t1.hour++;
                    if (t1.hour == 24)
                        t1.hour = 0;
                }
            }

            return t1;
        }

        public override string ToString()
        {
            return String.Format("{0}:{1}:{2}", hour, min, sec);
        }

        // Conversion operator
        public static explicit operator int(MyTime t)
        {
            return t.TotalSeconds;
        }
    }
    class TestMyTime
    {
        public static void Main()
        {
            MyTime t1 = new MyTime(10, 20, 30);
            MyTime t2 = new MyTime(10, 20, 30);
            MyTime t3 = new MyTime(10, 20, 33);
            MyTime t4 = new MyTime(10, 19, 30);

            Console.WriteLine(t1);

            Console.WriteLine(t1 == t2);
            Console.WriteLine(t1 != t3);
            Console.WriteLine(t2 > t4);
            Console.WriteLine(t2 < t3);
            Console.WriteLine(t1 == t3);
            t1++;
            Console.WriteLine(t1);
        }
    }
}


1. Create a class called Circle that stores x, y coordinates and radius. Overload == and != operators. Overload ++ operator that increases the x and y points by 1 unit. Add a couple of extension methods for Circle class to compare two objects, to print an object and to set x, y to center of given area in width and height and radius to 100.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    public class Circle
    {
        public int x { get; set; }
        public int y { get; set; }
        public int r { get; set; }

        public static bool operator ==(Circle c1, Circle c2)
        {
            return c1.x == c2.x && c1.y == c2.y && c1.r == c2.r;
        }
        public static bool operator !=(Circle c1, Circle c2)
        {
            return c1.x != c2.x || c1.y != c2.y || c1.r != c2.r;
        }
        public static Circle operator ++(Circle c1)
        {
            c1.x++;
            c1.y++;
            return c1;
        }
    }
    class TestCircle
    {
        public static void Main()
        {
            Circle c1 = new Circle { x = 10, y = 10, r = 10 };
            Circle c2 = new Circle { x = 10, y = 10, r = 10 };
            Circle c3 = new Circle { x = 10, y = 5, r = 50 };

            Console.WriteLine(c1 == c2);
            Console.WriteLine(c1 == c3);

            c1++;
            c1.Print();

            c2.set(100,200);
            c2.Print();
        }
    }
    public static class CircleExtensionsMethods
    {
        public static bool Compare(this Circle c1, Circle c2)
        {
            return c1 == c2;
        }
        public static void Print(this Circle c1)
        {
            Console.WriteLine("(x, y) : ({0}, {1})", c1.x, c1.y);
            Console.WriteLine("Radius : {0}", c1.r);
        }
        public static void set(this Circle c1, int width, int height)
        {
            c1.x = width / 2;
            c1.y = height / 2;
            c1.r = 100;
        }
    }
}

2.Create a generic class that implements a Queue data structure with the following methods and properties:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class GenericQueue
    {
        private T[] data = new T[10];
        int rear = 0, front=0;

        public void Add(T v)
        {
            if (rear == data.Length)
                throw new Exception("Queue is full!");

            data[rear] = v;
            rear++;
        }

        public T Remove()
        {
            if (front < rear)
            {
                return data[front++];
            }
            else
                throw new Exception("Empty Queue");

        }

        public bool Contains (T v) {
            for (int i = front; i < rear; i++)
            {
                if (data[i].Equals(v))
                    return true;
            }
            return false;
        }


        public void Print()
        {
            for (int i = front; i < rear; i++)
                Console.WriteLine(data[i]);
        }

        public int Length
        {
            get
            {
                return rear - front;
            }
        }

    }

    class TestQueue
    {
        public static void Main()
        {
            var q = new GenericQueue<string>();
            q.Add("Abc");
            q.Add("Xyz");

            q.Print();

            Console.WriteLine(q.Remove() );
            Console.WriteLine(q.Remove());

            Console.WriteLine(q.Length);

            q.Add("Pqr");
            q.Add("Def");

            q.Print();
        }
    }

}

3. Create a delegate type that points to a method, which takes an array of int as the parameter and performs operations on the array. Make the delegate point to methods like Print(), Reverse() and Sort() and perform those operations.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class DelegateOperations
    {
        delegate void ArrayOperation(int [] a);
        static void Main()
        {
            int[] a = { 10, 211, 50, 133, 144 };
            ArrayOperation printop = Print;
            ArrayOperation op;

            printop(a);

            op = Sort;
            op(a);
            Console.WriteLine("After Sorting");
            printop(a);


            op = Reverse;
            op(a);
            Console.WriteLine("After Reversing");
            printop(a);
        }

        public static void Sort(int [] a)
        {
            Array.Sort(a);
        }
        public static void Reverse(int [] a)
        {
                Array.Reverse (a);
        }
        public static void Print(int [] a)
        {
            foreach (int n in a)
                Console.WriteLine(n);
        }
    }
}



4. Create a function that takes any type of object and calls Print() method of the given object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class Test1
    {
        public void Print()
        {
            Console.WriteLine("Print in Test1");
        }
    }

    class Test2
    {
        public void Print()
        {
            Console.WriteLine("Print in Test2");
        }
    }

    class DynamicExercise
    {
        public static void Main()
        {
            Print(new Test1());
            Print(new Test2());
        }

        public static void Print(dynamic d)
        {
            d.Print();
        }
    }
}

5. Create a generic function called Insert() that takes an array, value to be inserted and position where it is to be inserted. Insert the value at the given position in the array. Similarly provide generic Delete() function that takes array and the position from where the value is to be deleted and deletes it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class GenericMethods
    {
        public static void Main()
        {
            int[] arr = { 10, 20, 30, 40, 50 };

            Insert(arr, 15, 1);
            Print(arr);
            Delete(arr, 0);
            Print(arr);

        }

        public static void Print<T>(T[] a)
        {
            foreach (T v in a)
                Console.WriteLine(v);
        }

        public static void Insert<T> ( T [] a, T v, int pos)
        {
            // push elements to right
            for (int i = a.Length - 1; i > pos; i--)
                a[i] = a[i - 1];

            a[pos] = v;

        }

        public static void Delete<T>(T[] a, int pos)
        {
            // push elements to left
            for (int i = pos; i < a.Length - 1; i ++ )
                a[i] = a[i + 1];

            a[a.Length - 1] = default(T);  // set last element to default
        }
    }
}

6. Accept two files and display common lines between those two files (Intersection).

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class Intersection
    {

        public static void Main()
        {
            Console.Write("Enter First File  : ");
            string filename1 = Console.ReadLine();

            Console.Write("Enter Second File : ");
            string filename2 = Console.ReadLine();

            var lines = new HashSet<string>();
            using (StreamReader sr1 = new StreamReader(filename1))
            {
                string line = sr1.ReadLine();
                while (line != null)
                {
                    lines.Add(line);
                    line = sr1.ReadLine();
                }
            }
            var commonlines = new HashSet<string>();

            using (StreamReader sr2 = new StreamReader(filename2))
            {
                string line = sr2.ReadLine();
                while (line != null)
                {
                    if (lines.Contains(line))
                        commonlines.Add(line);
                    line = sr2.ReadLine();
                }
            }

            foreach (string line in commonlines)
                Console.WriteLine(line);
        }

    }
}

7. Accept a file and display how many times each word is present in the file.

using System;
using System.Collections.Generic;
using System.IO;


namespace Booklet3_exercises
{
    class WordCount
    {

        public static void Main()
        {
            Console.Write("Enter Filename : ");
            string filename = Console.ReadLine();

            var wordscount = new SortedDictionary<string, int>();

            using (StreamReader sr = new StreamReader(filename))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    string[] words = line.Split('.', ' ');
                    foreach (string word in words)
                    {
                        if (word.Length == 0)
                            continue;
                        if (wordscount.ContainsKey(word))
                            wordscount[word]++;
                        else
                            wordscount.Add(word, 1);
                    }
                    line = sr.ReadLine();
                }
            }

            foreach (string word in wordscount.Keys)
                Console.WriteLine("[{0}] occurs [{1}]", word, wordscount[word]);
        }
    }
}


8. Accept a file and display all lines except duplicated lines

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class NonDuplicateLines
    {
        public static void Main()
        {
            Console.Write("Enter Filename : ");
            string filename = Console.ReadLine();

            var lines = new HashSet<string>();
            var duplines = new HashSet<string>();

            using (StreamReader sr = new StreamReader(filename))
            {
                string line = sr.ReadLine();
                while (line != null)
                {

                    if (lines.Contains(line))
                        duplines.Add(line);
                    else
                        lines.Add(line);

                    line = sr.ReadLine();
                }
            }


            foreach (string line in lines)
            {
                if (!duplines.Contains(line))
                      Console.WriteLine(line);
            }
        }
    }
}

9. Accept a file from user and display all words in sorted order by eliminating duplicates.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class SortedWords
    {

        public static void Main()
        {
            Console.Write("Enter filename : ");
            string filename = Console.ReadLine();

            var sortwords = new SortedSet<string>();

            using (StreamReader sr = new StreamReader(filename))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    string[] words = line.Split('.', ' ');
                    foreach (string word in words)
                    {
                        if (word.Length != 0)
                             sortwords.Add(word);
                    }
                    line = sr.ReadLine();
                }
            }
            foreach (string word in sortwords)
                Console.WriteLine(word);
        }

    }
}

10. Accept a file and remove all blank lines from the file and then write the new content into the same file.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booklet3_exercises
{
    class RemoveBlankLines
    {

        public static void Main()
        {
            Console.Write("Enter Filename : ");
            string filename = Console.ReadLine();
            var lines = new List<string>();
            using (StreamReader sr = new StreamReader(filename))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    if (line.Trim().Length > 0)
                        lines.Add(line);
                    line = sr.ReadLine();
                }
            }

            using (StreamWriter sw = new StreamWriter(filename))
            {
                foreach (string line in lines)
                    sw.WriteLine(line);
            }
        }

    }
}