From: "Flávio Lisbôa" Date: 2007-10-30T07:25:26+09:00 Subject: Re: find the closest items in an array to a given value. ------=_Part_146_18423273.1193696725958 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline 2007/10/29, trebor777 : > > 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. > > > Also, if someone knows a good way to synchro Scrolling and Music with > tempo > value that would be great... > I mean, not the conversion to find how many frames between each beats. but > how to convert, the number of frames between 2 beat to a distance in > pixel...? ( and possibly with a set-able speed) ? > > > Thanks. > > -- > View this message in context: > http://www.nabble.com/find-the-closest-items-in-an-array-to-a-given-value.-tf4714369.html#a13475984 > Sent from the ruby-talk mailing list archive at Nabble.com. Something like this? (Supposing the array may not be in order) def array_between(a=[], v=0.0) return [] if a.empty? return [v, a.min] if v < a.min return [a.max, v] if v > a.max ret = [] ret.push a.find {|num| num < v} ret.push a.find {|num| num > v} ret.push v if ret.size < 2 return ret.sort end Just a quick 10-second sketch... Maybe you should have tried this too. And i know you from other forums too! Nice to see you here trebor!! ------=_Part_146_18423273.1193696725958--