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

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

    Perl 6

    sub to_ranges( Int *@data ){
      my @ranges;
      
      OUTER: for @data -> $item {
        for @ranges -> $range {
          # short circuit if the $item is in a range
          next OUTER if $range[0] <= $item <= $range[1];
          
          given( $item ){
            when( $range[0]-1 ){ $range[0] = $item }
            when( $range[1]+1 ){ $range[1] = $item }
          }
        }
        
        push @ranges, [$item,$item];
      }
      
      return @ranges;
    }
    

提交回复
热议问题