Skip to content
Advertisement

Sum of lowest numbers that are part of an arithmetic sequence

I would like to iterate through a list of integers, calculate the sum of the lowest numbers that belongs to an arithmetic sequence with common difference 1 + the numbers that are not part of a sequence:

JavaScript

So, from mylist it would be 2 (from 2,3,4) + 10 (not part of a sequence) + 12 (from 12,13)

I’ve managed to make something work, but I could only figure out how to do it, if the list is reversed. And I am sure there is a better/cleaner solution that mine:

JavaScript

Hope someone will help me out, and that I get a little wiser in my coding journey. Thanks.

Advertisement

Answer

Keep a running sum, a running index, and iterate while it’s still a sequence:

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