Skip to content

Commit 854b900

Browse files
authored
Add Josephus Problem Recursive Solution (TheAlgorithms#3208)
1 parent 4aa58b6 commit 854b900

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.maths;
2+
3+
/** There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
4+
*/
5+
6+
/** The rules of the game are as follows:
7+
8+
1.Start at the 1st friend.
9+
2.Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.
10+
3.The last friend you counted leaves the circle and loses the game.
11+
4.If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.
12+
5.Else, the last friend in the circle wins the game.
13+
14+
@author Kunal
15+
*/
16+
17+
public class JosephusProblem {
18+
19+
/**
20+
* Find the Winner of the Circular Game.
21+
*
22+
* @param number of friends, n, and an integer k
23+
* @return return the winner of the game
24+
*/
25+
26+
public static int findTheWinner(int n, int k) {
27+
return winner(n, k) + 1;
28+
}
29+
30+
public static int winner(int n, int k){
31+
if (n == 1){
32+
return 0;
33+
}
34+
return (winner(n -1, k) + k) % n;
35+
}
36+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
public class JosephusProblemTest {
8+
9+
@Test
10+
void testJosephusProblem(){
11+
assertEquals(3, JosephusProblem.findTheWinner(5,2));
12+
assertEquals(5, JosephusProblem.findTheWinner(6,4));
13+
}
14+
15+
}

0 commit comments

Comments
 (0)