Thursday 21 December 2017

Check for missing number in sequence

//There are numbers from 1 to N in an array. out of these, one of the number
        //    gets duplicated and one is missing.The task is to write
        //    a program to find out the duplicate number.

        public void MissAndDuplicateTest()
        {
            int[] Array1 =new int[] { 1, 2, 3, 1, 5,2 };
            int num = 1,  missed = 0, duplicated = 0;
            while (num <= Array1.Length)
            {
               // Console.WriteLine("nunn"+num + "array1 Value" + Array1[num - 1]);
                if (num != Array1[num - 1])
                {
                    missed = num;
                    duplicated = Array1[num - 1];
                    if (missed != 0 && duplicated != 0)
                        Console.WriteLine("Missed number is {0} Duplicated number is {1}", missed, duplicated);
                }
                num++;
            }
           
        }

        //Result :
        // Missed number is 4 Duplicated number is1
        // Missed number is 6 Duplicated number is 2

No comments:

Post a Comment