Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find closest array of numbers to a target array?

I am working on the code below. Is there a way to get the closet array which are matching in all items with the goal array?

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>
like image 447
Mona Coder Avatar asked Nov 25 '25 19:11

Mona Coder


1 Answers

You can look at it with distances in an n-dimensional space (3 in this case)

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>
like image 90
SirPilan Avatar answered Nov 27 '25 08:11

SirPilan