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/askalski Dec 04 '17

Perl 5. Took me a while to come up with code that I liked. In Part 2, I use 8 steps of the spiral generator to iterate over neighbor nodes. Also discovered and used the "multidimensional array emulation" feature, which would have come in handy in previous AoC years had I known about it.

Looking over some of the other solutions in this thread, Python generators were making me feel a bit envious...

#! /usr/bin/env perl

use strict;
use warnings;

chomp($_ = <>);
printf "Part 1: %d\n", part1($_);
printf "Part 2: %d\n", part2($_);

sub part1 {
	my $s = spiral();
	my ($x, $y) = (0, 0);
	($x, $y) = $s->() for 2..$_[0];
	return abs($x) + abs($y);
}

sub part2 {
	my %a = ( "0$;0" => 1 );
	my $s = spiral();
	for (;;) {
		my ($x, $y) = $s->();
		my $neighbor = spiral($x, $y);
		$a{$x,$y} += $a{$neighbor->()} // 0 for 1..8;
		return $a{$x,$y} if $a{$x,$y} > $_[0];
	}
}

sub spiral {
	my ($x, $y) = map { $_ // 0 } @_;
	my ($dx, $dy, $i, $step) = (1, 0, 0, 0);
	return sub {
		$x += $dx;
		$y += $dy;
		if ($i++ == $step) {
			$i = 0;
			$step++ if $dy;
			($dx, $dy) = (-$dy, $dx);
		}
		return wantarray() ? ($x, $y) : "$x$;$y";
	};
}

1

u/gerikson Dec 05 '17
my %a = ( "0$;0" => 1 );
[...]
return $a{$x,$y} if $a{$x,$y} > $_[0];

What sorcery is this?!

2

u/askalski Dec 05 '17

This manner of sorcery, apparently. Never knew it existed until two days ago when I stumbled upon it in the docs and had the same reaction as you.

1

u/gerikson Dec 05 '17

Huh, TIL. I remember doing funky things with split and join before grokking references.

Apparently googling "perl multidimensional array emulation" gives you instructions on how to turn it off : http://search.cpan.org/~ilmari/multidimensional-0.013/lib/multidimensional.pm

I tried using an arrayref of arrayrefs to keep track of the coordinates in this problem (instead of a hashref of hashrefs) before realizing that negative subscripts in arrays don't really work...

Nice work of re-using the spiral generator for the values around the cell in part 2, by the way!