Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Finding and sorting elements in an array


using System;

class FindInArray{

  public static bool NullPoint(Point p){
       return Math.Abs(p.X + p.Y) <= 0.0001;
  }       

  public static void Main(){

    /* An array of points:  */
    Point[] points = { new Point(1,2),
                       new Point(-1,2),
                       new Point(-2,2),
                       new Point(-4,5),
                       new Point(-5,5),
                       new Point(5,5),
                       new Point(-5,-5)
                     };

    /* Solution with anonymous delegate: */
    Point fp = Array.Find(points,
                                 delegate(Point p){
                                   return Math.Abs(p.X + p.Y) <= 0.0001;}
                             );

    if (fp != null)
        Console.WriteLine("We found point: {0}", fp);
    else
        Console.WriteLine("We did not find a point");


    /* Solution with a named static method: */
    Point fp1 = Array.Find(points, NullPoint);

    if (fp1 != null)
        Console.WriteLine("We found point: {0}", fp1);
    else
        Console.WriteLine("We did not find a point");


    /* Finding all desired points: */ 
    Point[] pts = Array.FindAll(points, NullPoint);
    Console.WriteLine("We found these points:");
    foreach(Point p in pts) Console.WriteLine(p);

    
    /* Sorting the points as desired: */
    Array.Sort(points, 
               delegate(Point p1, Point p2){
                 if (p1.X + p1.Y < p2.X + p2.Y)
                   return -1;
                 else if (p1.X + p1.Y == p2.X + p2.Y)
                   return 0;
                 else return 1;
               });

    Console.WriteLine("Sorted points:");
    foreach(Point p in points) Console.WriteLine(p);
  }

}