Let's say I walking on the number line starting from 0 to 5. When I reach 5, If there still distance I need to travel, I go the reverse direction, walking from 5 to 0. Examples:
- Given 3 units of distance, I reach 3.
- Given 5 units of distance, I reach 5.
- Given 6 units of distance, I reach 4.
- Given 8 units of distance, I reach 2.
- Given 10 units of distance, I reach 0.
In general, given two points, a and b, and a < b, on the number line and distance D to travel, how do I find the position of the person when D == 0.
The expression I came up with is final_pos = start_pos + distance mod (end_pos - start_pos). which fails when it does the returning.
The end position depends on the evenness of the
quotientwhendistanceis divided byb-a. If it is even then the end position isa+rwhereris the remainder whendistancedivided byb-a. Otherwise, the end position isb-r.Edit
Or you can represent as follows:
$$ \text{end position} = \frac{(a+r)\left(1+(-1)^q\right)+(b-r)\left(1-(-1)^q\right)}{2} $$
where $r$ is the remainder and $q$ is the quotient.