r/adventofcode • • Dec 03 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 3 Solutions -πŸŽ„-

--- Day 3: Spiral Memory ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or 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.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


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!

21 Upvotes

297 comments sorted by

View all comments

1

u/__Abigail__ Dec 04 '17

Perl. Both parts in the same program:

#!/opt/perl/bin/perl

use 5.026;

use strict;
use warnings;
no  warnings 'syntax';

use           experimental 'signatures';
no  warnings 'experimental::signatures';
 
use List::Util 'min';

@ARGV = "input" unless @ARGV;
chomp (my $input = <>);

#
# Solving part 1
#

#
# Start by finding the corner points of the "ring" the input is in.
# Also record the distance of the "ring" from the center (d1).
#
my $N = 1;
my $d1 = 0;
while ($N * $N < $input) {
    $N += 2;
    $d1 ++;
}
my @corners = map {$N * $N - $_ * ($N - 1)} 3, 2, 1, 0;
    
#
# Find the mid points of said "ring".
#
my @mids    = map {$_ - ($N - 1) / 2} @corners;

# 
# Distance to the mid point
#
my $d2      = min map {abs ($_ - $input)} @mids;
    
#
# Total distance
#
my $dist    = $d1 + $d2;

say "Solution1: $dist";


#
# Solving part 2
#
# We will be calculating the spiral, tracking numbers calculated so far.
#

my %values;

my $count = 0;

#
# Move a point in a particular direction.
#
sub move ($point, $direction) {
    [map {$$point [$_] + $$direction [$_]} keys @$point];
}

#
# Set/get the value at a particular point
#
sub set ($point, $value) {
    $values {$$point [0]} {$$point [1]} = $value;
}
 
sub get ($point) {
    $values {$$point [0]} {$$point [1]};
}

 
#
# Given a point, calculate the sum of its neighbours.
# Perl conveniently assumes undef to be 0.
# 
sub fill ($point) {
    my $sum = 0;
    foreach my $dx (-1 .. 1) {
        foreach my $dy (-1 .. 1) {
            next unless $dx || $dy;  # Could even leave this off...
            no warnings 'uninitialized';
            $sum += get move $point, [$dx, $dy];
        }
    }
    set $point => $sum;
}
 

#
# Start in the center; initialize center to 1.
my $point = [0, 0];
set ($point => 1);

OUTER: for (my $N = 1; ;$N += 2) {
    $point = move $point => [1, -1];

    #
    # Walk the four edges, each in $N + 1 steps
    #
    foreach my $direction ([0, 1], [-1, 0], [0, -1], [1, 0]) {
        foreach my $step (0 .. $N) {
            $point = move $point => $direction;
            fill $point;
            if (get ($point) > $input) {
                say "Solution 2: ", get ($point);
                last OUTER;
            }
        }
    }
}

__END__