Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(pairwise);
- $; = ',';
- my @Dirs = ([-1,-1], [-1, 0], [-1, 1],
- [ 0,-1], [ 0, 1],
- [ 1,-1], [ 1, 0], [ 1, 1]);
- sub neighbours (\@) {
- my $pos = shift;
- my @res = map { [pairwise { $a + $b } @$pos, @$_] } @Dirs;
- return( grep { (0 <= $_->[0] <= 9) && (0 <= $_->[1] <= 9) } @res );
- }
- my @Grid = map { chomp; [split //] } <>;
- my @Gridpts = map { my $y = $_; map { [$y,$_] } (0 .. 9) } (0 .. 9);
- my $flashes = 0;
- for (my $t = 1; ; $t++) {
- my %flashed;
- my @queue;
- # initial flashes
- foreach my $pt (@Gridpts) {
- push( @queue, $pt ) if (++$Grid[$pt->[0]][$pt->[1]] > 9);
- }
- # cascade with work queue
- while (my $pos = shift @queue) {
- next if (++$flashed{$pos->[0],$pos->[1]} > 1);
- foreach my $n (&neighbours( $pos )) {
- push( @queue, $n ) if (++$Grid[$n->[0]][$n->[1]] > 9);
- }
- }
- # discharge flashers
- $flashes += keys %flashed;
- foreach my $f (keys %flashed) {
- my ($y,$x) = split( /,/, $f );
- $Grid[$y][$x] = 0;
- }
- if ($t == 100) {
- print "Part 1: $flashes\n";
- }
- if (keys %flashed == 100) {
- print "Part 2: $t\n";
- last;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement