如何找到最接近目标数组的数字数组?

时间:2019-05-03 21:56:27

标签: javascript jquery

我正在处理以下代码。有没有一种方法可以获取与目标数组在所有项目中都匹配的壁橱数组?

var counts = [
              [4,9,15],
              [2,11,81],
              [20,12,80],
              [14,3,80],
              [15,6,2],
              ]
  goal = [14,10,70];

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

console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2 个答案:

答案 0 :(得分:2)

您可以采用delta函数,该函数采用两个数组并返回绝对差之和,

const delta = (a, b) => a.reduce((r, v, i) => r + Math.abs(v - b[i]), 0);

var counts = [[4, 9, 15], [2, 11, 81], [20, 12, 80], [14, 3, 80], [15, 6, 2]],
    goal = [14, 10, 70],
    closest = counts.reduce((a, b) => delta(a, goal) < delta(b, goal) ? a : b);

console.log(closest);

使用三角形的平方

const delta = (a, b) => a.reduce((r, v, i) => r + (v - b[i]) ** 2, 0);

var counts = [[4, 9, 15], [2, 11, 81], [20, 12, 80], [14, 3, 80], [15, 6, 2]],
    goal = [14, 10, 70],
    closest = counts.reduce((a, b) => delta(a, goal) < delta(b, goal) ? a : b);

console.log(closest);

答案 1 :(得分:2)

您可以在n维空间(本例中为3)的距离内观察它

var counts = [
              [4,9,15],
              [2,11,81],
              [20,12,80],
              [14,3,80],
              [15,6,2],
              ]
  goal = [14,10,70];

var best = Infinity;
var closest = null;
for(var i in counts) {
  var sum = 0;
  for(var j in counts[i]) {
    sum += (goal[j] - counts[i][j])**2;
  }
  if ((sum**.5) < best) {
    closest = counts[i];
    best = sum**.5;
  }
}

console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>