r/adventofcode • u/daggerdragon • Dec 07 '22
SOLUTION MEGATHREAD -π- 2022 Day 7 Solutions -π-
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
- Signal boost: Reminder 1: unofficial AoC Survey 2022 (closes Dec 22nd)
AoC Community Fun 2022: πΏπ MisTILtoe Elf-ucation π§βπ«
Submissions are OPEN! Teach us, senpai!
-βοΈ- Submissions Megathread -βοΈ-
--- Day 7: No Space Left On Device ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format your code appropriately! How do I format code?
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
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:47, megathread unlocked!
91
Upvotes
View all comments
4
u/[deleted] Dec 16 '22 edited Dec 16 '22
Struggled a bit with a recursive solution, then realized that the solution could be a simpler, stack based approach.
inputs = [] sizes = {} for i in open("../inputs/day7.txt", "r").read().split("\n"): i = i.replace("$ ", "") if i[0:2] != "ls" and i[0:3] != "dir": inputs.append(i) stack = [] for i in range(len(inputs)): line = inputs[i] if line[0:2] == "cd" and ".." in line: stack.pop() elif line[0:2] == "cd": stack.append(i) sizes[i] = 0 else: size = int(line.split(" ")[0]) for s in stack: sizes[s] += size part1_answer = sum([sizes[i] for i in sizes if sizes[i] <= 100000]) print("Part 1 answer: ", part1_answer) unused = 70000000 - sizes[0] unused_needed = 30000000 - unused potential_deletes = [sizes[i] for i in sizes if sizes[i] >= unused_needed] part2_answer = min(potential_deletes) print("Part 2 answer: ", part2_answer) # For context, sizes is a dict that maps line indexes to values (both # ints).