summary refs log tree commit diff homepage
path: root/2023/day11.pl
blob: 4beb54bf526b8fae57964c89dae39e7e727ab9ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use strict;
use warnings;
my (@gs, @xp, @yp);
my ($x, $y) = (0, 0);
while (<>) {
	chomp;
	$x = 0;
	for (split //) {
		if ($_ eq "#") {
			push @gs, [ $x, $y ];
			$xp[$x] = 1;
			$yp[$y] = 1;
		}
		$x++;
	}
	$y++;
}
my ($w, $h) = ($x, $y);
sub expand {
	my ($f, @gs) = @_;
	my ($xe, $ye) = (0, 0);
	for (my $x = 0; $x < $w; ++$x) {
		next if defined $xp[$x];
		for (@gs) {
			$_ = [ $_->[0] + $f-1, $_->[1] ] if $_->[0] > ($x+$xe);
		}
		$xe += $f-1;
	}
	for (my $y = 0; $y < $h; ++$y) {
		next if defined $yp[$y];
		for (@gs) {
			$_ = [ $_->[0], $_->[1] + $f-1 ] if $_->[1] > ($y+$ye);
		}
		$ye += $f-1;
	}
	@gs;
}
sub dists {
	my $sum = 0;
	while (@_) {
		my $a = shift;
		for my $b (@_) {
			$sum += abs($a->[0] - $b->[0]) + abs($a->[1] - $b->[1]);
		}
	}
	$sum;
}
print dists(expand(2, @gs)), "\n";
print dists(expand(1000000, @gs)), "\n";