-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* An implementation of the Josephus problem Time complexity: O(n) | ||
* | ||
* @author Micah Stairs | ||
*/ | ||
|
||
public class JosephusProblem { | ||
|
||
// Suppose there are n people in a circle and person | ||
// 0 kill the k'th person, then the k'th person kills | ||
// the 2k'th person and so on until only one person remains. | ||
// The question is who lives? | ||
// Let n be the number of people and k the hop size | ||
public static int josephus(int n, int k) { | ||
int[] dp = new int[n]; | ||
for (int i = 1; i < n; i++) dp[i] = (dp[i - 1] + k) % (i + 1); | ||
return dp[n - 1]; | ||
} | ||
|
||
public static void main(String[] args) { | ||
|
||
int n = 41, k = 2; | ||
System.out.println(josephus(n, k)); | ||
|
||
n = 25; | ||
k = 18; | ||
System.out.println(josephus(n, k)); | ||
|
||
n = 5; | ||
k = 2; | ||
System.out.println(josephus(n, k)); | ||
} | ||
} |