Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Exercise 1: Functional programming using delegates and generics
- ===============================================================
- Exercise 1.2 (mandatory) Construct a generic method Merge that takes two elements of type List<T> where
- T is some type that implements IComparable<T> and returns an element of type List<T>. The result of
- applying Merge to two sorted lists should be a merge of the two lists so, e.g. if x represents the list [0, 2, 4] and y
- represents the list [1, 3], the result of applying Merge to x and y should be the list [0, 1, 2, 3, 4]. To use List<T>
- you need to include the directive using System.Collections.Generic;.
- */
- using System;
- using System.Collections.Generic;
- namespace exercise_5
- {
- public class Exercise_5_1_2
- {
- public static List<T> Merge<T>(List<T> a, List<T> b)
- where T : IComparable<T> {
- // sort a and b - otherwise set it as a precondition - not sure how its done in c#
- a.Sort();
- b.Sort();
- // new merged list
- List<T> c = new List<T>();
- int i, j, m, n;
- i = 0;
- j = 0;
- m = a.Count;
- n = b.Count;
- do {
- // a[i] <= b[j]
- if (a[i].CompareTo(b[j]) == -1) {
- c.Add(a[i]);
- i++;
- } else {
- c.Add(b[j]);
- j++;
- }
- } while (i < m && j < n);
- if (i < m) {
- for (int p = i; p < m; p++) {
- c.Add(a[p]);
- }
- } else {
- for (int p = j; p < n; p++) {
- c.Add(b[p]);
- }
- }
- return c;
- }
- public static void Main() {
- Console.WriteLine("Exercise 5.1.2 ");
- Console.WriteLine("Merged two lists with various int's");
- List<int> l1 = new List<int>();
- l1.Add(1);
- l1.Add(33);
- l1.Add(2);
- l1.Add(3);
- l1.Add(5);
- l1.Add(12);
- l1.Add(4);
- List<int> l2 = new List<int>();
- l2.Add(13);
- l2.Add(1);
- l2.Add(6);
- l2.Add(3);
- l2.Add(25);
- List<int> mergedL1L2 = Merge(l1, l2);
- foreach(int x in mergedL1L2) {Console.Write(x + " ");}
- Console.WriteLine("");
- Console.WriteLine("Merged two lists with various int's (stated in the exercise)");
- List<int> l3 = new List<int>();
- l3.Add(0);
- l3.Add(2);
- l3.Add(4);
- List<int> l4 = new List<int>();
- l4.Add(1);
- l4.Add(3);
- List<int> mergedL3L4 = Merge(l3, l4);
- foreach(int x in mergedL3L4) {Console.Write(x + " ");}
- Console.WriteLine("");
- Console.WriteLine("Merged two lists with various string's (just a proof of contest)");
- List<string> l5 = new List<string>();
- l5.Add("scala");
- l5.Add("python");
- l5.Add("go");
- List<string> l6 = new List<string>();
- l6.Add("lisp");
- l6.Add("java");
- l6.Add("c#");
- l6.Add("ruby");
- l6.Add("scheme");
- l6.Add("sql");
- List<string> mergedL5L6 = Merge(l5, l6);
- foreach(string x in mergedL5L6) {Console.Write(x + " ");}
- Console.WriteLine("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment