Adjacent number algorithm grouper

前端 未结 13 1699
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  难免孤独
    2021-02-15 07:48

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

    My answer to the above question:

    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");
    }
    

提交回复
热议问题