From: ermac Date: 2007-10-30T14:00:40+09:00 Subject: Re: find the closest items in an array to a given value. 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 > Of course there are many ways. Here's one. Add your target value to the array and sort, then return the values before and after it in sequence. Note that this code 'wraps' the values in the array -- a target value lower than the lowest value in the array, or higher than the highest value, will return the starting and ending values. #!/usr/bin/ruby -w # a is array of values, x is target value def nearest(a,x) tmp = a.sort tmp << x tmp.sort! i = tmp.index x [tmp[i-1], tmp[i+1]] end a = [ 1, 1.25, 2, 3, 3.5 ] x = ARGV.shift.to_i a,b = nearest(a,x) puts "%0.2f => %0.2f,%0.2f" % [x, a, b]