-
-
Save waynejo/a769c7af633f7b49052303c7d9bd1b24 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.io.StdIn | |
case class Card(winningNumbers: Vector[Int], numbers: Vector[Int]): | |
def matchCount(): Int = | |
winningNumbers.intersect(numbers).size | |
object Card { | |
def apply(line: String): Card = | |
val numbers = line.trim.split(" ").map(_.trim).filter(_.nonEmpty).toVector | |
val (winningNumbers, normalNumbers) = numbers.splitAt(numbers.indexOf("|")) | |
Card(winningNumbers.drop(2).map(_.toInt), normalNumbers.drop(1).map(_.toInt)) | |
} | |
def solve4_1(cards: Vector[Card]): Int = | |
cards.map { card => | |
if (card.matchCount() == 0) 0 else 1 << (card.matchCount() - 1) | |
}.sum | |
def solve4_2(cards: Vector[Card]): Int = | |
val cardCounts: Vector[Int] = Vector.fill(cards.length)(1) | |
cards.indices.foldLeft(cardCounts) { (acc, idx) => | |
val matchCount = cards(idx).matchCount() | |
(1 to matchCount).foldLeft(acc) { (acc, i) => | |
acc.updated(idx + i, acc(idx + i) + acc(idx)) | |
} | |
}.sum | |
@main def solve4(): Unit = | |
val in = new FileInputStream("example4-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line) | |
.toVector | |
val cards = inputs.map(Card.apply) | |
println(solve4_1(cards)) | |
println(solve4_2(cards)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment