How to correct my code for solving the Josephus problem?
Here's my solution using pattern-matching:
Range[10] //. {x_, y_, z___} :> {z, x}
{5}
NestWhile[Rest @ RotateLeft @ # &, Range @ 10, Length @ # > 1 &]
{5}
FixedPoint[If[Length @ # > 1, Rest @ RotateLeft[#], #] &, Range @ 10]
Edit
Historical note: As far as I can remember, Josephus roulette (a plain treason to his companions) consisted of killing every third person.
FixedPoint[If[Length@# != 1, Rest@RotateLeft[#, 2], #] &, Range@10]
{4}
Note: The direction is important. RotateRight[]
will select another victim.
You can use Nest
and define a function so you don't have to know the number of iterations:
josephus[n_] := Nest[Rest@RotateLeft[#] &, Range@n, n - 1]
So
josephus[10]
{5}
josephus[200]
{145}