Cloning attack programming exercise

Cloning attack programming exercise.

Cloning attack emergency!! To all battle station, prepare the compilator!

You are given an array of integers. Return a new array, where:
1) the order of the array is the same
2) but all the duplicate numbers are removed

Example:
3,5,5,1 => 3,5,1
1,2,5,1,2,3 => 1,2,5,3

Scroll down for the solution of this coding problem.

    public static List<int> Unique(List<int> integers)
    {
        //Lets start by declaring a list variable 
        //for storing the unique integers.
        List<int> r = new List<int>();
        //the we shall go through each number in the original
        //list.
        foreach (var i in integers)
        {
            int k = 0;
            //Then each time, we will check, if the number 
            //we are checking, is already inside our list with
            //uniques. If it is not already inside it -> it must 
            //be unique and we will add it to the list.
            foreach (var item in r)
            {
                if (item == i) k++;
            }
            if (k==0) r.Add(i);
        }            
        return r;
    }

Of course we can try to use even shorter solutions:

        public static List<int> Unique(List<int> integers)
        {
            return integers.Distinct().ToList();
        }

From the LINQ library we will use Distinct() witch by the way is saved in a .dll file -it is inside System.Linq.dll. So Distinct() Returns distinct elements from a sequence. This elements are in form of an array but we need them do be in form of a list, so naturally we use .ToList() to convert them to a list.

Or you can use all sort of one-line solutions …

  public static List<int> Unique(List<int> integers)
     {
       return integers.GroupBy(x => x).Select(x => x.Key).ToList();
     }

All of them a valid in the beginning. But if you are learning a language with a lot of ready functions to use (i.e. most modern languages) its a good idea to make cards, for the one you use most often, or most like, or the one you going to use to make your future game 🙂 Just write an explanation of the function and some example on a piece of paper and collect them on your working desk. Don’t worry, in the beginning it seems that there is a lot of functions to memorize, but you when you start writing them on cards, they won’t be that many. Plus, you will remember them much better 😉