Wednesday, December 14, 2016

Given array and n, get an index from circular array

When there is an array that indexed from 0, it count from 0 as 1, 1 as 2, and so forth. When it reaches the end of the array, it goes to the first again to count.
Given a string array and integer n, return the index of array that count to n.
Let's look at some examples.

Array: {a,b,c,d,e,f}
n: 6
if we start with a, then it return 5 ( because f is at index 5)

n: 20
if we start with a, then it return 1 ( because b is at index 1)

So, the index we are looking is (start + (n - 1)) % (size of array);
start 0, n=6, (0+5) %  6 = 5
start 0, n=20, (0+19)% 6 = 1

No comments:

Post a Comment