2
$\begingroup$

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...

$\endgroup$

1 Answer 1

2
$\begingroup$

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$$

$\endgroup$
6
  • $\begingroup$ 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. $\endgroup$
    – BrDaHa
    Jul 16, 2013 at 3:00
  • 1
    $\begingroup$ @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) $\endgroup$ Aug 7, 2013 at 18:49
  • $\begingroup$ @Raymond Manzoni: thanks for the correction! $\endgroup$
    – Alex R.
    Aug 7, 2013 at 21:22
  • $\begingroup$ Glad it helped @Alex: (even if a little late for the OP...) $\endgroup$ Aug 7, 2013 at 21:56
  • $\begingroup$ @Raymond Manzoni Thanks! I can still use this in the future! $\endgroup$
    – BrDaHa
    Aug 8, 2013 at 6:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .