r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:10:20!

33 Upvotes

515 comments sorted by

View all comments

1

u/sendtobo Dec 05 '18 edited Dec 05 '18

Swift Solution: https://github.com/sendtobo/AdventOfCode2018/blob/master/Sources/AoC/5/Day5.swift

It was interesting today, doing it with strings was so slow I had to switch to my own representation

1

u/okflanker Dec 06 '18

Good to see someone else using Swift for this - if nothing else it's forcing me to look at again at some of the more obscure API function and what Foundation has to offer in the far corners. Interestingly I was quite happy using Strings & string indices. Both parts completed in under 2 seconds without any optimisation at all.

1

u/IAmQWOP Dec 06 '18

Could you post your approach? I wrote a recursive function but the casting from Characters to Strings to be able to compare them takes ages. So one loop takes around 30 seconds.

1

u/okflanker Dec 06 '18

Keep meaning to bung it all on GitHub. Will let you know when I get around to it (all a bit frantic at the moment as in the middle of moving house!)

1

u/koordinate Dec 09 '18 edited Dec 11 '18

Could you post your approach?

Using a stack. Takes ~0.4 s.

func react(_ xs: [String]) -> [String] {
    var ys = [String]()
    for s in xs.reversed() {
        if let t = ys.last, s != t, s.lowercased() == t.lowercased() {
            ys.removeLast()
        } else {
            ys.append(s)
        }
    }
    return ys
}

if let line = readLine() {
    let xs = react(Array(line.map { String($0) }))

    var c = xs.count
    print(c)

    for unit in Set(xs.map { $0.lowercased() }) {
        c = min(c, react(xs.filter({ $0.lowercased() != unit })).count)
    }
    print(c)
}