Salutations.
I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.
So, next in this series is Sum of Numbers. In this specific problem, it's more math than coding. See, you need to calculate an area. In this graph, for example, we show all values between -5 and 4:
You can use integration if you so desired, but there's a simpler route. Since we're dealing with linear functions, we can search for the median and multiply for the range:
So we just need to insert that equation in the code. It starts like this:
function getSum(a, b)
{
//Good luck!
}
function getSum(a, b)
{
let sum = (b ** 2 - a ** 2 + b + a ) / 2 ;
return sum;
}
We test it and:
But why? I know the equation is correctly simplified, so... Oh. This is the problem:
getSum(a, b)
(a,b)
in exactly that order. It works if the input is (-5,4)
, but not if it's (4,-5)
. Fix? You could code an "if" statement for both situations. I won't do it like that though. I'll do this:
if (a > b){
let c = a;
a = b;
b = c;
}
And so, we put together everything:
function getSum(a, b)
{
if (a > b){
let c = a;
a = b;
b = c;
}
let sum = (b ** 2 - a ** 2 + b + a ) / 2 ;
return sum;
}
Somewhat decent, easy for the reading.
Cya. Drink water 💧💧💧.
Top comments (0)