The FCC intermediate algorithm sums all the numbers

Source: Internet
Author: User

The problem is dry:

We'll pass you an array with two numbers. Returns the and of the two numbers and all the numbers between them.

The smallest number is not always at the front.

function SumAll (arr) {2   return 1;  }5 SumAll ([1, 4]);

Functions that will be used

Math.max ()

Math.min ()

Array.reduce ()

Ideas:

(1) by Math.max (), math.min () extracts the maximum value in the array max and Min min;

(2) Create a new array to get the values between the minimum and maximum values;

(3) Use Array.reduce () to accumulate the new array.

Knowledge Points:

(1) Math.max (), math.min () cannot accept an array as a parameter,Math.max (array) does not exist ;

and apply is a method that fun.apply(thisArg, [argsArray]) all functions have, and fun Thisarg is equivalent to what is specified when the function is run. this

argsArrayAn array or class array object in which the array element is passed as a separate parameter to the fun function;
1  function Getmaxofarray (numarray) {2         return Math.max.apply (null, numarray); 3     }

This function can be implemented with a for loop, but it is too cumbersome.

(2) The reduce () method can operate on each element of an array, where value is the value of a single element, and sum is the cumulative value of those elements;

1 var total = Arr.reduce (function  (sum, value) {2        return sum + value; 3      }, 0);

My Code:

1 functionSumAll (arr) {2     functionGetmaxofarray (numarray) {3         returnMath.max.apply (NULL, Numarray);4     }5 6     functionGetminofarray (numarray) {7         returnMath.min.apply (NULL, Numarray);8     }9     varMax =Getmaxofarray (arr);Ten     varMin =Getminofarray (arr); One     varArray = []; A  -      for(vari = min; I <= Max; i++) { -Arr[i-min] =i; the     } -     varTotal = Arr.reduce (function(sum, value) { -         returnSum +value; -}, 0); +  -     returnTotal ; + } ASumAll ([1, 4]);

The FCC intermediate algorithm sums all the numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.