Skip to content

Instantly share code, notes, and snippets.

@aero
Created April 3, 2010 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aero/354115 to your computer and use it in GitHub Desktop.
Save aero/354115 to your computer and use it in GitHub Desktop.
use MooseX::Declare;
class Person {
has 'position' => (is => 'ro', isa => 'Int');
has 'alive' => (is => 'rw', isa => 'Bool', default => 1);
has 'succ' => (is => 'rw', isa => 'Person', default => undef);
# Create a chain of people
method createChain(Int $n) {
return $self unless $n > 0;
my $succ = Person->new( position => $self->position+1 );
$self->succ($succ);
$succ->createChain($n-1)
}
# Pass on the killing message
method kill(Int $pos, Int $n, Int $remaining) {
return $self->succ->kill($pos, $n, $remaining) if !$self->alive;
return $self if $remaining == 1;
if ($pos == $n) {
$self->alive(0);
$pos = 0;
$remaining--;
}
$self->succ->kill($pos+1, $n, $remaining)
}
# Print descriptive information
method to_s() {
"Person #".$self->position.", ".($self->alive ? "alive" : "dead")
}
}
#--------------------------------------------------------------------
package main;
use strict;
use warnings;
# Circle of $n people, kill every one out of every $m
my $m = 3;
my $n = 40;
my $first = Person->new( position => 1 );
my $last = $first->createChain($n-1);
$last->succ($first);
my $winner = $first->kill(1,$m,$n);
print "Winner: ", $winner->to_s, "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment