This problem is known as the Josephus Problem. Fortunately I've already studied that problem. It can be solved by recursion. The recursive formula is:

j(n, k) = (j(n - 1, k) + k-1) % n + 1
j(1, k) = 1

where:

j is the Josephus Problem mathematical function
n is the number of people in the circle
k is the number of steps to go around the circle

The main idea is that, for each interaction around the circle, one person goes out, thus leaving n-1 people in it. That's the recursion part:

j(n, k) = j(n - 1, k) ...

But, for j(n - 1, k), we would solve it starting from the same first person in the circle. So we have to adjust the return of the recursion by (k-1). For example, with n = 5 and k = 3:

(i)     A B C D E -> remove C
(ii)    A B D E

In (ii), if we start from A again, we'll remove D. However, looking at (i), if we start from C, than the next one to be removed is A. From D to A, in (ii), we walk 2 steps (exactly k-1 steps). The general rule is that we will always have to walk k-1 steps to adjust the recursion.

Finally, we have to get the mod (% n) from the returning recursion because it is a circle. We sum +1 to the mod because the mod function returns a zero-based position.

Share this project:

Updates