AoC day 5. Part 1 was straightforward; the naive solution that checks every ID against every range is plenty fast. For part 2 I went with a three-step approach: Read provided ranges, merge adjacent/overlapping ranges, sum up the remaining (non-overlapping) ranges.
use v5.36;<br>use List::Util qw(sum0 min);<br><br>my @ranges;<br>while (readline) {<br> chomp;<br> last if $_ eq '';<br><br> my ($lo, $hi) = m{^ (\d+) - (\d+) \z}xa<br> or die "bad input: '$_'";<br><br> push @ranges, [$lo, $hi + 1];<br>}<br><br>@ranges = sort { $a->[1] <=> $b->[1] } @ranges;<br><br>for my $i (reverse 1 .. $#[url=https://infosec.exchange/tags/ranges]ranges[/url]) {<br> if ($ranges[$i - 1][1] >= $ranges[$i][0]) {<br> $ranges[$i - 1][1] = $ranges[$i][1];<br> $ranges[$i - 1][0] = min $ranges[$i - 1][0], $ranges[$i][0];<br> splice @ranges, $i, 1;<br> }<br>}<br><br>say sum0 map $_->[1] - $_->[0], @ranges;<br>
#
AdventOfCode #
perl
Füsilier Breitlinger
Unknown parent • • •Sensitive content
Füsilier Breitlinger
Unknown parent • • •Sensitive content
@choroba @mina Yeah:
That's not even the full 32-bit range (and AoC likes to use 64-bit integers). 😦
But at least there's metacpan.org/release/ANDYA/Set…, which is nice.
Client Challenge
metacpan.orgfuzzix
in reply to Füsilier Breitlinger • • •Sensitive content
@mina I also did a sort and coalesce ... the first effort was a `Range` class which checked newly added ranges against existing ones, but I ditched that in favour of using `reduce` on a sorted set:
gist.github.com/jbarrett/67d19…
@barubary If I'm reading correctly, yours also joins adjacent ranges as well as overlapping ones?
Advent of Code day 5
GistFüsilier Breitlinger
in reply to fuzzix • • •Sensitive content
foreachloop shouldn't need it, but it seems neater this way.