0
votes

Given five positive integers, I am trying to find the minimum and maximum values that can be calculated by summing exactly four of the five integers.

This code works except with when all elements of array are the same integer:

function miniMaxSum(arr) {
  let min = Number.MAX_VALUE,
    max = 0;

  for (let i = 0; i < arr.length; i++) {
    let sum = 0;
    const foo = arr.filter((item) => item !== arr[i]);
    for (let x in foo) {
      sum += foo[x];
    }
    if (sum > max) max = sum;
    if (sum < min) min = sum;
    console.log(foo);
    console.log("Sum: " + sum);
  }
  console.log("Min: " + min + "\nMax: " + max);
}

let bar = [7, 69, 2, 221, 8974];
let baz = [769082435, 210437958, 673982045, 375809214, 380564127];
let a = [5, 5, 5, 5, 5];
miniMaxSum(bar);
miniMaxSum(baz);
miniMaxSum(a);

OUTPUT:

[ 69, 2, 221, 8974 ]
Sum: 9266
[ 7, 2, 221, 8974 ]
Sum: 9204
[ 7, 69, 221, 8974 ]
Sum: 9271
[ 7, 69, 2, 8974 ]
Sum: 9052
[ 7, 69, 2, 221 ]
Sum: 299
Min: 299
Max: 9271
[ 210437958, 673982045, 375809214, 380564127 ]
Sum: 1640793344
[ 769082435, 673982045, 375809214, 380564127 ]
Sum: 2199437821
[ 769082435, 210437958, 375809214, 380564127 ]
Sum: 1735893734
[ 769082435, 210437958, 673982045, 380564127 ]
Sum: 2034066565
[ 769082435, 210437958, 673982045, 375809214 ]
Sum: 2029311652
Min: 1640793344
Max: 2199437821
[]
Sum: 0
[]
Sum: 0
[]
Sum: 0
[]
Sum: 0
[]
Sum: 0
Min: 0
Max: 0

Why does the algorithm behave unexpectedly when elements of the given array are all the same integer value?

1
Well the filtered array will have no elements in it when you start summing. - Pointy
I'm having trouble understanding why since arr[i] should be unique to the given index, right? - plt656
No, because it is just comparing the values at those indexes, which are all the same - RobbieD
Unrelated to your bug, an approach like this seems much easier: const miniMaxSum = arr => { const sum = arr.reduce((p, c) => p + c, 0); const max = Math.max(...arr); const min = Math.min(...arr); console.log(`Max:${sum - min}\nMin: ${sum - max}`); }; - ASDFGerte
@ASDFGerte that is an elegant solution, but there must be some trivial mechanism that causes an unexpected output only when all integers in the array are the same value within my overly complex "solution". - plt656

1 Answers

0
votes

Replace this line:

const foo = arr.filter((item) => item !== arr[i]);

With this:

let foo = arr;
foo.splice(i,1);