# Calculation for absolute value pattern

I have a weird pattern I have to calculate and I don't quite know how to describe it, so my apologies if this is a duplicate somewhere.. I want to solve this pattern mathematically. When I have an array of numbers, I need to calculate a secondary sequence (position) based on the index and the size, i.e.:

1 element:

index:    0
position: 1


2 elements:

index:    0  1
position: 2  1


3 elements:

index:    0  1  2
position: 2  1  3


4 elements:

index:    0  1  2  3
position: 4  2  1  3


5 elements:

index:    0  1  2  3  4
position: 4  2  1  3  5


6 elements:

index:    0  1  2  3  4  5
position: 6  4  2  1  3  5


etc....

The array can be 1-based as well if that would make it easier. I wrote this out to 9 elements to try and find a pattern but the best I could make out was that it was some sort of absolute value function with a variable offset...

-

For an array with $n$ elements, the function is:

$$f(n,k)=1+2(k-[n/2])$$

when $k\geq [n/2]$ and

$$f(n,k)=2+2([n/2]-k-1)$$

when $k<[n/2]$, where $[\cdot]$ is the floor function. Example:

$$f(5,4)=1+2(4-2)=5$$.

$$f(5,1)=2+2(1-2+1)=2$$

-
This answer, unfortunately, starts to fail when 4 elements are reached. For the 0th element in an array of 4, f(4,0) = 2+2(0-[4/2]+1) = 2+2(0-2+1) = 2-2 = 0; it should be 4. –  BrDaHa Jul 16 '13 at 3:00
@BrDaHa: The first formula (for $k\geq [n/2]$) is right. The second one should be replaced by : $$f(n,k)=2+2([n/2]-k-1)$$. (+1) –  Raymond Manzoni Aug 7 '13 at 18:49
@Raymond Manzoni: thanks for the correction! –  Alex R. Aug 7 '13 at 21:22
Glad it helped @Alex: (even if a little late for the OP...) –  Raymond Manzoni Aug 7 '13 at 21:56
@Raymond Manzoni Thanks! I can still use this in the future! –  BrDaHa Aug 8 '13 at 6:57
show 1 more comment