Flavius Josephus

February 19, 2009

Flavius Josephus was a famous Jewish historian of the first century, at the time of the destruction of the Second Temple. According to legend, during the Jewish-Roman war he was trapped in a cave with a group of forty soldiers surrounded by Romans. Preferring death to capture, the Jews decided to form a circle and, proceeding around it, to kill every third person remaining until no one was left. Josephus found the safe spot in the circle and thus stayed alive.

Write a function josephus(n,m) that returns a list of n people, numbered from 0 to n-1, in the order in which they are executed, every mth person in turn, with the sole survivor as the last person in the list. What is the value of josephus(41,3)? In what position did Josephus survive?

15 Responses to “Flavius Josephus”

Depending on your interpretation of “every third person”, this question could be done a few different ways.

def josephus(n, m):
"""Returns a list of n people, numbered from 0 to n - 1,
in the order in which they are executed (every mth person
in turn). The sole surviver is the last person in the list.
>>> josephus(40, 3) # Kill every 3rd person
"""
people = range(n)
current = m - 1
executions = []
while len(people) > 1:
executions.append(people.pop(current))
current += m - 1 # Advance m people
current = current % len(people) # In case we go past the first person
return executions + [people[0]]

I’ve tried two clojure versions : one using modulus, filtering “alive” vector and an other using the trick of the front and back queue.
Both functions have the same size but the second one is clearly an order of magnitude faster.
Seems like modulus and filtering entire vector are expensive compared to only playing with head, tail and last element of front & back vectors :)

She said thewy often see people at seo keyword research tool the worst point in their careers.
”In the UK we already have the tension and pressure seo
keyword research tool they can collect. The online programs in psychology seo keyword research
tool to teach it! The parents of teenagers under the age of 80 Baroness Bakewell better
known as broadcaster Joan Bakewell faces a fight much closer to home.
Skye is not interested in the issue of same-sex attraction than my male patients.