DESCRIPTION:
We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.
Examples
sumAll([1, 4]) `should return 10`.
sumAll([10, 5]) `should return 45`.
My approach for solving this problem:
- find the min and max value in the array.
- fill the array with range from min to max.
- if not return sliced str with num length.
- get the summation of the array with reduce().
My solution:
function sumAll(arr) {
const minNumber = Math.min(...arr);
const maxNumber = Math.max(...arr);
return new Array(maxNumber - minNumber + 1)
.fill()
.map((num,index)=> minNumber+index)
.reduce((perv,num) => perv + num)
}
sumAll([1, 4]);
Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!
Follow Muhmmad Awd on
If you have any questions or feedback, please feel free to contact me at
Top comments (22)
My approach, based on the fact that the sum from
0βn
is equal to(n/2)(n+1)
:(Could be made shorter by not copying the original array, but I wanted to avoid mutation)
With mutation (and more code golf):
thank you, Relly for your interest!
This works fast too when you pass in:
sumAll(7, 80000)
I'm suck at Math; I hope to be become good like that someday.
I think you're awesome at Javascript, and I need to learn how to use fill(), map(), and reduce() properly. I'm new at Javascript, so your posts are very inspiring.
Relly, glad to hear that. you can check freecodecamp.com to learn more
Try and be amazed:
this is a pattern ?
I belive that's just a basic math equation.
Yeah, but I mean is it design pattern.
Nah. It's math. The basic idea is that you can calculate the sum of all integers from 1 to n using n*(n+1)/2
I need to focus on math and learn how use it because better with BigO
I'm not very good at math. I just happen to know some of the more usual stuff like exactly this one.
Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!
Another one (no mutation):
great but it's seemed little complex, right? I more into simple solutions
It's interesting you would say that, as your solution is actually the most complex (timewise) here at
O(N)
. The simplest I can now think of is a small reworking of @donnywi solution (which in itself is a slight mathematical simplification of others here):I suspect the way I wrote my code in posts here may have made it look more complex than it is, as it doesn't really explain itself. Sorry, my brain often tends to work in terse, code-golf like code.
yes, I know my code was the worst, but it easier to read than yours, I should study the math section again, because I didn't Relly use Math methods expect min, max and random.
This is a good use of the arrow function. π