Calculating distances mod N

Python 2, 53 bytes

lambda n,l:sum((b-a+n/2)%n-n/2for a,b in zip(l,l[1:]))

Super straight forward answer. I wonder if there is a shorter way.


Mathematica, 30 bytes

Tr@Mod[Differences@#2,#,-#/2]&

This is an anonymous function which takes two arguments. Example usage:

Tr@Mod[Differences@#2,#,-#/2]&[3, {0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1}]
(* 4 *)
Tr@Mod[Differences@#2,#,-#/2]&[10, {5, 2, 8, 9, 5}]
(* -10 *)

This works by taking the Differences between successive elements, wrapping them to the range -n/2 to +n/2 with Mod and its offset parameter, then taking the total with Tr (matrix trace, sum of diagonal elements).


Note that even ungolfed it's only 43 bytes!

f[n_, l_] := Total[Mod[Differences[l], n, -n/2]]

J, 24 bytes

[+/@(]-(>-:)~*[)[|2-~/\]

Usage:

   f=:[+/@(]-(>-:)~*[)[|2-~/\]

   3 f 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
4

   10 f 5 2 8 9 5
_10

Will try to golf more and add some explanation after that.

Try it online here.

Tags:

Math

Code Golf