/Day9.scala Secret
Last active
January 30, 2021 04:35
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.collection.mutable | |
object Day9 extends App { | |
println("Hello Day9") | |
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) | |
val quizCalculator = { (preamble: Int, sampleArray: Array[Long]) => | |
val answer1 = findInvalidNumber(preamble, sampleArray) | |
answer1.foreach(num => println(s"findInvalidNumber - the answer is ${num}")) | |
val answer2 = answer1.flatMap { | |
findEncryptionWeakness(_, sampleArray) | |
} | |
answer2.foreach(num => println(s"findEncryptionWeakness - the answer is ${num}")) | |
} | |
quizCalculator(5, sampleArray) | |
quizCalculator(25, QuizSampleCode.getSampleCodeArray) | |
def findInvalidNumber(preamble: Int, sampleArray: Array[Long]): Option[Long] = { | |
var firstIndex = 0 | |
var lastIndex = preamble | |
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)) { | |
return Some(number) | |
} | |
firstIndex += 1 | |
lastIndex += 1 | |
} | |
None | |
} | |
def findEncryptionWeakness(invalidNumber: Long, sampleArray: Array[Long]): Option[Long] = { | |
var leftIndex = 0 | |
var rightIndex = leftIndex + 1 | |
val filteredList = sampleArray.filter(_ <= invalidNumber) | |
while (leftIndex < filteredList.size) { | |
val slicedList = filteredList.slice(leftIndex, rightIndex + 1) | |
val sum = slicedList.sum | |
sum match { | |
case s if s > invalidNumber => { | |
leftIndex += 1 | |
rightIndex = +1 | |
} | |
case s if s < invalidNumber => rightIndex += 1 | |
case s if s == invalidNumber => { | |
return Some(slicedList.min + slicedList.max) | |
} | |
} | |
} | |
None | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment