performance - 通过表达式查找最佳匹配
问题描述
背景
假设您有一个数字数组,并且您想找到最接近某个预定值的数字。
示例,没有特定的语言:
baseValue = 6
array = [1, 3, 5, 8, 9, 11, 13]
// 5 is the value closest to 6, and is the expected return value
我们可以通过跟踪当前的最佳匹配来解决这个问题,如下所示:
for value in array
diff = abs(value - baseValue)
if (diff < currentBestMatch)
currentBestMatch = diff
// And at this point, currentBestMatch fits its name
但是这段代码是不完整的,因为currentBestMatch
我们进入循环时没有初始化,所以比较diff < currentBestMatch
会中断。
可能的解决方案
currentBestValue
例如,在循环之前实例化-1
,并将 if 条件扩展为if (diff < currentBestMatch OR currentBestMatch == -1)
实例化为
currentBestValue
一些可笑的高但任意的值,例如该类型的最大允许数量,以便第一次检查将始终给出更好的匹配
可能的问题
第一个解决方案感觉不对,因为现在我们必须执行
currentBestMatch
检查。好吧,从技术上讲不是,因为 if 条件应该在大多数语言的第一个条件上触发。但是,它仍然感觉像是一段不合时宜的代码。第二种解决方案感觉有点不对劲,因为如果可笑的高值实际上低于最佳匹配怎么办?更不用说,为此目的存储可笑的高值的内存成本是多少?可能我们不会注意到这一点,但是如果我们继续这样编程呢?
问题
有没有更理智的方法来解决这个感觉更干净的问题?我知道这是一种随意的定义,但我想这里的大多数人都会明白我的意思。
解决方案
而不是使用硬编码值-1
或inf
使用数组中的实际值。如果数组为空,则无论如何都必须处理这种情况(可能会抛出异常),因此访问数组中的第一个条目是安全的。
顺便说一句:而不是currentBestMatch = diff
你可能的意思是currentBestMatch = value
因为你想“找到最接近某个预定值的数字”而不是“差异”。
伪代码:
if array is empty
throw exception
diff = abs(array[0] - baseValue)
currentBestMatch = array[0]
for value in array starting at the second entry
diff = abs(value - baseValue)
if (diff < currentBestMatch)
currentBestMatch = value
这里有一个小的代码重复。你可以转移abs(... - ...)
到它自己的功能。但这与使用argmin(array, x -> abs(x-baseValue))
.
推荐阅读
- javascript - 使用 JavaScript 执行器连接可变字符串
- arrays - 如何连接以逗号分隔的命名范围的返回值
- mysql - B树的最小占用率是多少?
- c# - 如何从 Ninja Trader 的操作中使用 C# 制作 JSON 帖子?
- javascript - 如何在运行测试用例之前正确初始化/加载 aurelia-dialog 插件?
- google-chrome - 将不安全的来源视为安全
- javascript - 关于在 JavaScript 中调用函数,哪一个是正确的?
- c++11 - 为什么委托给默认构造函数不为零初始化成员变量
- rabbitmq - 我更改了 rabbitmq 的磁盘限制,现在无法重新启动它。
- react-native - 反应导航不起作用