Skip to content

Instantly share code, notes, and snippets.

@fehmicansaglam
Created January 13, 2013 22:32
Show Gist options
  • Save fehmicansaglam/4526579 to your computer and use it in GitHub Desktop.
Save fehmicansaglam/4526579 to your computer and use it in GitHub Desktop.
Bilye probleminin Scala ile çözümü
object Bilye extends App {
val onbellek = collection.mutable.Map[(Int, Int), Boolean]()
def onbellekliSpragueGrundy(p: Int, q: Int): Boolean = {
onbellek.getOrElseUpdate((p, q), spragueGrundy(p, q))
}
def spragueGrundy(p: Int, q: Int) = {
if (p == 0) true
else if (2 * q < p) {
(q + 1 to 2 * q).foldLeft(true)((a, b) => a & !onbellekliSpragueGrundy(p - b, b))
} else false
}
def enIyiHamle(bilyeSayisi: Int, min: Int, max: Int) = {
(min to max) find (q => onbellekliSpragueGrundy(bilyeSayisi - q, q)) getOrElse min
}
def sonraki(bilyeSayisi: Int, onceki: Option[Int]): Int = {
onceki match {
case None => enIyiHamle(bilyeSayisi, 2, 3)
case Some(q) =>
val (min, max) = (q + 1, 2 * q)
if (max >= bilyeSayisi) bilyeSayisi
else enIyiHamle(bilyeSayisi, min, max)
}
}
def gecerliMi(q: Int, onceki: Option[Int]) = {
onceki match {
case None => q == 2 || q == 3
case Some(x) => q > x && q <= 2 * x
}
}
def insan(bilyeSayisi: Int, onceki: Option[Int]) {
val q = onceki match {
case None => readLine("Kac bilye aliyorsun? (2 <--> 3)").toInt
case Some(x) => readLine("Kac bilye aliyorsun? (%d <--> %d)".format(x + 1, 2 * x)).toInt
}
if (!gecerliMi(q, onceki)) {
println("Geçersiz hamle!!!")
insan(bilyeSayisi, onceki)
return
}
val r = bilyeSayisi - q
if (r == 0) println("Sen %d bilye aldin, hic bilye kalmadi. Sen kazandin!!!".format(q))
else {
println("Sen %d bilye aldin, %d bilye kaldi".format(q, r))
computer(r, Some(q))
}
}
def computer(bilyeSayisi: Int, onceki: Option[Int]) {
val q = sonraki(bilyeSayisi, onceki)
val r = bilyeSayisi - q
if (r == 0) println("Ben %d bilye aldim, hiç bilye kalmadi. Ben kazandim!!!".format(q))
else {
println("Ben %d bilye aldim, %d bilye kaldi".format(q, r))
insan(r, Some(q))
}
}
val bilyeSayisi: Int = readLine("Bilye sayisi?").toInt
val sira: Int = readLine("Kim baslasin (1:Ben, 2:Sen)?").toInt
if (sira == 1)
computer(bilyeSayisi, None)
else
insan(bilyeSayisi, None)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment