Computer >> Computer tutorials >  >> Programming >> Javascript

Non-negative set subtraction in JavaScript


We have a set of integers, and a value that we need to subtract from the sum of the set.

Like here,

[4, 5, 6, 7, 8] − 25

If we subtract from every number evenly, we'd get −

[−1, 0, 1, 2, 3]

However, we don't want any numbers less than 0.

Therefore, if we were writing an algorithm to do this, the negative numbers would overflow equally into the remaining numbers, and we'd now have −

[0, 0, 1, 2, 3] − 1

Making the resulting set −

[0, 0, 1 − 0.333, 2 − 0.333, 3 − 0.333]

Note that this is exactly the outcome we want.

All of the negative values overflow EVENLY into the remaining positive values.

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a sum number as the second argument.

The function should then compute the evenly subtracted and distributed array and return it.

Example

The code for this will be −

const arr = [4, 5, 6, 7, 8];
const subtract = (arr, sum) => {
   return arr.map((el, index, array) => {
      const rem = array.length − index
      const avg = sum / rem;
      const toSubtract = Math.min(avg, el);
      sum −= toSubtract;
      return el − toSubtract;
   });
};
console.log(subtract(arr, 25));

Output

And the output in the console will be −

[ 0, 0, 0.666666666666667, 1.666666666666666, 2.666666666666666 ]