0

So I'm attempting a coding exercise, and I can't seem to find the problem. I need to pull the median from an array. If the array is an even length, I need the average of two values.

const N = parseInt(readline());
var inputs = readline().split(' ');
for (let i = 0; i < N; i++) {
    const X = parseInt(inputs[i]);
}

var arr = inputs.sort((a, b) => a - b);
if (arr.length % 2 === 0)
{
    console.error(arr);
    console.error(arr[arr.length / 2 - 1]);
    console.error(arr[arr.length / 2]);
    var a = arr[arr.length / 2 - 1];
    var b = arr[arr.length / 2];
    var ans = (a + b) / 2;
    console.log(ans);
}
else console.log(arr[Math.floor(arr.length/2)]);

CONSOLE OUTPUT: [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ] 5 6 28

So from the console output, my array is sorted properly. Next, I'm pulling out the two medians correctly. My a is indeed 5, and my b is indeed 6. But adding them with (a + b) / 2 suddenly turns into 28... Why?

2
  • because a and b is strings 56/2=28 Commented Mar 11, 2019 at 4:46
  • element in your arr is String. So "5"+"6" = "56" -> 56/2 = 28 Commented Mar 11, 2019 at 4:53

3 Answers 3

3

Variables a and b are being treated as strings and concatenated, then the division happens: '5' + '6' becomes 56 and dividing them by 2 results in 28. So you need to coerce them into numbers before doing the addition:

 var ans = (+a + +b) / 2;

Appending a arithmetic operator before the variables will coerce them into numbers and then you can add them.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh man, what an eye-opener for JavaScript (and coding practice in general). Thanks. I'll be more careful of this in the future.
2

dude u are adding two strings i.e. '5' + '6' which makes it 56 divide by 2 = 28 (Yes JS is crazy). Just use parseInt,

var ans = (parseInt(a, 10) + parseInt(b, 10)) / 2;

Comments

0

It is seems you are adding Strings together. It is essentially taking the charCode rather than the Number value ex: '1'.charCodeAt(0)

I solved this by using .map on the Array of inputs:

const N = parseInt(readline());
var inputs = readline().split(' ').map(function(num) { return parseInt(num); });

var arr = inputs.sort((a, b) => a - b);
if (arr.length % 2 === 0)
{
    console.error(arr);
    console.error(arr[arr.length / 2 - 1]);
    console.error(arr[arr.length / 2]);
    var a = arr[arr.length / 2 - 1];
    var b = arr[arr.length / 2];
    var ans = (a + b) / 2;
    console.log(ans);
}
else console.log(arr[Math.floor(arr.length/2)]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.