Created
September 14, 2019 07:13
-
-
Save nyango/289b1d47125c7fb1a0e7e9559978e8f8 to your computer and use it in GitHub Desktop.
ピクロス(お絵かきロジック)を解くプログラム
This file contains hidden or 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
object Main extends App { | |
def possibleSeq(baseSeq: Seq[Option[Boolean]]): Seq[Seq[Boolean]] = | |
baseSeq.foldLeft(Seq(Seq.empty[Boolean])) { (acc, ele) => | |
ele match { | |
case Some(b) => acc.map(_ ++ Seq(b)) | |
case None => acc.flatMap(s => Seq(s ++ Seq(true), s ++ Seq(false))) | |
} | |
} | |
def reduceSeq(possibleSeqs: Seq[Seq[Boolean]]): Seq[Option[Boolean]] = { | |
possibleSeqs.tail.foldLeft(possibleSeqs.head.map(Some(_)): Seq[Option[Boolean]]) { (acc, ele) => | |
acc.zip(ele).iterator.map { | |
case (a, b) if (a.contains(b)) => a | |
case _ => None | |
}.toSeq | |
} | |
} | |
def serialize(seq: Seq[Boolean]): Seq[Int] = | |
seq.foldLeft((0, Seq.empty[Int])) { (acc, ele) => | |
ele match { | |
case true => (acc._1 + 1, acc._2) | |
case false if acc._1 > 0 => (0, acc._2 ++ Seq(acc._1)) | |
case _ => acc | |
} | |
} match { | |
case (0, res) => res | |
case (las, res) => res ++ Seq(las) | |
} | |
def checkValid(seq: Seq[Boolean], nums: Seq[Int]): Boolean = { | |
serialize(seq) == nums | |
} | |
def rowUpdate(table: Seq[Seq[Option[Boolean]]]) = | |
table.zip(rowNums).map { tpl => | |
reduceSeq(possibleSeq(tpl._1).filter(checkValid(_, tpl._2))) | |
} | |
def colUpdate(table: Seq[Seq[Option[Boolean]]]) = | |
table.transpose.zip(colNums).map { tpl => | |
reduceSeq(possibleSeq(tpl._1).filter(checkValid(_, tpl._2))) | |
}.transpose | |
def doIter(table: Seq[Seq[Option[Boolean]]]) = colUpdate(rowUpdate(table)) | |
def printout(res: Seq[Seq[Option[Boolean]]]): Unit = { | |
res.foreach(row => | |
println(row.map { | |
case Some(true) => "■" | |
case Some(false) => "□" | |
case None => "◆" | |
}.mkString("")) | |
) | |
} | |
// サンプルデータ | |
val totalSize = 10 | |
val rowNums = Seq( | |
Seq(4), | |
Seq(3, 1), | |
Seq(1, 2), | |
Seq(5, 1), | |
Seq(1, 1), | |
Seq(1, 3), | |
Seq(3, 4), | |
Seq(4, 4), | |
Seq(4, 2), | |
Seq(2) | |
) | |
val colNums = Seq( | |
Seq(2), | |
Seq(4), | |
Seq(4), | |
Seq(8), | |
Seq(1, 1), | |
Seq(1, 1), | |
Seq(1, 1, 2), | |
Seq(1, 1, 4), | |
Seq(1, 1, 4), | |
Seq(8) | |
) | |
val table: Seq[Seq[Option[Boolean]]] = (1 to totalSize).map(_ => | |
(1 to totalSize).map(_ => None)) | |
// 計算・出力 | |
val t1 = doIter(table) | |
val t2 = doIter(t1) | |
val t3 = doIter(t2) | |
printout(t1) | |
println("") | |
printout(t2) | |
println("") | |
printout(t3) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment