Created
December 3, 2010 04:45
-
-
Save dalinaum/726591 to your computer and use it in GitHub Desktop.
ruby
This file contains 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
class Person | |
# Accessor and mutator methods | |
attr_reader :position, :succ, :alive | |
attr_writer :position, :succ, :alive | |
# Initialize | |
def initialize(pos) | |
@position = pos | |
@alive = true | |
end | |
# Stringify | |
def to_s | |
"Person \##@position, #{@alive ? 'alive' : 'dead'}" | |
end | |
# Create a linked chain of people. | |
def createChain(n) | |
return self unless n > 0 | |
@succ = Person.new(@position + 1) | |
@succ.createChain(n-1) | |
end | |
# Kill every nth person. Stop killing if I'm the last one. | |
def kill(pos,n,remaining) | |
return @succ.kill(pos,n,remaining) if !@alive | |
return self if (remaining == 1) | |
if pos == n | |
@alive = false | |
pos = 0 | |
remaining -= 1 | |
end | |
@succ.kill(pos+1,n,remaining) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment