Skip to content

Instantly share code, notes, and snippets.

@terdong
Last active January 30, 2021 04:35
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 terdong/20cb38dc3815218b17988a73c4eb5330 to your computer and use it in GitHub Desktop.
Save terdong/20cb38dc3815218b17988a73c4eb5330 to your computer and use it in GitHub Desktop.
import scala.collection.mutable
object Day9 extends App {
val preamble = 5
val sampleArray: Array[Long] = Array(35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576)
findInvalidNumber(preamble, sampleArray)
def findInvalidNumber(preamble:Int , sampleArray: Array[Long]) = {
var firstIndex = 0
var lastIndex = preamble
val errorQueue = mutable.Queue[Long]().empty
sampleArray.drop(preamble).foreach { number =>
val set = mutable.HashSet[Long]().empty
val slicedArray = sampleArray.slice(firstIndex, lastIndex).sorted
val sumList = slicedArray.zipWithIndex.flatMap { n: (Long, Int) =>
slicedArray.patch(n._2, Nil, 1).map(n._1 + _)
}
set ++= sumList
if (!set.contains(number)) {
errorQueue.addOne(number)
}
firstIndex += 1
lastIndex += 1
}
println(errorQueue.mkString(","))
errorQueue.front
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment