理想情况下,我想要一个Ruby或Javascript的解决方案用数组代替javascript中的范围就可以了。
我想输入如下:

    [0..301, 230..268, 242..364, 574..579, 587..593]


    [0,301, 230,268, 242,364, 574,579, 587,593]

把它变成这样:
    [0..230, 230..242, 242..268, 268..301, 301..364, 574..579, 587..593]


    [[0,230], [230,242, [242,268], [268,301], [301,364], [574,579, [587,593]]

任何帮助都很好这种方法有帮助,但不是完全的,因为它提供了完整的范围而不是分块的范围,How do I summarize array of integers as an array of ranges?

最佳答案

下面是一个ruby解决方案:

ranges = [0..301, 230..268, 242..364, 574..579, 587..593]
endpoints = ranges.map{|r| [r.first, r.last]}.flatten.sort
values = ranges.map{|r| r.to_a}.reduce(:+)

new_ranges = []
endpoints.reduce do |x, y|
    r = Range.new(x,y);
    new_ranges << r if r.all?{|v| values.include? v}
    y
end

puts new_ranges

#0..230
#230..242
#242..268
#268..301
#301..364
#574..579
#587..593

10-01 07:00