0

I want to find the differences between all closest-neigbour pairs and sum them, given the input array is even-length.

I have this code right now but it only gives the minimum difference of one pair. How do I go about to achieve this? So take out the pairs who have already been summed and calculate with the rest of the pairs.

 var lowestDiff = Infinity;
arr.sort((a, b) => a - b);
for (var i = 0; i < arr.length - 1; i++) {
    lowestDiff = Math.min(lowestDiff, Math.abs(arr[i] - arr[i + 1]));
}
   console.log(lowestDiff);

So for example if the input is: [6,2,3,6], output would be: 1 because 6 pairs with 6 and 2 pairs with 3

So essentially i want to pair an element with another element which is closest to them, and get that difference. And sum them.

Y_Lakdime
  • 825
  • 2
  • 15
  • 33

1 Answers1

1

As you need to find the sum of the minimum difference pairs from an even length array. One thing to note: here is that-: After sorting the given array closest pairs will be adjacent to each other So, I think below code should work

function min_difference(arr)
{
       arr.sort(function(a, b) {
          return a - b;
                });
       let ans=0;
       for (let i=1;i<arr.length;i+=2)
      {
          ans+=(arr[i]-arr[i-1]);
      }
       return ans;
}
var arr=[2,2,2,2];
console.log(min_difference(arr));
saurabh sisodia
  • 312
  • 1
  • 8
  • The explanation is good, but [the sorting does not work](https://stackoverflow.com/q/1063007/1048572) and I'd recommend a `for` loop instead of a `while` loop. – Bergi Jul 28 '20 at 23:28
  • 1
    @Bergi Thank You very much. I have updated my answer. – saurabh sisodia Jul 28 '20 at 23:47
  • @saurabhsisodia : `Math.abs()` in above case seems to do only to things: slow down your code and make it more verbose. As long as your items are sorted in ascending order, the difference between them will be positive (or 0) anyways. Also, I would recommend to wrap that code block into function which would return `ans` rather than `console.log()` it. You may consider to turn your code into live-snippet, as well. – Yevhen Horbunkov Jul 31 '20 at 07:43
  • @saurabhsisodia : you're supposed to do rather something, like `function min_difference(arr){..`, aren't you? – Yevhen Horbunkov Jul 31 '20 at 16:11