Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created December 31, 2021 13:11
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 waynejo/a43eecaa23bcdaa4ffedd8a0289dc13e to your computer and use it in GitHub Desktop.
Save waynejo/a43eecaa23bcdaa4ffedd8a0289dc13e to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.annotation.tailrec
import scala.io.StdIn
def flip(inputs: Vector[Char]): Vector[Char] =
inputs.map { v => if v == '0' then '1' else '0' }
def binaryToInt(binary: Vector[Char]): Int =
Integer.parseInt(binary.mkString(""), 2)
def solve3_1(inputs: Vector[String]): Int = {
val gammaRate = inputs.transpose.map { arr =>
if (arr.count('0' == _) < arr.count('1' == _)) '1' else '0'
}
val epsilonRate = flip(gammaRate)
binaryToInt(gammaRate) * binaryToInt(epsilonRate)
}
def bitCriteriaOfOxygenGeneratorRating(inputs: Vector[Char]): Char = {
if inputs.count('0' == _) <= inputs.count('1' == _) then '1' else '0'
}
def bitCriteriaOfCo2ScrubberRating(inputs: Vector[Char]): Char = {
if inputs.count('0' == _) <= inputs.count('1' == _) then '0' else '1'
}
@tailrec
def findLifeSupportRating(inputs: Vector[String], bitCriteria: Vector[Char] => Char, index: Int = 0): Int = {
if 1 == inputs.size then
binaryToInt(inputs.head.toVector)
else
val criteriaBit = bitCriteria(inputs.transpose.toVector(index))
val nexInputs = inputs.filter(_(index) == criteriaBit)
findLifeSupportRating(nexInputs, bitCriteria, index + 1)
}
def solve3_2(inputs: Vector[String]): Int = {
val oxygenGeneratorRating = findLifeSupportRating(inputs, bitCriteriaOfOxygenGeneratorRating)
val co2ScrubberRating = findLifeSupportRating(inputs, bitCriteriaOfCo2ScrubberRating)
oxygenGeneratorRating * co2ScrubberRating
}
@main def solve3(): Unit =
val in = new FileInputStream("example3-2.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine())
.takeWhile(line => null != line && line.trim.nonEmpty)
.toVector
println(solve3_1(inputs))
println(solve3_2(inputs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment