-
-
Save waynejo/ebec8e10fffdf2037e1e88fb418e77de to your computer and use it in GitHub Desktop.
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 java.io.FileInputStream | |
import scala.annotation.tailrec | |
import scala.io.StdIn | |
case class Input(patterns: Vector[String], fourDigit: Vector[String]) | |
def is1478(digit: String): Boolean = | |
digit.length match | |
case 2 | 4 | 3 | 7 => | |
true | |
case _ => | |
false | |
def solve8_1(inputs: Vector[Input]): Int = | |
inputs.map(input => input.fourDigit.count(is1478)).sum | |
def numberMap(input: Input): Map[Set[Char], Int] = | |
val counts = "abcdefg".map(c => input.patterns.count(_.contains(c)) -> c).groupBy(_._1).view.mapValues(_.map(_._2).toSet).toMap | |
val b = counts(6).head | |
val e = counts(4).head | |
val f = counts(9).head | |
val number7 = input.patterns.find(_.length == 3).get.toSet | |
val number1 = input.patterns.find(_.length == 2).get.toSet | |
val a = number7.diff(number1).head | |
val c = counts(8).diff(Set(a)).head | |
val abcefSet = Set(a, b, c, e, f) | |
val number0 = input.patterns.find(pattern => pattern.length == 6 && abcefSet.diff(pattern.toSet).isEmpty).head | |
val g = number0.toSet.diff(abcefSet).head | |
val d = counts(7).diff(Set(g)).head | |
Map( | |
Set(a, b, c, e, f, g) -> 0, | |
Set(c, f) -> 1, | |
Set(a, c, d, e, g) -> 2, | |
Set(a, c, d, f, g) -> 3, | |
Set(b, c, d, f) -> 4, | |
Set(a, b, d, f, g) -> 5, | |
Set(a, b, d, e, f, g) -> 6, | |
Set(a, c, f) -> 7, | |
Set(a, b, c, d, e, f, g) -> 8, | |
Set(a, b, c, d, f, g) -> 9, | |
) | |
def toNumber(numbers: Map[Set[Char], Int], text: String): Int = | |
numbers(text.toSet) | |
def toNumber(numbers: Map[Set[Char], Int], texts: Vector[String]): Int = | |
texts.foldLeft(0) { (acc, x) => | |
acc * 10 + toNumber(numbers, x) | |
} | |
def solve8_2(inputs: Vector[Input]): Int = | |
inputs.map { input => | |
toNumber(numberMap(input), input.fourDigit) | |
}.sum | |
@main def solve8(): Unit = | |
val in = new FileInputStream("example8-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line && line.trim.nonEmpty) | |
.map(line => { | |
val Array(patterns, fourDigit) = line.trim.split("\\|") | |
Input(patterns.trim.split(" ").toVector, fourDigit.trim.split(" ").toVector) | |
}).toVector | |
println(solve8_1(inputs)) | |
println(solve8_2(inputs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment