r/adventofcode • • Dec 07 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 7 Solutions -๐ŸŽ„-

--- Day 7: Recursive Circus ---


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!

10 Upvotes

222 comments sorted by

View all comments

Show parent comment

1

u/Smylers Dec 07 '17 edited Dec 07 '17

My part 2 Vim solution translated to Perl โ€” O(N), no tree or recursion:

my (@ready, %parent);
while (<>) {
  /^(?<program>\w+) \((?<weight>\d+)\)( -> (?<dependency>.*))?/ or die;
  my $node = {
        name => $+{program},
        own_weight => $+{weight},
        total_weight => $+{weight},
      };
  if ($+{dependency}) {
    my @child = split /, /, $+{dependency};
    $node->{unknown_dependencies} = @child;
    $parent{$_} = $node foreach @child;
  }
  else {
    push @ready, $node;
  }
}

my $wonky;
while (my $child = shift @ready) {
  my $parent = delete $parent{$child->{name}};
  $parent->{total_weight} += $child->{total_weight};
  push @{$parent->{child_weighing}{$child->{total_weight}}}, $child;
  if (--$parent->{unknown_dependencies} == 0) {
    push @ready, $parent;
    $wonky = $parent
        if keys %{$parent->{child_weighing}} > 1
            && (!$wonky || $parent->{total_weight} < $wonky->{total_weight});
  }
}

my ($bad_node, $right_total_weight);
while (my ($weight, $child) = each %{$wonky->{child_weighing}}) {
  if (@$child == 1) {
    $bad_node = $child->[0];
  }
  else {
    $right_total_weight = $weight;
  }
}
say "$bad_node->{name} should have weight ",
    $bad_node->{own_weight} - $bad_node->{total_weight} + $right_total_weight;

The algorithm's pretty much the same in both โ€” so if you understand either the Perl or the Vim, maybe you can use it to help you read t'other. @ready is the equivalent the lines beginning with a node name; %parent is the equivalent of lines beginning with one or more hyphens. Instead sorting the processed lines, the smallest unbalanced node is kept track of while iterating through @ready.