not bad (and *so* short), but failing for descending ranges and ones with
negative values:
harp:~ > ruby a.rb
=>
[0] => [0..0]
[0, 1] => [0..1]
[1, 0] => [0..1]
[0, 1, 2] => [0..2]
[2, 1, 0] => [0..2]
[0, 1, 2, 3] => [0..3]
[3, 2, 1, 0] => [0..3]
[0, 3] => [0..0, 3..3]
[3, 0] => [0..0, 3..3]
[0, 3, 5] => [0..0, 3..3, 5..5]
[5, 3, 0] => [0..0, 3..3, 5..5]
[0, 3, 5, 7] => [0..0, 3..3, 5..5, 7..7]
[7, 5, 3, 0] => [0..0, 3..3, 5..5, 7..7]
[0, 1, 3, 4] => [0..1, 3..4]
[4, 3, 1, 0] => [0..1, 3..4]
[0, 1, 3, 4, 6, 7] => [0..1, 3..4, 6..7]
[7, 6, 4, 3, 1, 0] => [0..1, 3..4, 6..7]
[0, 1, 3, 4, 6, 7, 9, 10] => [0..1, 3..4, 6..7, 9..10]
[10, 9, 7, 6, 4, 3, 1, 0] => [0..1, 3..4, 6..7, 9..10]
[0, 1, 3, 4, 6, 7, 10] => [0..1, 3..4, 6..7, 10..10]
[10, 7, 6, 4, 3, 1, 0] => [0..1, 3..4, 6..7, 10..10]
[0, 3, 4, 6, 7, 9, 10] => [0..0, 3..4, 6..7, 9..10]
[10, 9, 7, 6, 4, 3, 0] => [0..0, 3..4, 6..7, 9..10]
[0, 1, 3] => [0..1, 3..3]
[3, 1, 0] => [0..1, 3..3]
[0, 3, 4] => [0..0, 3..4]
[4, 3, 0] => [0..0, 3..4]
[0, -1] => [0..0]
[-1, 0] => [0..0]
[0, -1, -2] => [0..0]
[-2, -1, 0] => [0..0]
[0, -1, -3, -4] => [0..0]
[-4, -3, -1, 0] => [0..0]
[0, -1, -3, -4, -6] => [0..0]
[-6, -4, -3, -1, 0] => [0..0]
[0, -1, -3, -4, -6, -7] => [0..0]
[-7, -6, -4, -3, -1, 0] => [0..0]
[-1, -3, -4, -6, -7] =>
[-7, -6, -4, -3, -1] =>
[-3, -4] =>
[-4, -3] =>
[-3, -4, -6, -8, -9, -10, -11, -12, - =>
[-42, -41, -40, -39, -38, -37, -36, - =>
harp:~ > cat a.rb
tests = [
,
[0],
[0,1],
[0,1,2],
[0,1,2,3],
[0,3],
[0,3,5],
[0,3,5,7],
[0,1,3,4],
[0,1,3,4,6,7],
[0,1,3,4,6,7,9,10],
[0,1,3,4,6,7,10],
[0,3,4,6,7,9,10],
[0,1,3],
[0,3,4],
[0,-1],
[0,-1,-2],
[0,-1,-3,-4],
[0,-1,-3,-4,-6],
[0,-1,-3,-4,-6,-7],
[-1,-3,-4,-6,-7],
[-3,-4],
[-3,-4,-6, *(-42 .. -8).to_a.reverse],
]
def sequences d
seqs =
d.inject(0) {|s,x| s | (1 << x)}.to_s(2).reverse!.scan(/1+/) do |m|
s = $`.length
seqs << (s .. (s + m.length - 1))
end
seqs
end
tests.each do |a|
begin
printf "%-37.37s => %37.37s\n", a.inspect, sequences(a).inspect
a.reverse!
printf "%-37.37s => %37.37s\n", a.inspect, sequences(a).inspect
rescue => e
printf "%-37.37s => %s\n", a.inspect, "#{ e } (#{ e.message })"
end
end
i never thought i'd get any help at all on this and ended up with so many
viable ideas... what a great list!
regards.
-a
···
On Fri, 5 Aug 2005, Robert Klemme wrote:
Btw, here's another funny idea:
-----------------
data = [3, 4, 5, 6, 7, 8, 9, 15, 38, 39, 40, 41, 6789, 6790, 9998, 9999]
ranges =
data.inject(0) {|s,x| s | (1 << x)}.to_s(2).reverse!.scan(/1+/) do |m|
s = $`.length
ranges << (s .. (s + m.length - 1))
end
puts ranges
--
email :: ara [dot] t [dot] howard [at] noaa [dot] gov
phone :: 303.497.6469
My religion is very simple. My religion is kindness.
--Tenzin Gyatso
===============================================================================