Monday, March 31, 2014

Compress the Number Range




Program:   Compress the Number Range.

Input will be given as sequence of number , we need to compress the number if the numbers are continues.
Ex:  1,2,3,8,9,52,30,31,32.
Output : 1-3,8-9,30-32,52

Coding

class Program
    {
        static void Main(string[] args)
        {
            string numrange = "52,23,13,14,89,11,90,12,36,86,87,88,4,6,8,9,1,2,3";
            string asscendingorder = ordernumber(numrange);
            string finaloutput = compressnumber(asscendingorder);
            Console.ReadKey();
        }

        private static string ordernumber(string num)
        {
            // Bubble sorting Technique
            string[] range = num.Split(',');
            int i = 0;
            while (i < range.Length)
            {
                for (int j = 0; j < range.Length - 1; j++)
                {
                    if (int.Parse(range[j]) > int.Parse(range[j + 1]))
                    {
                        var x = range[j];
                        var y = range[j + 1];
                        range[j] = y;
                        range[j + 1] = x;
                    }
                }
                i++;
            }
            string orderedlist = string.Join(",", range);        
            return orderedlist;
        }

        private static string compressnumber(string num)
        {        
            int count = 0;
            String final =null;
            string[] range = num.Split(',');
            for (int i = 0; i < range.Length-1; i++)
            {              
                int first = int.Parse(range[i]);
                int second = int.Parse(range[i + 1]);
                if (!((first + 1).Equals(second)))
                {
                    count = 0;
                    final = final + range[i] + ",";                
                }
                else if (count == 0)
                {
                    count++;
                    final = final+ range[i] + "-";                    
                }
                if (i.Equals(range.Length - 2))
                {
                    final = final + range[i+1];
                }
            }  

            return final.ToString();
        }
    }



Dell

No comments:

Post a Comment