# Algorithm help

**URL:** <https://rubytalk.org/t/algorithm-help/19968>\
**Category:** ruby-talk\
**Created:** [5 August 2005 14:55 UTC](https://rubytalk.org/t/algorithm-help/19968 "2005-08-05T14:55:40Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kroeger\_Simon\_ext](https://avatars.discourse-cdn.com/v4/letter/k/5daacb/32.png) [@Kroeger\_Simon\_ext](https://rubytalk.org/u/Kroeger_Simon_ext)\
**Post date:** [5 August 2005 14:55 UTC](https://rubytalk.org/t/algorithm-help/19968/1 "2005-08-05T14:55:40Z")

</div>

> i never thought i'd get any help at all on this and ended up  
> with so many  
> viable ideas... what a great list!

Yeah, and I hope this is the last message (at least my last  
message) in this thread 🙂

def to\_ranges d  
&nbsp;&nbsp;&nbsp;&nbsp;return unless d && d.size \> 0  
&nbsp;&nbsp;&nbsp;&nbsp;return [d.first..d.last] if (d.last - d.first).abs==d.size-1  
&nbsp;&nbsp;&nbsp;&nbsp;r1, r2 = to\_ranges(d[0...(d.size/2)]), to\_ranges(d[(d.size/2)..-1])  
&nbsp;&nbsp;&nbsp;&nbsp;return r1+r2 if (r1.last.last - r2.first.first).abs != 1  
&nbsp;&nbsp;&nbsp;&nbsp;r1[0..-2]+[r1.last.first..r2.first.last]+r2[1..-1]  
end

That's not so short but it handles negativ values, reversed arrays  
and empty arrays and all of them in O(log n) time.

I hope that's it.

Simon
