javascript - 从两个不同的数组中返回具有最接近数字的数组
问题描述
编辑:为了清楚起见,这是对问题的改写(为混淆道歉):
问题:给定一个数组limits和一个数组punct_arr,其中两者都已排序,返回一个输出数组separation_index,其中separation_index[i]是punct_arr中最接近limits[i]的值。因此,separation_index 的大小将与限制相同。
所以,假设我有两个数组:
限制 = [280, 560]
punct_arr = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]
预期结果: [255, 556]
结果应始终与限制数组的长度相同。
这是我到目前为止得到的:
for (var limit = 0; limit < limits.length; limit++) {
for (var punct = 0; punct < punct_arr.length; punct++) {
if (Math.abs(punct_arr[punct - 1] - limits[limit]) < (Math.abs(punct_arr[punct] - limits[limit])) && (Math.abs(punct_arr[punct] - limits[limit]) < (Math.abs(punct_arr[punct] - limits[limit + 1])))) {
separation_index.push(punct_arr[punct-1]);
}
}
}
提前致谢!
解决方案
这是一种分解的方法,我们从高层次开始编写,并在此过程中定义辅助辅助函数 -
function closest (limits, inputs) {
return limits.map(v => closest1(v, inputs))
}
function closest1 (one, many) {
return many.reduce((r, v) =>
delta(r, one) < delta(v, one) ? r : v,
-Infinity
)
}
function delta (a, b) {
return Math.abs(a - b)
}
const limits = [280, 560]
const inputs = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]
console.log(closest(limits, inputs))
[ 255, 556 ]
推荐阅读
- python-3.x - 在循环中使用颜色图(python)
- f# - 从公共字符串生成 href 值和路由模式
- mysql - 从历史表中查询项目
- jenkins - 如何使用 jenkins 向 microsoft team\skype 发送管道更改(提交)通知
- python - 尝试在 Google Colab 上安装 xlwings
- django - django:我不小心删除了 manage.py 文件。如何恢复它?
- amazon-web-services - 如何在 aws EC2 中设置 Sockect.io 服务器,然后远程连接到服务器?
- php - 使用 Laravel 自动生成发票
- php - PHP:如何使用 GET 发送 cURL 请求?
- python - Keras model.inputs 不保存名称