Number List Compression

Input: Sorted number list
1, 2, 3, 10, 25, 26, 30, 31, 32, 33

Output: Merge consecutive segments
1-3, 10, 25-26, 30-33

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sorted array
            int[] A = { 1, 2, 3, 7, 8, 10, 11, 12, 14 };
            for(int i = 0; i < A.Length; i++)
            {
                int lowerRange = A[i];
                int upperRange = 0; bool range = false;
                while (i < A.Length - 1 && A[i] + 1 == A[i + 1])
                {
                    upperRange = A[i + 1];
                    range = true;
                    i++;
                }
                if (range)
                {
                    if(i + 1 == A.Length) //check for last element
                    {
                        Console.Write(lowerRange + " - " + upperRange);
                    }
                    else
                    {
                        Console.Write(lowerRange + " - " + upperRange + ", ");
                    }
                }
                else
                {
                    if (i + 1 == A.Length) //check for last element
                    {
                        Console.Write(lowerRange);
                    }
                    else
                    {
                        Console.Write(lowerRange + ", ");
                    }
                }
            }
            Console.WriteLine();            
        }
    }
}

Output
=======
1 - 3, 7 - 8, 10 - 12, 14
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s