Skip to content
Advertisement

How to start a for loop from the end of a vector, and at the value 0 do something

I have to start looping a vector from its end to zero. When I meet the value 0 I need to replace it with the sum of the three previews values. The exception will be for the first zero met, I need just to sum the previous two values.

e.g.

JavaScript

Expected result:

JavaScript

Code

JavaScript

The code is not working. Where am I wrong?

Advertisement

Answer

You can avoid index errors with sum(v[i+1:i+4]). You have to compare each element (if v[i] == 0) not the whole list.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement