Adjacent number algorithm grouper

前端 未结 13 1734
不思量自难忘°
不思量自难忘° 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:38

    Short and sweet Ruby

    def range_to_s(range)
      return range.first.to_s if range.size == 1
      return range.first.to_s + "-" + range.last.to_s
    end
    
    def format_ints(ints)
      range = []
      0.upto(ints.size-1) do |i|
        range << ints[i]
        unless (range.first..range.last).to_a == range
          return range_to_s(range[0,range.length-1]) + "," + format_ints(ints[i,ints.length-1])
        end
      end
      range_to_s(range)  
    end
    

提交回复
热议问题