首页 > 解决方案 > 从两个不同的数组中返回具有最接近数字的数组

问题描述

编辑:为了清楚起见,这是对问题的改写(为混淆道歉):

问题:给定一个数组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]);
            }
        }
    }

提前致谢!

标签: javascriptarraysalgorithmloops

解决方案


这是一种分解的方法,我们从高层次开始编写,并在此过程中定义辅助辅助函数 -

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 ]

推荐阅读