how to find best matching element in array of numbers?

怎甘沉沦 提交于 2019-12-03 10:03:14

问题


I need help with something that seems simple but confuses me. Trying to write some fuzzy matching method that copes with differences in format between what value is computed as needed, and which are actually available from a selection list.

The value (option strike price) is always a computed Float like 85.0 or Int.

The array contains numbers in string form, unpredictable in either increment or whether they will be shown rounded to some decimal (including extra zeros like 5.50) or no decimal (like 85), eg.:

select_list = ["77.5", "80", "82.5", "85", "87.5", "90", "95", "100", "105"]

I am unsure how to write a simple line or two of code that will return the closest matching element (by number value) as it appears in the array. For example, if select_list.contains? 85.0 returned "85"

Actually, the selection choices come from a Watir::Webdriver browser.select_list(:id, "lstStrike0_1") HTML object whose visible text (not HTML value) are those numbers; maybe there is a more direct way to just call browser.select_list(:id, "lstStrike0_1").select X without having to figure out in Watir how to convert all those choices into a Ruby array?


回答1:


xs = ["77.5", "80", "82.5", "85", "87.5", "90", "95", "100", "105"]
xs.min_by { |x| (x.to_f - 82.4).abs } 
#=> "82.5"



回答2:


I'm not a ruby coder so this might not be the best way to do it

def select_closest(list, target)                               
    return (list.map {|x| [(x.to_f - target).abs, x]}).min[1]  
end                                                            

select_list = ["77.5", "80", "82.5", "85", "87.5", "90", "95", "100", "105"] 

puts select_closest(select_list, 81)  # yields 80


来源:https://stackoverflow.com/questions/11476878/how-to-find-best-matching-element-in-array-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!