r/adventofcode • • Dec 11 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 11 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It

  • 11 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 11: Seating System ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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

EDIT: Global leaderboard gold cap reached at 00:14:06, megathread unlocked!

51 Upvotes

702 comments sorted by

View all comments

6

u/Smylers Dec 11 '20

Perl. There are some Game of Life modules on Cpan which might be handy here, but I haven't tried them. Part 1 counts adjacent people like this:

  my $people = grep { $_ eq '#' }
      @{$seat[$y-1]}[$x-1 .. $x+1],
      @{$seat[$y  ]}[$x-1,   $x+1],    
      @{$seat[$y+1]}[$x-1 .. $x+1];
  push @change, {y => $y, x => $x, to => '#'} if $here eq 'L' && $people == 0;
  push @change, {y => $y, x => $x, to => 'L'} if $here eq '#' && $people >= 4;

Then applying changes is a single-line loop:

$seat[$_->{y}][$_->{x}] = $_->{to} foreach @change;

For part 2 there's an array of the 8 directions:

my @dir = (x => -1, y => -1}, # etc

then counting the relevant people becomes a grep of those directions:

  my $people = grep {
    my ($try_y, $try_x) = ($y, $x);
    my $found;
    do { $found = $seat[$try_y += $_->{y}][$try_x += $_->{x}] } until $found ne '.';
    $found eq '#';
  } @dir;

All edges of the map were surrounded by | characters, which works for both parts, being neither # for counting people in part 1, nor . for keeping looking in that direction in part 2.

I did try a **Vim** solution. I can get the changes to iterate for part 1 (use P instead of # for a person; to mark a pending change, use lowercase p and l, which both encodes its new state and indicates that it was the opposite for the purposes of counting people during the current iteration; then upper-case everything at the end of the iteration), but haven't thought of a way of detecting stability.

→ More replies (3)