forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjosephus_problem.py
91 lines (68 loc) · 2.22 KB
/
josephus_problem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""
The Josephus problem is a famous theoretical problem related to a certain
counting-out game. This module provides functions to solve the Josephus problem
for n people and a step size of k.
The Josephus problem is defined as follows:
- n people are standing in a circle.
- Starting with a specified person, you count around the circle,
skipping a fixed number of people (k).
- The person at which you stop counting is eliminated from the circle.
- The counting continues until only one person remains.
For more information about the Josephus problem, refer to:
https://en.wikipedia.org/wiki/Josephus_problem
"""
def josephus_recursive(n: int, k: int) -> int:
"""
Solve the Josephus problem for n people and a step size of k recursively.
Args:
n (int): Number of people.
k (int): Step size for elimination.
Returns:
int: The position of the last person remaining.
Examples:
>>> josephus_recursive(7, 3)
3
>>> josephus_recursive(10, 2)
4
"""
if n == 1:
return 0
return (josephus_recursive(n - 1, k) + k) % n
def find_winner(n: int, k: int) -> int:
"""
Find the winner of the Josephus problem for n people and a step size of k.
Args:
n (int): Number of people.
k (int): Step size for elimination.
Returns:
int: The position of the last person remaining (1-based index).
Examples:
>>> find_winner(7, 3)
4
>>> find_winner(10, 2)
5
"""
return josephus_recursive(n, k) + 1
def josephus_iterative(n: int, k: int) -> int:
"""
Solve the Josephus problem for n people and a step size of k iteratively.
Args:
n (int): The number of people in the circle.
k (int): The number of steps to take before eliminating someone.
Returns:
int: The position of the last person standing.
Examples:
>>> josephus_iterative(5, 2)
3
>>> josephus_iterative(7, 3)
4
"""
circle = list(range(1, n + 1))
current = 0
while len(circle) > 1:
current = (current + k - 1) % len(circle)
circle.pop(current)
return circle[0]
if __name__ == "__main__":
import doctest
doctest.testmod()