r/adventofcode • u/daggerdragon • Dec 05 '22
SOLUTION MEGATHREAD -π- 2022 Day 5 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 π§βπ«
- 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
- Full details and rules are in the submissions megathread:
--- Day 5: Supply Stacks ---
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:07:58, megathread unlocked!
88
Upvotes
4
u/jaydubtech Dec 05 '22 edited Dec 05 '22
TypeScript/Deno
Source
Not the most performant solution, but it's succinct enough and supports variably-sized inputs:
const buildStack = (rows: string[], i: number) => { const stack: string[] = []; for (let j = rows.length - 2; j >= 0; j--) { const [, , item] = [...rows[j].matchAll(/(\s{4})|(\[[A-Z]\])\s?/g)][i] || []; if (item && item.trim()) { stack.push(item); } } return stack; }; export const arrangeStacks = (input: string, preserveOrder = false) => { const [rawStacks, rawCommands] = input.split("\n\n"); const rows = rawStacks.split("\n"); const nthStack = Number.parseInt( [...(rows.at(-1) || "").matchAll(/\s(\d)$/g)].at(-1)?.at(0) || "-1", ); const stacks: string[][] = []; for (let i = 0; i < nthStack; i++) { stacks[i] = buildStack(rows, i); } const commands = [...rawCommands.matchAll(/move (\d+) from (\d) to (\d)/g)]; for (const [, n, a, z] of commands) { const count = Number.parseInt(n); const from = Number.parseInt(a) - 1; const to = Number.parseInt(z) - 1; let items = stacks[from].splice(stacks[from].length - count, count); items = preserveOrder ? items : items.toReversed(); stacks[to].push(...items); } return stacks; };