Created
June 19, 2012 20:42
-
-
Save vcwu/2956429 to your computer and use it in GitHub Desktop.
Solving the Josephus problem via recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #CS352 Homework 2, Summer '12 | |
| #Victoria Wu | |
| #Josephus Problem | |
| #----------------- | |
| #N people are in a circle, with first person (1) holding a hot potato. | |
| #After M passes of the potato, the person holding the potato is out, and the | |
| #game continues with the next person in line picking up the potato. | |
| #Continue until one person remains. Who will be the victor, given (N>0, M>=0)? | |
| #Number the people from 0 to N-1 | |
| #kill(people-1, passes) is the position of the survivor in the next | |
| #iteration of the circle. | |
| #kill(people-1, passes) + passes is the position of the NEXT person who is out. | |
| #The last person who would have been out is the winner. This function returns the | |
| #last person to be "out", thus the minus one to find the winner. | |
| def kill(people, passes): | |
| #If there is one person left, no need to continue. | |
| if people ==1: | |
| return 0 | |
| return ((kill(people-1,passes)+passes) % people ) | |
| people = int(raw_input("Please enter how many people (N) :")) | |
| passes = int(raw_input("Please enter number of passes (M) :")) | |
| winner = kill(people, passes)-1 | |
| if winner < 0: | |
| winner = people | |
| print "Player %d wins!" %(winner) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment