From: "Ara.T.Howard" Date: 2005-08-05T23:02:40+09:00 Subject: Re: algorithm help On Fri, 5 Aug 2005, Kroeger Simon (ext) wrote: > >> d = [1, 3, 4, 5, 6, 7, 8, 9, 15, 38, 39, 40, 41, 6789, 6790, >> 9998, 9999] >> puts d.inject([d[0]..d[0]]){|r,x|r<<(((r.last.end+1>=x)?r.pop.end: >> x)..x)} > > erm, this has to be > > d = [1, 3, 4, 5, 6, 7, 8, 9, 15, 38, 39, 40, 41, 6789, 6790, 9998, 9999] > puts d.inject([d[0]..d[0]]){|r,x| > r<<(((r.last.end+1>=x)?r.pop.first: x)..x)} there are lots of failures with this however: harp:~ > ruby a.rb [] => bad value for range (bad value for range) [0] => [0..0] [0] => [0..0] [0, 1] => [0..1] [1, 0] => [1..0] [0, 1, 2] => [0..2] [2, 1, 0] => [2..0] [0, 1, 2, 3] => [0..3] [3, 2, 1, 0] => [3..0] [0, 3] => [0..0, 3..3] [3, 0] => [3..0] [0, 3, 5] => [0..0, 3..3, 5..5] [5, 3, 0] => [5..0] [0, 3, 5, 7] => [0..0, 3..3, 5..5, 7..7] [7, 5, 3, 0] => [7..0] [0, 1, 3, 4] => [0..1, 3..4] [4, 3, 1, 0] => [4..0] [0, 1, 3, 4, 6, 7] => [0..1, 3..4, 6..7] [7, 6, 4, 3, 1, 0] => [7..0] [0, 1, 3, 4, 6, 7, 9, 10] => [0..1, 3..4, 6..7, 9..10] [10, 9, 7, 6, 4, 3, 1, 0] => [10..0] [0, 1, 3, 4, 6, 7, 10] => [0..1, 3..4, 6..7, 10..10] [10, 7, 6, 4, 3, 1, 0] => [10..0] [0, 3, 4, 6, 7, 9, 10] => [0..0, 3..4, 6..7, 9..10] [10, 9, 7, 6, 4, 3, 0] => [10..0] [0, 1, 3] => [0..1, 3..3] [3, 1, 0] => [3..0] [0, 3, 4] => [0..0, 3..4] [4, 3, 0] => [4..0] [0, -1] => [0..-1] [-1, 0] => [-1..0] [0, -1, -2] => [0..-2] [-2, -1, 0] => [-2..0] [0, -1, -3, -4] => [0..-4] [-4, -3, -1, 0] => [-4..-3, -1..0] [0, -1, -3, -4, -6] => [0..-6] [-6, -4, -3, -1, 0] => [-6..-6, -4..-3, -1..0] [0, -1, -3, -4, -6, -7] => [0..-7] [-7, -6, -4, -3, -1, 0] => [-7..-6, -4..-3, -1..0] [-1, -3, -4, -6, -7] => [-1..-7] [-7, -6, -4, -3, -1] => [-7..-6, -4..-3, -1..-1] [-3, -4] => [-3..-4] [-4, -3] => [-4..-3] [-3, -4, -6, -8, -9, -10, -11, -12, - => [-3..-42] [-42, -41, -40, -39, -38, -37, -36, - => [-42..-8, -6..-6, -4..-3] 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 d.inject([d[0]..d[0]]){|r,x| r<<(((r.last.end+1>=x)?r.pop.first: x)..x)} 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 it is short though ;-) -a -- =============================================================================== | 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 ===============================================================================