Josephus problem

From Rosetta Code
Revision as of 12:39, 15 November 2012 by Keithpinson (talk | contribs) (Noted prisoners labeled 1 to n)
Josephus problem is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Josephus problem is a math puzzle with a grim description: prisoners are standing on a circle, sequentially numbered from to . An executioner walks along the circle, starting from prisoner , removing every -th prisoner and killing him. As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed. For example, if there are prisoners and , the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2.

Task Given any , find out which prisoner will be the final survivor. In one such incident, there were 41 prisoners and every 3rd prisoner was being killed (). Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale. Which number was he?

Extra The captors may be especially kind and let survivors free, and Josephus might just have friends to save. Provide a way to calculate which prisoner is at any given position on the killing sequence.

Notes

  1. You can always play the executioner and follow the procedure exactly as described, walking around the circle, counting (and cutting off) heads along the way. This would yield the complete killing sequence and answer the above questions, with a complexity of probably . However, individually it takes no more than to find out which prisoner is the -th to die.
  2. If it's more convenient, you can number prisoners from to instead. If you choose to do so, please state it clearly.
  3. An alternative description has the people committing assisted suicide instead of being executed, and the last person simply walks away. These details are not relevant, at least not mathematically.


Perl

Translation of: Perl6

<lang Perl>my @prisoner = 0 .. 40; my $k = 3; until (@prisoner == 1) {

   push @prisoner, shift @prisoner for 1 .. $k-1;
   shift @prisoner;

}

print "Prisoner @prisoner survived.\n"</lang>

Output:
Prisoner 30 survived.

Perl 6

Straightforward implementation of the executioner's algorithm: <lang Perl6>sub Execute(@prisoner is rw, $k) {

   until @prisoner == 1 {

@prisoner.=rotate($k - 1); @prisoner.shift;

   }

}

my @prisoner = ^41; Execute @prisoner, 3; say "Prisoner {@prisoner} survived."; </lang>

Output:
Prisoner 30 survived.

We don't have to use numbers. Any list will do:

<lang Perl6>my @dalton = <Joe Jack William Averell Rantanplan>; Execute @dalton, 2; say "{@dalton} survived."; </lang>

Output:
William survived.

Scala

Executioner's Solution, not Josephus'

(Prisoners labeled 1 to n) <lang scala>def executed( prisonerCount:Int, step:Int ) = {

 val prisoners = ((1 to prisonerCount) map (_.toString)).toList
 def behead( dead:Seq[String], alive:Seq[String] )(countOff:Int) : (Seq[String], Seq[String]) = {
   val group = if( alive.size < countOff ) countOff - alive.size else countOff
   (dead ++ alive.take(group).drop(group-1), alive.drop(group) ++ alive.take(group-1))
 }
 def beheadN( dead:Seq[String], alive:Seq[String] ) : (Seq[String], Seq[String]) =
   behead(dead,alive)(step)
 def execute( t:(Seq[String], Seq[String]) ) : (Seq[String], Seq[String]) = t._2 match {
   case x :: Nil => (t._1, Seq(x))
   case x :: xs => execute(beheadN(t._1,t._2))
 }
 execute((List(),prisoners))

}

val (dead,alive) = executed(41,3)

println( "Prisoners executed in order:" ) print( dead.mkString(" ") )

println( "\n\nJosephus is prisoner " + alive(0) )</lang>

Output:
Prisoners executed in order:
3 6 9 12 15 18 21 24 27 30 33 36 39 1 5 10 14 19 23 28 32 37 41 7 13 20 26 34 40 8 17 29 38 11 25 2 22 4 35 16

Josephus is prisoner 31

Python

<lang python>>>> def j(n, k): p, i, seq = list(range(n)), 0, [] while p: i = (i+k-1) % len(p) seq.append(p.pop(i)) return 'Prisoner killing order: %s.\nSurvivor: %i' % (', '.join(str(i) for i in seq[:-1]), seq[-1])

>>> print(j(5, 2)) Prisoner killing order: 1, 3, 0, 4. Survivor: 2 >>> print(j(41, 3)) Prisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15. Survivor: 30 >>> </lang>