Sha256: c7da645855899b323ce4809d8fdca99cb173358e4df19e6613f269915e6bb22d

Contents?: true

Size: 1.28 KB

Versions: 323

Compression:

Stored size: 1.28 KB

Contents

package Example;

use strict;
use warnings;

sub count_adjacent_bombs {
    my $board = shift;

    my @lines = split "\n", $board;

    # All input lines have same length
    my $length = length( $lines[0] );
    die "ArgumentError" if grep { length != $length } @lines;

    # The board consists of legal characters
    my @board = grep { /[-+| *]/ } map { split // } @lines;
    die "ArgumentError" if @board < @lines * $length;

    # The borders are sane
    /^\+\-+\+$/ or die "ArgumentError" for @lines[0, -1];
    /^\|.+\|$/  or die "ArgumentError" for @lines[1 .. -2];

    my $translate = sub { $_[0] * $length + $_[1] };

    my $count_bombs = sub {
        my($row, $col) = @_;

        $row -= 2;
        return grep { $board[$_] eq "*"              }
               map  { $translate->( @$_ )            } 
               map  { $row++; map { [$row, $_] } @$_ }
                      ( [$col-1, $col, $col+1] ) x 3;
    };

    foreach my $row ( 1 .. @lines-1 ) {
	foreach my $col ( 1 .. $length-1 ) {
	    my $idx = $translate->($row, $col);
	    next unless $board[$idx] eq " ";
	    $board[$idx] = $count_bombs->($row, $col) || " ";
	}
    }

    return( join "\n",
            map { join '', @board[$_ .. $_+$length-1] }
            map { $_ * $length } 0 .. @lines-1
	  ) . "\n";
}

1;

Version data entries

323 entries across 323 versions & 1 rubygems

Version Path
trackler-2.0.6.27 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.26 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.25 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.24 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.23 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.22 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.21 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.20 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.19 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.18 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.17 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.16 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.15 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.14 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.13 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.12 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.11 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.10 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.9 tracks/perl5/exercises/minesweeper/Example.pm
trackler-2.0.6.8 tracks/perl5/exercises/minesweeper/Example.pm