Joan Venge
Joan Venge

Reputation: 331340

What's the most elegant way to create this series of numbers?

I have N items in a collection and I am assigning values starting from 1, going down to 0 in the "center" of the list, and then going back up to 1 linearly.

So if you have 5 items:

0   1   2   3   4
1   0.5 0   0.5 1

For 6 items, 2 items in the center would have the same value 0.

0   1   2   3   4   5
1   0.5 0   0   0.5 1

Right now I have a bunch of if statements checking for index and then deciding whether the value should go up or down from 1. But it seems too messy.

Is there an elegant way to create such a series of numbers (particularly without if statements if possible)?

Upvotes: 1

Views: 91

Answers (1)

Martin R
Martin R

Reputation: 539975

If N >= 3 is odd, then

f(x) = fabs(2*x-N+1)/(N-1)

If N >= 4 is even, then

f(x) = (fabs(2*x-N+1) - 1)/(N-2)

To get totally rid of if-statements, you can write this as

f(x) = (fabs(2*x-N+1) + (N%2) - 1)/(N-2 + (N%2))

which works for even and odd values of N >= 3.

Upvotes: 5

Related Questions