r/adventofcode • • Dec 22 '20

SOLUTION MEGATHREAD -πŸŽ„- 2020 Day 22 Solutions -πŸŽ„-

Advent of Code 2020: Gettin' Crafty With It

  • 23:59 hours remaining until the submission deadline TONIGHT at 23:59 EST!
  • Full details and rules are in the Submissions Megathread

--- Day 22: Crab Combat ---


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:20:53, megathread unlocked!

35 Upvotes

537 comments sorted by

View all comments

Show parent comment

1

u/Smylers Dec 23 '20

Full source

Added lines:

my $player_with_max_card = max_by { max $hand[$_]->@* } 0 .. $#hand;
warn " " x $recurse . "Game " . ++(state $game) . "; player with max = $player_with_max_card\n";
return 0 if $player_with_max_card == 0;

For anybody who doesn't read Perl:

  • 0 .. $#hand is the range of indices in the @hand array, each player's hand. We have 2 players, so it's just 0, 1.
  • max_by gives us the player index with the maximum by the criteria specified in the block, setting $_ to each index in turn.
  • $hand[$_]->@* is the list of cards for the player with index $_.
  • max does what you'd expect.
  • So for each player index max finds the maximum card in their hand, then max_by returns the index of the player with the maximum maximum.

PlayerΒ 1 has indexΒ 0, so return 0 as the winner when that player has the max card.

It definitely is doing some shortcutting (and still getting the same answer, with playerΒ 2 eventually winning) β€” just not much.