Skip to content

Instantly share code, notes, and snippets.

@waynejo
Last active January 7, 2022 13:02
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/c75a7d6f9f9affdd6509be2c278ed9f6 to your computer and use it in GitHub Desktop.
Save waynejo/c75a7d6f9f9affdd6509be2c278ed9f6 to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.annotation.tailrec
import scala.io.StdIn
case class BoardCell(isSelected: Boolean, number: Int)
case class Board(cells: Vector[Vector[BoardCell]]) {
def isBingo: Boolean = // 빙고 여부를 판단한다.
cells.exists(_.forall(_.isSelected)) || cells.transpose.exists(_.forall(_.isSelected))
def applyNumber(n: Int): Board = // 보드에 새 숫자를 추가한다.
val newCells = cells.map(_.map(cell => if cell.number == n then cell.copy(isSelected = true) else cell))
Board(newCells)
}
object Board {
def from(numbers: Vector[Vector[Int]]): Board = // 숫자 배열에서 보드를 생성한다.
Board(numbers.map(_.map(n => BoardCell(false, n))))
}
def score(board: Board, lastNumber: Int): Int = // 문제에 주어진 방식대로 점수를 계산한다.
board.cells.flatten.filter(!_.isSelected).map(_.number).sum * lastNumber
@tailrec
def solve4_1(boards: Vector[Board], numbers: Vector[Int], index: Int = 0): Int =
boards.find(_.isBingo) match // 현재 빙고 상태인 보드가 있으면,
case Some(board) =>
score(board, numbers(index - 1)) // 점수를 계산하여 반환한다.
case _ =>
solve4_1(boards.map(_.applyNumber(numbers(index))), numbers, index + 1) // 아닌 경우는 그 다음 숫자를 적용한다.
@tailrec
def solve4_2(boards: Vector[Board], numbers: Vector[Int], index: Int = 0): Int =
boards.find(_.isBingo) match
case Some(board) if boards.size == 1 => // 마지막 보드가 빙고 상태면
score(board, numbers(index - 1)) // 점수를 계산하여 반환한다.
case _ =>
solve4_2(boards.filter(!_.isBingo).map(_.applyNumber(numbers(index))), numbers, index + 1) // 아닌 경우는 빙고인 보드를 제거하고 그 다음 숫자를 적용한다.
@main def solve4(): Unit =
val in = new FileInputStream("example4-2.in")
System.setIn(in)
val numbers = StdIn.readLine().split(",").map(_.toInt).toVector
val boardNumbers = Iterator.continually(StdIn.readLine())
.takeWhile(line => null != line)
.filter(line => line.trim.nonEmpty)
.grouped(5)
.map(_.map(_.split(" ").filter(_.nonEmpty).map(_.toInt).toVector).toVector)
.toVector
val boards = boardNumbers.map(Board.from)
println(solve4_1(boards, numbers))
println(solve4_2(boards, numbers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment