Demo entry 3363563

Advent of Code - Day 18

   

Submitted by Matt Creenan on Dec 18, 2015 at 18:28
Language: Perl6. Code size: 1.9 kB.

#!/usr/bin/env perl6

my (%light_grid, %new_light_grid);
my Int ($x, $y, $w, $h);
constant $number_of_steps = 100;

for 1..2 -> $part {

	$x = 0;
	$y = 0;
	@*ARGS[0].IO.lines.map: {
		$x = 0;
		$_.comb.map: { %light_grid{$y+1}{$x+1} = $_ eq '#'; $x += 1; }
		$y += 1;
	}
	$w = $x;
	$h = $y;

	for 1..$number_of_steps -> $step {

		# Copy grid
		for 1..$w -> $y {
			for 1..$h -> $x {
				%new_light_grid{$x}{$y} = %light_grid{$x}{$y};
			}
		}

		for 1..$w -> $y {
			for 1..$h -> $x {
				my Int $n = number-of-neighbors-lit(%light_grid, $x, $y, $part);
				if is-cell-lit(%light_grid, $x, $y, $part) and $n != 2 and $n != 3 {
					%new_light_grid{$y}{$x} = False;
				}
				elsif not is-cell-lit(%light_grid, $x, $y, $part) and $n == 3 {
					%new_light_grid{$y}{$x} = True;
				}
			}
		}

		# Copy grid
		for 1..$w -> $y {
			for 1..$h -> $x {
				%light_grid{$x}{$y} = %new_light_grid{$x}{$y};
			}
		
		}
	}

	my Int $n = 0;
	for 1..$w -> Int $y {
		for 1..$h -> Int $x {
			$n += 1 if is-cell-lit(%light_grid, $x, $y, $part);
		}
	}
	say $n;
}

sub number-of-neighbors-lit(%light_grid, Int $x, Int $y, Int $part) {
	my @neighbors = (
		(-1, -1), (0, -1), (1, -1),
		(-1,  0),          (1,  0),
		(-1,  1), (0,  1), (1,  1));
	[+] @neighbors.map: { is-cell-lit(%light_grid, $x + $_[0], $y + $_[1], $part) ?? 1 !! 0 };

}

sub is-cell-lit(%light_grid, Int $x, Int $y, Int $part) {
	if $part == 2 {
		return True if $x == 1 and $y == 1;
		return True if $x == $w and $y == 1;
		return True if $x == $w and $y == $h;
		return True if $x == 1 and $y == $h;
	}
	return %light_grid{$y}{$x} || False;
}

sub print-grid(%light_grid, Int $w, Int $h, Int $part) {
	my Str $out = '';
	for 1..$w -> Int $y {
		for 1..$h -> Int $x {
			$out ~= is-cell-lit(%light_grid, $x, $y, $part) ?? '#' !! '.';
		}
		$out ~= "\n";
	}
	say $out;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).