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