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

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

    I will assume the array X() is pre-sorted (and if not, sort the array before-hand).

    for each element of X() as $element (with $i as current array posistion)
        add $element to end of array Y()
        if (X($i) + 1 is less than X($i + 1)) AND ($i + 1 is not greater than sizeof(X())) then
            append Y(1)."-".Y(sizeof(Y())) to end of Z()
            unset Y()
        end if    
    next
    if anything remains in Y() append to end of Z()
    
    

    well, that's how I would do it.

提交回复
热议问题