language-agnosticcode-golf

Code Golf: Numeric Ranges


Challenge

Compactify a long list of numbers by replacing consecutive runs with ranges.

Example

Input

1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15
The input is guaranteed to be in ascending order and will not contain duplicates.

Output

1 - 4, 7, 8, 10, 12 - 15
Note that ranges of two numbers should be left as is. (7, 8; not 7 - 8)

Rules

You can accept a sorted list of integers (or equivalent datatype) as a method parameter, from the commandline, or from standard in. (pick whichever option results in shorter code)
You can output a list of strings by printing them, or by returning either a single string or set of strings.

Reference Implementation

(C#)

IEnumerable<string> Sample(IList<int> input) {
    for (int i = 0; i < input.Count; ) {
        var start = input[i];
        int size = 1;
        while (++i < input.Count && input[i] == start + size)
            size++;

        if (size == 1)
            yield return start.ToString();
        else if (size == 2) {
            yield return start.ToString();
            yield return (start + 1).ToString();
        } else if (size > 2)
            yield return start + " - " + (start + size - 1);
    }
}

Solution

  • Python, 83 characters

    def f(l,a=2):
     for x in l:
      b,a=a,(x+1in l)*(x-1in l)
      if a<1:print',- '[b],`x`,
    

    Demo:

    >>> l=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
    >>> f(l)
      1 - 4 , 7 , 8 , 10 , 12 - 15