Display 1,2,3,4,5,6,8,10,11 as 1-6,8,10-11

Billa picture Billa · Feb 19, 2013 · Viewed 10.3k times · Source

I have this sequence 1,2,3,4,5,6,8,10,11

Expected output is 1-6,8,10-11

This problem is about formatting the sequence in easy readable form

I tried with c# and used many if & else.

Interviewer said, there is some simple algorithm to do this.

I have no idea how to achive this very simple.

Also for 1,2,3 i shown 1-3. They said its wrong!.

Is there any design pattern(interpreter) involved in this logic?

Answer

Ivan G picture Ivan G · Feb 19, 2013

Here is one way of doing it:

        int[] numbers = { 1, 2, 3, 4, 5, 6, 8, 10, 11 };

        int start, end;
        for (int i = 0; i < numbers.Length; i++)
        {
            start = numbers[i];

            while (i < numbers.Length - 1 && numbers[i] + 1 == numbers[i + 1])
                i++;

            end = numbers[i];

            if(start == end)
                Console.WriteLine(start);
            else
                Console.WriteLine(start + " - " + end);
        }

This will display subsequent numbers that grow incrementally as range. Numbers that are not increasing linearly are not written as part of a range.

Here is another version of the first approach, it utilizes the same for loop to iterate on range:

        int temp = numbers[0], start, end;
        for (int i = 0; i < numbers.Length; i++)
        {
            start = temp;

            if (i < numbers.Length - 1 )
                // if subsequent numbers are incremental loop further
                if (numbers[i] + 1 == numbers[i + 1])
                    continue;
                // if they are not, number at index i + 1 is a new 'start' for the next iteration
                else
                    temp = numbers[i + 1];

            end = numbers[i];

            if (start == end)
                Console.WriteLine(start);
            else
                Console.WriteLine(start + " - " + end);
        }