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.

  • $\begingroup$ I like to know where the person ends up given some distance D to travel in a range [a, b], where a < b. The person goes back and forth until D == 0. Hopefully this clarifies my question. I know I'm bad at wording $\endgroup$ – Laurainmar May 9 at 6:30

The end position depends on the evenness of the quotient when distance is divided by b-a. If it is even then the end position is a+r where r is the remainder when distance divided by b-a. Otherwise, the end position is b-r.

using static System.Console;

class Program
    static void Main(string[] args)
        int a = 1;
        int b = 3;
        int distance = 7;

        int quotient = distance / (b - a);
        int remainder = distance % (b - a);
        if (quotient % 2 == 0)
            WriteLine($"end position: {a + remainder }");
            WriteLine($"end position: {b - remainder }");



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.

  • 1
    $\begingroup$ Thanks for the help!! $\endgroup$ – Laurainmar May 9 at 6:54
  • $\begingroup$ Of course you can use trigonometry as well. $\endgroup$ – Artificial Stupidity May 9 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.