r/adventofcode • • Dec 06 '15

SOLUTION MEGATHREAD --- Day 6 Solutions ---

--- Day 6: Probably a Fire Hazard ---

Post your solution as a comment. Structure your post like the Day Five thread.

22 Upvotes

171 comments sorted by

View all comments

2

u/Aneurysm9 Dec 06 '15

Perl again, going for speed...

my $lights = {};

foreach my $line (@data) {
	chomp $line;
	$line =~ /^(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)/;
	my $instr = $1;
	my ($x1, $y1) = ($2, $3);
	my ($x2, $y2) = ($4, $5);

	my $x = $x1;

	while ($x <= $x2) {
		my $y = $y1;
		while ($y <= $y2) {
			if ($instr =~ m/on/) {
				$lights->{$x}{$y} = 1;
			}
			if ($instr =~ m/off/) {
				$lights->{$x}{$y} = 0;
			}
			if ($instr =~ m/toggle/) {
				$lights->{$x}{$y} = 0 unless defined $lights->{$x}{$y};
				$lights->{$x}{$y} = 1 - $lights->{$x}{$y};
			}
			$y++;
		}
		$x++;
	}
}

foreach my $x (keys %$lights) {
	foreach my $y (keys %{$lights->{$x}}) {
		$count++ if $lights->{$x}{$y};
	}
}

Allowing the intensity to go below 0 and then not incrementing $y in the right place cost me about 90s on part 2. Speed kills...

my $lights = {};

foreach my $line (@data) {
	chomp $line;
	$line =~ /^(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)/;
	my $instr = $1;
	my ($x1, $y1) = ($2, $3);
	my ($x2, $y2) = ($4, $5);

	my $x = $x1;

	while ($x <= $x2) {
		my $y = $y1;
		while ($y <= $y2) {
			$y++;
			$lights->{$x}{$y} = 0 unless defined $lights->{$x}{$y};
			if ($instr =~ m/on/) {
				$lights->{$x}{$y} += 1;
			}
			if ($instr =~ m/off/) {
				next if $lights->{$x}{$y} == 0;
				$lights->{$x}{$y} -= 1;
			}
			if ($instr =~ m/toggle/) {
				$lights->{$x}{$y} += 2;
			}
		}
		$x++;
	}
}

foreach my $x (keys %$lights) {
	foreach my $y (keys %{$lights->{$x}}) {
		$count += $lights->{$x}{$y} if $lights->{$x}{$y};
	}
}