如何在数字数组中找到最匹配的元素? [英] how to find best matching element in array of numbers?

查看:46
本文介绍了如何在数字数组中找到最匹配的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些看似简单但让我困惑的事情的帮助.尝试编写一些模糊匹配方法,以处理根据需要计算的值与从选择列表中实际可用的值之间的格式差异.

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.

价值(期权执行价格)总是一个计算的浮点数,如 85.0 或 Int.

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

数组包含字符串形式的数字,无论是增量还是无法预测它们是否会显示为小数点(包括额外的零,如 5.50)或没有小数点(如 85)代码>),例如:

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"]

我不确定如何编写一两行简单的代码来返回最接近的匹配元素(按数字值),因为它出现在数组中.例如,如果 select_list.contains?85.0 返回 "85"

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"

实际上,选择选项来自 Watir::Webdriver browser.select_list(:id, "lstStrike0_1") HTML 对象,其可见文本(不是 HTML 值)是那些数字;也许有更直接的方法来调用 browser.select_list(:id, "lstStrike0_1").select X 而不必在 Watir 中弄清楚如何将所有这些选择转换为 Ruby 数组?

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?

推荐答案

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"

这篇关于如何在数字数组中找到最匹配的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆