2025-12-08 17:45:23
2025-12-08 17:39:33
2025-12-08 17:39:32
6011031
Advent of Code solutions in Perl
Sensitive content
AoC day 8, part 1. Not very happy with this one. Getting a list of pairs of points ordered by distance was easy, but somehow I couldn't keep the rest of the problem straight in my head, so I just copy/pasted in the union-find code I wrote for last year's day 12. I assume the code/data structure can be simplified, but this works well enough.
#AdventOfCode #perl
use v5.36;<br><br>sub dist($p1, $p2) {<br> my $dx = $p1->[0] - $p2->[0];<br> my $dy = $p1->[1] - $p2->[1];<br> my $dz = $p1->[2] - $p2->[2];<br> $dx*$dx + $dy*$dy + $dz*$dz<br>}<br><br>my @points = map [/^(\d+),(\d+),(\d+)$/a], readline;<br><br>my @pairs = map {<br> my $p1 = $points[$_];<br> my $i = $_;<br> map $i >= $_ ? () : [$i, $_, dist($p1, $points[$_])], 0 .. $#[url=https://infosec.exchange/tags/points]points[/url]<br>} 0 .. $#[url=https://infosec.exchange/tags/points]points[/url];<br><br>@pairs = sort { $a->[2] <=> $b->[2] } @pairs;<br><br>my @regions;<br>my $representative = sub ($p) {<br> $regions[$p] //= { arity => 1 };<br> my $repr = $p;<br> while (defined(my $next = $regions[$repr]{repr})) {<br> $repr = $next;<br> }<br> while ($p != $repr) {<br> my $rr = \$regions[$p]{repr};<br> ($p, $$rr) = ($$rr, $repr);<br> }<br> $repr<br>};<br><br>my $merge = sub ($p, $q) {<br> $p = $representative->($p);<br> $q = $representative->($q);<br> return if $p == $q;<br><br> if ($regions[$p]{arity} > $regions[$q]{arity}) {<br> ($p, $q) = ($q, $p);<br> }<br><br> my $rp = $regions[$p];<br> my $rq = $regions[$q];<br> $rp->{repr} = $q;<br> $rq->{arity} += $rp->{arity};<br>};<br><br>for my $p (@pairs[0 .. 999]) {<br> $merge->($p->[0], $p->[1]);<br>}<br><br>my @arities = map $_ && !$_->{repr} ? $_->{arity} : (), @regions;<br>@arities = sort { $b <=> $a } @arities;<br><br>say $arities[0] * $arities[1] * $arities[2];<br>#AdventOfCode #perl

Füsilier Breitlinger
in reply to Füsilier Breitlinger • • •Sensitive content
#AdventOfCode #perl