Skip to content

Instantly share code, notes, and snippets.

@JavadocMD
Last active December 14, 2022 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavadocMD/e3bcb6de646442159da0dfe3c9b01e0b to your computer and use it in GitHub Desktop.
Save JavadocMD/e3bcb6de646442159da0dfe3c9b01e0b to your computer and use it in GitHub Desktop.
A solution to Advent of Code 2022 Day 1 using Akka Streams.
/*
Copyright 2022 Tyler Coles (javadocmd.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import akka.actor.ActorSystem
import akka.stream.FlowShape
import akka.stream.IOResult
import akka.stream.scaladsl.FileIO
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Framing
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source
import akka.stream.stage.GraphStage
import akka.util.ByteString
import java.nio.file.Path
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success
/** Assumes we have the puzzle input in a resource file called "Day01.input.txt". */
object Day01AkkaStreams:
final def main(args: Array[String]): Unit =
implicit val system = ActorSystem("Day01AkkaStreams")
implicit val exec = system.dispatcher
// Stream the lines from the input...
readLines("Day01.input.txt")
// compute the sum of calories held by each elf
.via(groupAndSum)
// compute the top three sums
.via(new TopThree)
// collect to a Seq
.runWith(Sink.seq)
// print the results
.andThen {
case Success(Seq(a, b, c)) =>
// Part 1: the number of calories carried by the elf with the most calories
println(a)
// Part 2: the sum of the number of calories carried by the three elves with the most calories
println(a + b + c)
case Success(x) => println(s"Error: Result was an unexpected shape: $x")
case Failure(e) => e.printStackTrace()
}
.andThen { _ => system.terminate() }
/** Source which reads input lines from the named resource file. */
def readLines(resource: String): Source[String, Future[IOResult]] =
val inputPath = Path.of(getClass.getClassLoader.getResource(resource).toURI())
FileIO
.fromPath(inputPath)
.via(Framing.delimiter(ByteString("\n"), maximumFrameLength = 1024, allowTruncation = true))
.map(_.utf8String)
/** Flow which forms groups by splitting on blank lines and emits the sum of each group. */
val groupAndSum = Flow[String]
.splitWhen(_ == "")
.filter(_ != "")
.map(_.toInt)
.reduce(_ + _)
.mergeSubstreams
/** Flow which reduces a stream of Ints to its maximum three values. When the input stream completes, outputs the
* three values.
*/
class TopThree extends GraphStage[FlowShape[Int, Int]]:
import akka.stream.{Inlet, Outlet, Attributes}
import akka.stream.stage._
val in = Inlet[Int]("TopThree.in")
val out = Outlet[Int]("TopThree.out")
override val shape = FlowShape(in, out)
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape):
// Our state -- the current top three values seen.
// We know we will have at least three values and that none are negative, so it's safe to use 0 as a placeholder.
private var top = Vector(0, 0, 0)
setHandler(
out,
new OutHandler:
override def onPull(): Unit = pull(in)
)
setHandler(
in,
new InHandler:
override def onPush(): Unit = {
val n = grab(in)
top = top.indexWhere(_ < n) match
case 0 => Vector(n, top(0), top(1))
case 1 => Vector(top(0), n, top(1))
case 2 => Vector(top(0), top(1), n)
case _ => top
pull(in)
}
override def onUpstreamFinish(): Unit = {
emit(out, top(0))
emit(out, top(1))
emit(out, top(2))
completeStage()
}
)
end createLogic
end TopThree
@JavadocMD
Copy link
Author

Scala 3.2.1 with dependency com.typesafe.akka::akka-stream:2.7.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment