Best way to find minimal difference between two values in a cyclic system?

Viewed 112

Take for example time:

If we take a 12-hour clock, we'd get the following results

  • from 1 to 5 = 4
  • from 5 to 1 = 4
  • from 11 to 1 = 2
  • from 1 to 11 = 2

What is the most efficient way to do that?

Assuming the values are doubles.

2 Answers

With mod being your cycle, and under the assumption that both input values are smaller than mod, you can use:

int x = std::min((mod + a - b) % mod, (mod - a + b) % mod);
Related