1
votes

I realize that a similar question has been asked before.

But as per this coding challenge, I need to return the sum of the "min array" (smallest 4 numbers) and "max array" (largest 4 numbers) on the same line as two numbers separated by a space. Not as an array, string, or object.

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)

I have:

function miniMaxSum(arr) {
  arr = arr.sort((a, b) => a - b);
  let smallest = arr.slice(0, -1);
  let largest = arr.slice(1, arr.length);
  let first = Number(smallest.reduce((a, b) => a + b));
  let second = Number(largest.reduce((a, b) => a + b));
  
  return first + " " + second;
}

And when I return first and second, they return as strings instead of numbers, I'm assuming that this is because I've added the + " " + in-between them.

So then how do I return them as numbers with a space in-between?

I also tried return Number(first) + " " + Number(second); but it doesn't seem to matter, they still return as a string.

Similarly, storing the sums in an object:

function miniMaxSum(arr) {
  arr = arr.sort((a, b) => a - b);
  let smallest = arr.slice(0, -1);
  let largest = arr.slice(1, arr.length);
  let first = Number(smallest.reduce((a, b) => a + b));
  let second = Number(largest.reduce((a, b) => a + b));
  let object = {first, second};
  return Object.values(object);
}

also returned the values as an array.

1
10 14 is a string. That's it. There's nothing you can do to change that. Period. - Jack Bashford
Okay. Know why my code is failing on HackerRank then? hackerrank.com/challenges/mini-max-sum/… - HappyHands31

1 Answers

2
votes

You can't return them - if you look at the testing code:

miniMaxSum(arr);

It doesn't log the result - just runs your code. Logging the result instead works perfectly:

console.log(first + " " + second);