user2785929
user2785929

Reputation: 1035

Circular array formula used in iterating months

Currently I found that using ( starting index + size of array + 1 ) % size of array will enable me to index the circular array from 0 to N ( size of array - 1 ).

Currently I'm using this to loop months from a specific month (i.e 6 = july). But the problem is this approach also print 0 which is not part of the proper month ( 1 - 12 ). I know I can do this with just if else statement but if possible I just want to modify the ( starting index + size of array + 1 ) % size of array formula to adapt to my needs if it is possible.

Upvotes: 1

Views: 1978

Answers (4)

Markian
Markian

Reputation: 1

Here is the formula you want where N is the number of elements (12 months) indexed 1..N n is the "current" element This generates the indices (indexed from 1) of the 2 adjacent neighbours, wrapping around both ends:

( ( n-1 + N ± 1 ) % N ) + 1

the -1 in (n-1) and the final +1 on the RHS are the index adjustors

Upvotes: 0

Mark B
Mark B

Reputation: 96291

If as you say 6 = July then it seems pretty likely that 0 = January and 0 is in fact a perfectly valid value.

If you mean to say 7 = July then I would actually suggest simply making your array index from 0-11 instead of 1-12. When changing between interfacing with the user and internal you would do the conversion between zero and one based indexing.

Upvotes: 1

vicentazo
vicentazo

Reputation: 1809

If you have an incremental variable i and you do something like that i % N, you will get circular values from 0 to N-1: 0,1,2,...,(N-1),0,1,2,...,(N-1)

Therefore, if you want to start in 1, you have to add 1 to that result:

(i % N) + 1

Upvotes: 0

Ripple
Ripple

Reputation: 1265

How about:

starting index % size of array + 1

Upvotes: 1

Related Questions