Contents
raw puzzle

Original Problem

You are given a chain of digits. The first element of the chain is the initial offset. Your task is to calculate the total offset, where offset is the sum of differences between two consecutive digits.

Example

For chain = "14839", the output should be
offsets(chain) = 6.

The total offset is calculated as follows:
1 + ((8 - 4) + (3 - 8) + (9 - 3)) = 1 + (4 - 5 + 6) = 6.

Input/Output

Solution

When we formalize the problem it reads like this:

\[ s = x_1 + (x_3 - x_2) + (x_4 - x_3) + ... + (x_n - x_{n-1}) \]

Almost all terms cancel out this way and the only remaining thing is:

\[ s = x_1 - x_2 + x_n \]

Since the data is given as a string instead of an array, we abuse JavaScripts capabilities of implicit typing to get to a minimalistic solution:

offsets = c => <br />   c[0] - c[1] - -c.slice(-1)