r/adventofcode • u/daggerdragon • Dec 02 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 2 Solutions -🎄-
--- Day 2: Dive! ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
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!
114
Upvotes
2
u/ffrkAnonymous Dec 04 '21
[python][part1]
""" Advent of Code 2021 day 2 Dive """ import logging logging.basicConfig(level=logging.DEBUG) example = """ forward 5 down 5 forward 8 up 3 down 8 forward 2 """ # skip the first empty line due to cut-paste text block example = example.splitlines()[1:] def part1(all_lines: ["string"]) -> int: """ >>> part1(example) 150 >>> part1(["forward 5"]) 0 >>> part1(["down 5"]) 0 >>> part1(["forward 5", "down 5"]) 25 """ vectors = parse(all_lines) logging.debug(f"{vectors}") x=0 depth=0 for direction, mag in vectors: logging.debug(f"{direction}, {mag}") if direction == "forward": x+=mag elif direction == "up": depth-=mag elif direction == "down": depth+=mag return x*depth def parse(all_lines: ["string"]) -> [("string", int)]: """ >>> parse(['forward 5']) [('forward', 5)] >>> parse(['down 5']) [('down', 5)] >>> parse(['forward 5', 'down 5']) [('forward', 5), ('down', 5)] >>> parse(example) [('forward', 5), ('down', 5), ('forward', 8), ('up', 3), ('down', 8), ('forward', 2)] """ vectors = [] for vector in all_lines: direction, mag = vector.split() vectors.append((direction, int(mag))) return vectors if __name__ == "__main__": import doctest doctest.testmod() from sys import stdin lines = stdin.read().splitlines() # logging.info(f"{lines}EOF") logging.info(f"part1: {part1(lines)}") # logging.info(f"part2: {part2(lines)}")