Compute the distance between two elements in a ring

935 Views Asked by At

Given a ring of size $n = 2^m$, starting with element $0$ to element $n-1$, what general formula gives the distance between two arbitrary elements $i$ and $j$? Note that the distance between the elements $0$ and $n-1$ is $1$.

There are a few cases...

  • Assume for instance that $i>j$ and $|i-j|\leq\frac{n}{2}=2^{m-1}$, we then have $distance_{n}(i,j) = |i-j|$

  • But for $\frac{n}{2} < |i-j| \leq n-1$, we need another formula. For e.g. let $n = 8$, then the distance between $1$ and $7$ is $1$, not $|7-1|=6$

What is the general, one-line formula for this problem?

Thank you!

1

There are 1 best solutions below

0
On BEST ANSWER

Answer: $distance_{n}(i,j) = \min ( |i-j|,n-|i-j|)$