+ 2
what is the reduce.function(a,b) and after the curly why there 0)?? from last 6 lines
function main() { //take the number of passed levels var levels = parseInt(readLine(),10); var points = new Array(); var count = 0; while(count<levels){ var elem = parseInt(readLine(),10); points[count] = elem; count++; } var sum = 0; sum=points.reduce(function(a,b){ return a+b; },0); //calculate the sum of points //output console.log(sum); }
2 Respostas
+ 6
reduce is like knitting.
you hava a list of numbers and get them together one after the other. In your case u get them together by a+b
But how to treat the first number? Well... the first number is joined with 0 (thats what 0 is for)
now lets have a list
1,2,3
reduce does it number by number
the start is 0
0+1 = 1
now 2
1+2 = 3
now 3
3+3 = 6
the result is 6.
now try to multiply all that numbers. Which is start and how to redefine the function?
0
Thanks