Thanks for the new test.
Here's my "new entry" fixed to pass it.
package Organism;
# based on http://perlmonks.org/?node_id=1197284
use strict;
use warnings;
sub count
{
return shift->{config}[0] =~ tr/1//;
}
# Input a list of [ x, y ] coords
sub insert_cells
{
my $extra = 3;
my $self = shift;
my $xl = my $xh = $_[0][0]; # find cell limits
my $yl = my $yh = $_[0][1];
for (@_)
{
my ($x, $y) = @$_;
$xl > $x and $xl = $x;
$xh < $x and $xh = $x;
$yl > $y and $yl = $y;
$yh < $y and $yh = $y;
}
my $xoffset = $xl - $extra; # get sizes and insert live cells
my $w = $xh - $xl + 2 * $extra;
my $yoffset = $yl - $extra;
my $h = $yh - $yl + 2 * $extra;
my $grid = '0' x $w x $h;
for (@_)
{
my ($x, $y) = @$_;
substr $grid, $x - $xoffset + ($y - $yoffset) * $w, 1, '1';
}
$self->{config} = [ $grid, $w, $h, $xoffset, $yoffset ];
}
# Return sorted list of cells in the Organism.
# Used for verification and testing the state of the organism.
sub get_live_cells
{
my $self = shift;
my ( $grid, $w, $h, $xoffset, $yoffset ) = @{ $self->{config} };
my @cells;
push @cells, [ $-[0] % $w + $xoffset, int( $-[0] / $w ) + $yoffset ]
while $grid =~ /1/g;
sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } @cells;
}
sub tick
{
my $self = shift;
my ( $grid, $w, $h, $xoffset, $yoffset ) = @{ $self->{config} };
# expand
$grid = join '00', '0' x ($w + 1), unpack("(a$w)*", $grid), '0' x ($
+w + 1);
$w += 2;
$h += 2;
$xoffset--;
$yoffset--;
# now get new generation
my $all = '0' x ($w + 1) . $grid;
my $sum = $all =~ tr/1/2/r;
( $sum |= substr $all, $_ ) =~ tr/1357/2468/ for
1, 2, $w, $w + 2, $w * 2, $w * 2 + 1, $w * 2 + 2; # other 7 neighb
+ors
$grid = substr $grid | $sum, 0, $w * $h;
$self->{config} = [ $grid =~ tr/1-9/000011100/r, $w, $h, $xoffset, $
+yoffset ];
}
sub new {
my $class = shift;
my %init_self = ( );
bless \%init_self, $class;
}
1;
Tweak a couple of lines and add only 5 new ones and it's fixed. I really love perl!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|