Skip to content

Instantly share code, notes, and snippets.

@anderseriksson
Created April 25, 2012 19:30
Show Gist options
  • Save anderseriksson/2492570 to your computer and use it in GitHub Desktop.
Save anderseriksson/2492570 to your computer and use it in GitHub Desktop.
Mastermind resolver in Scala
package mastermind
import collection.Seq
object MasterMindKata extends App {
def getPlusV1(z: Seq[(Char, Char)]): String = {
val res = for (t <- z) yield {
if (t._1 == t._2) {
"+"
} else ""
}
res.mkString("")
}
def resolveMasterMind(secret: String, guess: String): String = {
//consider using corresponds instead
val z: Seq[(Char, Char)] = secret.zip(guess)
val y: (Seq[(Char, Char)], Seq[(Char, Char)]) = z.partition(c => c._1 == c._2)
val matched = y._1
val unmatched = y._2.unzip
val matchedSomewhere = unmatched._1.intersect(unmatched._2)
"+" * matched.size + "-" * matchedSomewhere.size
}
val case1: String = resolveMasterMind("rrrrrr", "bbbbbb")
println(case1 == "" , " >" + case1 + "<")
val case2: String = resolveMasterMind("rrrrrb", "bbbbbb")
println(case2 == "+" , " >" + case2+ "<")
val case3: String = resolveMasterMind("rrrrbb", "bbbbbb")
println(case3 == "++" , " >" + case3 + "<")
val case4: String = resolveMasterMind("grrrbb", "bgbbbb")
println(case4 == "++-" , " >" + case4 + "<")
val case5: String = resolveMasterMind("rgbyrgby", "yrgbyrgb")
println(case5 == "--------" , " >" + case5 + "<")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment