How would you display an array of integers as a set of ranges? (algorithm)

后端 未结 16 2932
我在风中等你
我在风中等你 2021-02-15 18:04

Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:

$numbers = ar         


        
16条回答
  •  青春惊慌失措
    2021-02-15 18:29

    C (gcc)

    It is similar to the Python's version.

    void ranges(int n; int a[n], int n)
    {
      qsort(a, n, sizeof(*a), intcmp);
      for (int i = 0; i < n; ++i) {
        const int start = i;
        while(i < n-1 and a[i] >= a[i+1]-1)
          ++i;
        printf("%d", a[start]);
        if (a[start] != a[i])
          printf("-%d", a[i]);
        if (i < n-1)
          printf(",");
      }
      printf("\n");
    }
    

    Example:

    /**
     * $ gcc -std=c99 -Wall ranges.c -o ranges && ./ranges
     */
    #include  // and
    #include 
    #include 
    
    #define T(args...)                                              \
      {                                                             \
        int array[] = {args};                                       \
        ranges(array, sizeof(array) / sizeof(*array));              \
      }
    
    int intcmp(const void* a, const void* b)
    {
      const int *ai = a;
      const int *bi = b;
    
      if (*ai < *bi)
        return -1;
      else if (*ai > *bi)
        return 1;
      else
        return 0;
    }
    
    int main(void)
    {
      T(1,3,4,5,6,8,11,12,14,15,16);
      T();
      T(1);
      T(1, 2);
      T(3, 1);
      T(1, 3, 4);
      T(1, 2, 4);
      T(1, 1, 2, 4);
      T(1, 2, 2, 4);
      T(1, 2, 2, 3, 5, 5);
    }
    

    Output:

    1,3-6,8,11-12,14-16
    
    1
    1-2
    1,3
    1,3-4
    1-2,4
    1-2,4
    1-2,4
    1-3,5
    

提交回复
热议问题