Josephus Algorithm
Josephus Algorithm
Algorithm
The problem
According to the legend, during the Great Jewish Revolt against the
Romans, a group of 40 Jewish soldiers found themselves trapped in
a cave.
A Let len(Qc) = n
l
Let r the distance to choose a player that will die
(Note: In common or popular J.A , r=1)
o
enqueue (Qc,i)
Let x=s where s is the start index Pi starts J.A
r P = x - 1
i
while len(Qc)>1 :
u = P + r % len(Qc)
t if u==P then
h u = u+1
P = u % len (Qc)
m Dequeue (Qc)
P = u % len(Qc)
Sea Qc una cola circular.
A Sea len(Qc) = n.
l
Sea r la distancia para elegir un jugador que morirá.
o encolar(Qc, i)
t
u = P + r % len(Qc)
si u == P entonces
m u = u + 1
o P = u % len(Qc)
desencolar(Qc)
P = u % len(Qc)
1.
Let r = 3
P1 02 03
start P1
0 1
5 P2
P= 0
P6 u= 0+3%6 = 3
2
3==0 ? No
4
P3 P= 3%6 = 3
P5 Dequeue
3
P4 P= 3%5 = 3
2.
P1 02 03
P= 3
0
1 u= 3+3%5 =
P2 6%5 = 1
P6 1==3 ? No
Dequeue
4
2 P= 1%5 = 1
P3
P5 3 P= 1%4 = 1
3.
P1 02 03
P= 1
0
1 u= 1+3%4 = 4%4 = 0
4==1 ? No
P3 P= 0%4=0
Dequeue
P6 P= 0%3 = 0
3 2
P5
4.
P3 02 P= 0 03
u= 0%3 = 3%3 = 0
0 0==0 ? sí
1 u=u+1 u=1
P5 P= 1%3=1
Dequeue
P6 P= 1%2 = 1
2
5.
0 02 P= 1 03
u= 1+3%2 = 4%2 = 0
0==1 ? no
P6 P3 P= 0%2=0
Dequeue
P= 0%1 =0
1
s(6) =P6
r=3
Practice Exercise
s(7) =P1
r=2