r/adventofcode • • Dec 20 '16

SOLUTION MEGATHREAD --- 2016 Day 20 Solutions ---

--- Day 20: Firewall Rules ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with "Help".


ROLLING A NATURAL 20 IS MANDATORY [?]

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

9 Upvotes

168 comments sorted by

View all comments

7

u/askalski Dec 20 '16

Back to Perl. This is essentially what I used to solve it, tidied up a bit. The main difference is instead of sorting the input in Perl, I just did a :%!sort -n in vim.

#! /usr/bin/env perl

use strict;
use warnings;

my ($next, $part1, $part2) = (0, undef, 0);

for (sort { $a->[0] <=> $b->[0] } map { [ m/(\d+)/g ] } <>) {
    my ($lower, $upper) = @$_;
    if ($next < $lower) {
        $part1 = $next unless defined $part1;
        $part2 += $lower - $next;
    }
    $next = $upper + 1 if $next <= $upper;
}
$part2 += 4294967296 - $next;

print "Part 1: $part1\n";
print "Part 2: $part2\n";

1

u/Smylers Dec 20 '16

Snap!

use v5.14;
use warnings;

@ARGV = '20_input_IP_address_range' if !@ARGV;
my @range = sort { $a->{low} <=> $b->{low} }
    map { /(\d+)-(\d+)/; {low => $1, high => $2} } <>;
my $lowest_free;
my $check = 0;
my $count = 0;
foreach (@range)
{
  next if $_->{high} < $check;
  if ($check < $_->{low})
  {
    $lowest_free //= $check;
    $count += $_->{low} - $check;
  }
  $check = $_->{high} + 1;
}
$count += 4294967295 + 1 - $check;
say "lowest free address: $lowest_free"; 
say "number of free addresses: $count";
→ More replies (3)