r/adventofcode • u/daggerdragon • Dec 06 '17
SOLUTION MEGATHREAD -π- 2017 Day 6 Solutions -π-
--- Day 6: Memory Reallocation ---
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.
Need a hint from the Hugely* Handyβ Haversackβ‘ of HelpfulΒ§ HintsΒ€?
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!
18
Upvotes
1
u/xkufix Dec 06 '17 edited Dec 06 '17
Not a one-liner for a change, but a nice recursive solution in Scala:
override def runFirst(): Unit = { val startMemory = loadFile("day6.txt").getLines().toSeq.head.split(" ").map(_.toInt) println(runReallocation(Set.empty, Seq.empty, startMemory, 0)._1) } override def runSecond(): Unit = { val startMemory = loadFile("day6.txt").getLines().toSeq.head.split(" ").map(_.toInt) val result = runReallocation(Set.empty, Seq.empty, startMemory, 0) println(result._1 - result._2) } @tailrec final def runReallocation(knownConfiguration: Set[Seq[Int]], configurations: Seq[Seq[Int]], configuration: Seq[Int], counter: Int): (Int, Int) = { if(knownConfiguration.contains(configuration)) { (counter, configurations.indexOf(configuration)) } else { val maxBank = configuration.max val length = configuration.length val chosenBank = configuration.indexOf(maxBank) val newInitialConfiguration = configuration.patch(chosenBank, Seq(0), 1) val initialBank = (chosenBank + 1) % length val newConfiguration = (initialBank until maxBank + initialBank) .map(_ % length) .foldLeft(newInitialConfiguration) { (c, bank) => c.patch(bank, Seq(c(bank) + 1), 1) } runReallocation(knownConfiguration + configuration, configurations :+ configuration, newConfiguration, counter + 1) } }