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

后端 未结 16 3357
我在风中等你
我在风中等你 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:32

    first: sort second: tokenise then: print the first value and loop over subsequent ones. If the 'current' value is equal to the last value +1, skip it. Otherwise if you've skipped value print dash and the value, otherwise print a comma and repeat.

    That should do. Unless you wanted me to code up your homework for you? :)

提交回复
热议问题