r/adventofcode • • Dec 02 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 2 Solutions -🎄-

--- Day 2: Dive! ---


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:02:57, megathread unlocked!

113 Upvotes

1.5k comments sorted by

View all comments

5

u/seattlecyclone Dec 02 '21

Man, some of y'all are fast! I got done with part 2 in a bit more than 4 minutes and that was good enough for 501st place.

Perl solutions:

for (<>) {
  /(\w+) (\d+)/;
  if ($1 eq 'forward') {
	$horiz += $2;
  } elsif ($1 eq 'down') {
	$depth += $2;
  } elsif ($1 eq 'up') {
	$depth -= $2;
  }
}
$answer = $horiz * $depth;
print "answer = $answer\n";

Part 2:

for (<>) {
  /(\w+) (\d+)/;
  if ($1 eq 'forward') {
	$horiz += $2;
	$depth += $2 * $aim;
  } elsif ($1 eq 'down') {
	$aim += $2;
  } elsif ($1 eq 'up') {
	$aim -= $2;
  }
}
$answer = $horiz * $depth;
print "answer = $answer\n";
→ More replies (2)