Skip to content

Instantly share code, notes, and snippets.

@horace-velmont
Created March 12, 2021 13:38
Show Gist options
  • Save horace-velmont/a5887a2d55ec53d3b45caade73a53c38 to your computer and use it in GitHub Desktop.
Save horace-velmont/a5887a2d55ec53d3b45caade73a53c38 to your computer and use it in GitHub Desktop.
advent.of.code.day.14
package day14
import java.io.FileInputStream
import scala.io.StdIn
@main def solve14_1() =
def masking(bit: String, mask: String): Double = {
mask.zipWithIndex.foldLeft(0.0)((acc, maskNext) => {
val maskVal = maskNext._1
val index = maskNext._2
if (bit.length > index) {
mask.charAt(index) match {
case 'X' =>
val value = if bit.charAt(index) == '1' then Math.pow(2, mask.length - index - 1) else 0.0
acc + value
case maskVal: Char =>
val value = if maskVal == '1' then Math.pow(2, mask.length - index - 1) else 0.0
acc + value
}
} else {
val value = if maskVal == '1' then Math.pow(2, mask.length - index - 1) else 0.0
acc + value
}
})
}
def solve(list: List[String], map: Map[Int, Long], mask: String): Map[Int, Long] = {
list match {
case Nil => map
case _ =>
val head = list.head
if head.startsWith("mask") then solve(list.tail, map, head.substring(7))
else {
val idx = head.substring(head.indexOf("[") + 1, head.indexOf("]")).toInt
val bit = head.substring(head.indexOf("=") + 2).toLong.toBinaryString
solve(list.tail, map + (idx -> masking(bit, mask).toLong), mask)
}
}
}
val in = new FileInputStream("src/example14-1.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine()).takeWhile(_ != null).toList
println(solve(inputs, Map.empty[Int, Long], "").foldLeft(0L)((a, b) => a + b._2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment