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/sim642 Dec 05 '18 edited Dec 05 '18

My Scala solution.

Initially I wrote a horrendous and slow immutable reactor for part 1. After completing both parts I optimized it to use zipper-like approach to Scala's immutable List to get the proper performance and allow going back.

Edit: Realized that my function was actually just a foldLeft.

1

u/[deleted] Dec 05 '18

Just a heads up, the reverse isn't necessary since the problem doesn't depend on direction. I included in my original solution too though

package aoc

object Problem5 extends Base("input5.txt") {
  def reactPolymer(string: String): String = string.reverse.foldLeft[List[Char]](Nil) {
    case (h :: t, char) if h != char && h.toUpper == char.toUpper => t
    case (acc, char) => char :: acc
  }.mkString

  val input = lines.head

  val reduced = reactPolymer(input)

  println(s"Part 1: ${reduced.length}")

  val smallest = ('a'.toInt to 'z'.toInt).map { charInt =>
    val char = charInt.toChar
    reactPolymer(input.filter(_.toLower != char)).length
  }.min

  println(s"Part 2: $smallest")
}

1

u/sim642 Dec 05 '18

Good point about not needing the reversal because we only care about the length. I didn't realize this because I had already written tests to check the correctness of the actual reaction process on the strings for which I wanted it to be in the right order.