Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use Math::Vector::Real;
- my ($vy,$vx) = Math::Vector::Real->canonical_base(2);
- my @Dirs = ($vy, $vx, -$vy, -$vx);
- # Read in grid, adding sentinel ~s to right and bottom
- my @Grid = map { chomp; [split(//), '~'] } <>;
- push( @Grid, [('~') x $Grid[0]->@*] );
- sub grid_at ($) { my $p = shift; return ($Grid[$p->[0]][$p->[1]]) }
- sub print_grid { say "\t", join( '', @$_ ) foreach (@Grid); }
- my $part1 = 0;
- my %visited;
- foreach my $y (0 .. $#Grid - 1) {
- foreach my $x (0 .. $Grid[0]->$#* - 1) {
- my $start = V($y,$x);
- next if ($visited{$start});
- my $plant = grid_at($start);
- my $area = 0;
- my $inner = 0;
- my @field = ($start);
- while (my $pos = shift @field) {
- next if ($visited{$pos});
- my @neigh = grep { grid_at($_) eq $plant } map { $pos + $_ } @Dirs;
- $inner += scalar @neigh;
- $area++;
- $visited{$pos}++;
- push( @field, @neigh );
- }
- $part1 += $area * (4 * $area - $inner);
- }
- }
- say "Part 1: $part1";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement