javascript - 查找多维数组中两个相关数字最接近的组合

标签 javascript jquery arrays multidimensional-array nearest-neighbor

我需要根据用户输入搜索并比较多维数组中两个数字的最接近组合。

目前我有类似的东西可以找到最接近的匹配数字,例如“一个数字”。

var count= [10, 20, 30, 40],

  goal = userinput

  var closest = count.reduce(function(prev, curr) {
    return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  });

$('#result').attr('value', closest);

我想要做什么:当用户在userinput14中输入19userinput2 中,它应该搜索并比较多维数组 counts 中最接近的数字组合。

<input id="userinput1 " value="19" type="text">
<input id="userinput2 " value="4" type="text">

-

var userinput1 = $('#userinput1 ').val();
var userinput2 = $('#userinput2 ').val();

counts = [['10', '5'], ['20', '10']];

goal = [[userinput1, userinput2]];

/* NEEDED SCRIPT */

$('#result1').attr('value', closest1);
$('#result2').attr('value', closest2);

在此示例中,它应该选择 ['20', '10'] 并在不同的变量中输出这两个数字。

HTML 结果应该是:

<input id="result1" value="20" type="text">
<input id="result2" value="10" type="text">

最佳答案

为了比较索引方面的绝对差异,您可以先获取增量,然后根据总和返回数组。

const addAbsDelta = g => (s, v, i) => s + Math.abs(v - g[i]);

var counts = [[10, 5], [20, 10]],
    goal = [19, 4],
    result = counts.reduce((a, b) =>
        a.reduce(addAbsDelta(goal), 0) < b.reduce(addAbsDelta(goal), 0) ? a : b
    );
    
console.log(result);

为了获得其中一个值匹配的结果,您需要获取结果顺序的绝对增量与绝对增量之和的乘积,并取最小值。

function getApproximation(counts, goal) {
    const
        p = (r, v, i) => r * Math.abs(v - goal[i]),   // moves zeros to top
        s = (r, v, i) => r + Math.abs(v - goal[i]),   // allowes sorting
        score = a => a.reduce(p, 1) + a.reduce(s, 0); // get product and sum

    return counts
        .filter(a => goal.every((g, i) => a[i] >= g))
        .reduce((a, b) => score(a) <= score(b) ? a : b);
}

var counts = [[5300, 4.2], [6800, 6.0], [5650, 6.6], [2600, 7.0], [4700, 7.0], [3250, 7.3], [3800, 7.5], [3300, 7.8], [9000, 8.2], [5700, 8.5], [7400, 8.5], [6900, 8.7], [4300, 9.0], [5000, 9.5], [6000, 9.5], [7700, 9.5], [2750, 10.0], [5300, 10.0], [6500, 10.0], [8900, 10.5], [6800, 11.0], [3600, 11.4], [4500, 11.5], [9500, 11.5], [5700, 12.0], [5000, 24.0], [6500, 27.0], [7900, 30.0], [5700, 31.0]];

console.log(getApproximation(counts, [2000, 5]));  // [2600, 7]
console.log(getApproximation(counts, [2000, 30])); // [7900, 30]
console.log(getApproximation(counts, [2600, 30])); // [7900, 30] 

关于javascript - 查找多维数组中两个相关数字最接近的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51764150/

相关文章:

javascript - 动态 iframe 中的表单提交不会被触发

javascript - 哪个是包装历史 API 的最佳 JavaScript 库?

javascript - React-router-dom 重定向不适用于 withRouter HOC (react-redux)

javascript - 将 jquery 变量传递给 javascript 函数

javascript - jQuery:使用 CSS3 而不是 JavaScript 制作动画

python - 查找未知形状的 numpy ndarray 的第一个元素

javascript - Angular + php登录api cors问题

javascript - 通过 Javascript 从字符串中提取纬度和经度

c++ - 将二维数组的 1 维复制到同一数组的另一部分

JavaScript 嵌入每天都会变化的视频