On Oct 29, 2007, at 2:19 PM, trebor777 wrote:

>
> Hi!
>
> I'm searching for a light method for finding the closest items to a  
> given
> value.
>
> example/
>
> 1..10
> in a range
> i give,  5.5, return  5 and 6  for example....
>
> as i'm working with arrays, containing numbers, but with no regular  
> step...
> it will change i think.
> example..
>
> a = [ 1, 1.25, 2, 3, 3.5 ]
>
> if i give 1.85, it gives me 1.25 and 2
>
> It's for a little music game, where player has to tap at the right  
> moment,
> notes are register in a array, with the correct time, and as  
> players can't
> be accurate as a computer, i need some error margin. I working  
> with  0.05
> rounded values.

install rbtree - it has upper_bound and lower_bound methods that do  
just this - otherwise you can do something like this:



cfp:~ > cat a.rb
require 'alib'

Array.send :include, alib.bsearch

list = %w( a b c c c d e f )
index = list.bsearch_first {|x| x <=> "c"}
p list[index - 1 .. index + 1]

list = %w( a b c c c d e f )
index = list.bsearch_last {|x| x <=> "c"}
p list[index - 1 .. index + 1]


cfp:~ > ruby a.rb
["b", "c", "c"]
["c", "c", "d"]



a @ http://codeforpeople.com/
--
it is not enough to be compassionate.  you must act.
h.h. the 14th dalai lama