0
$\begingroup$

If I have: { 0, 1, 2, 3, 4, 5, 6 }

How can I make a function that will return the number of steps to a target element, in one direction?

To clarify, let the target be 2... Say that x = 5, and I want my function to move backwards to find 2, and return -3.. And say that x = 0, it needs to return -5.

That's where I am confused.. Normally with my understanding of algebra, something like:

5 - x = 2 ==> x = 3

That satisfies my first scenario (if I negate it).. but, the second:

0 - x = 2 ==> x = -2 ... not what I want..

Is there some simple way to do this that I am not seeing?

  • 0
    Is the answer you're looking for just to do the arithmetic mod the length of the list? So in the example you gave, $-2 \equiv 5 (\mod 7)$, so if the number is negative, you just return seven (the length in the general case) plus the number.2012-09-12

1 Answers 1

1

You can add n to x, subtract the target from x, and then take the mod n of the result where n is the number of elements. For example, if you have x=5, and your target is 2, then do 7+x=7+5=12. 12-2 = 10. 10 mod 7 = 3. And then you make the 3 negative since you are going backwards. If x=0, then do 0+7=7. 7-2 = 5. 5 mod 7 = 5, and make that negative again.