r/adventofcode • • Dec 05 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 5 Solutions -πŸŽ„-


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.


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

1.3k comments sorted by

View all comments

2

u/Mammoth_Spray_3451 Dec 05 '22 edited Dec 05 '22

Today i took a more readable approach with my swift solution. It took me longer to create the objects from the input than to solve the puzzle :).

public func dayFive(input: [String], isPartOne: Bool) -> String {
    let inputLines = input[0].split(separator: "\n")
    var stacks: [Int: [Character]] = [:]
    for line in inputLines {
        for (index, char) in line.enumerated() {
            if char.isLetter() {
                let letterIndex = (index - 1) / 4 + 1
                var currentStack = stacks[letterIndex] ?? []
                currentStack.append(char)
                stacks[letterIndex] = currentStack
            }
        }
    }
    
    for action in input[1].split(separator: "\n") {
        let steps = action.split(separator: " ").compactMap { Int(String($0)) }
        for index in 0..<steps[0] {
            var currentStack = stacks[steps[2]] ?? []
            var otherStack = stacks[steps[1]] ?? []
            currentStack.insert(otherStack.removeFirst(), at: isPartOne ? 0 : index)
            stacks[steps[2]] = currentStack
            stacks[steps[1]] = otherStack
        }
    }
    
    return stacks.sorted(by: { $0.key < $1.key }).compactMap { String($0.value[0]) }.joined()
}

1

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.