We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

I started with the same approach, but there is a gotcha in there.
[1,2,3,4].slice(2,6) will return [3,4]. So the length of a new array is only 2. Have no idea how to fix it so I decided to use the inner cycle.

I did it pretty much the same way but slightly different.
I like your chained functions in the evaluation!

functionsolve(s,d,m){letvc=[];for(leti=0;i<s.length;i++){letc=s.slice(i,i+m);// if c the size of m and d equals c's sum then keep itif((c.length===m)&&(d===c.reduce((a,p)=>p+a,0))){vc.push(c);}}returnvc.length;}

## Birthday Chocolate

You are viewing a single comment's thread. Return to all comments →

Javascript solution (tried to simplify as much as possible):

I started with the same approach, but there is a gotcha in there.

[1,2,3,4].slice(2,6)will return[3,4]. So the length of a new array is only 2. Have no idea how to fix it so I decided to use the inner cycle.If s was a sorted array this function would fail more than it would succeed

I did it pretty much the same way but slightly different. I like your chained functions in the evaluation!

In your for loop,

`i`

should stop when`i < = l - m`

? Or would your if statement not run if the segment is less than`m`

?I like this approach; you could either set the endpoint of the

`for`

loop to`i<l-m`

or just compare`s.length==m`

in the`if`

to avoid going "off the edge."I found a very one-line functional approach, ugly but appealing all the same. I didn't put in the off-the-edge check for brevity :)

`return s.filter((e,i,a) => (a.slice(i,i+m).reduce((aa,cc)=>aa+cc)==d)).length`