Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(min max);
- sub in_range {
- my ($pt, $range) = @_;
- return ($range->[0] <= $pt <= $range->[1]);
- }
- sub try_merge {
- my ($p, $q) = @_;
- if (($q->[1] - $p->[0]) * ($q->[0] - $p->[1]) <= 0) {
- return ([min ($p->[0], $q->[0]), max ($p->[1], $q->[1])]);
- }
- return (0);
- }
- my $row = 2_000_000;
- my @ranges;
- my %beacons;
- foreach my $line (<>) {
- my ($x, $y, $bx, $by) = ($line =~ m#(-?\d+)#g);
- if ($by == $row) {
- $beacons{ $bx }++;
- }
- my $dist = abs( $x - $bx ) + abs( $y - $by );
- my $to_row = abs( $y - $row );
- my $diff = $dist - $to_row;
- if ($diff >= 0) {
- push( @ranges, [$x - $diff, $x + $diff] );
- }
- }
- @ranges = sort { $a->[0] <=> $b->[0] } @ranges;
- my @new = (shift @ranges);
- foreach my $range (@ranges) {
- my $merge = &try_merge( $new[-1], $range );
- if ($merge == 0) {
- push( @new, $range );
- } else {
- $new[-1] = $merge;
- }
- }
- my $part1 = 0;
- foreach my $r (@new) {
- $part1 += $r->[1] - $r->[0] + 1;
- foreach my $b (keys %beacons) {
- $part1-- if (&in_range( $b, $r ));
- }
- }
- print "Part 1: $part1\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement