Skip to content

Instantly share code, notes, and snippets.

@jeantil
Created August 25, 2011 17:37
Show Gist options
  • Select an option

  • Save jeantil/1171242 to your computer and use it in GitHub Desktop.

Select an option

Save jeantil/1171242 to your computer and use it in GitHub Desktop.
package eu.bjean
object Mastermind {
def check(secret: Symbol*)(guess: Symbol*): (Int, Int) = {
val (goodPairs,badPairs) = secret.zip(guess).partition({ case (x, y) => x == y })
var badCount = 0
if (badPairs.size > 0) {
val (badSecret, badGuess) = badPairs.unzip
val badSecSort = badSecret.sortBy(_.toString)
val badGueSort = badGuess.sortBy(_.toString)
badCount = badSecSort.zip(badGueSort).filter { case (x, y) => x == y }.size
}
val pairs = goodPairs.size
(pairs, badCount)
}
}
package eu.bjean
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
@RunWith(classOf[JUnitRunner])
class MastermindSpec extends FlatSpec with ShouldMatchers {
behavior of "Mastermind"
it should "find no good and no misplaced for a wrong guess" in {
Mastermind.check (secret='blue)(guess='red) should equal (0,0)
}
it should "find all good if guess equals secret" in {
Mastermind.check (secret='blue)(guess='blue) should equal (1,0)
}
it should "find 1 good in a secret of 2" in {
Mastermind.check ('red,'blue)('green,'blue) should equal (1,0)
}
it should "find 2 good in a secret of 3" in {
Mastermind.check ('red,'blue,'red)('green,'blue,'red) should equal (2,0)
}
it should "find one misplaced in a secret of 2" in {
Mastermind.check ('blue,'red)('green,'blue) should equal (0,1)
}
it should "find 2 misplaced in a secret of 3" in {
Mastermind.check ('blue,'red,'green)('green,'blue,'yellow) should equal (0,2)
}
it should "find 1 wellplaced and 1 misplaced in a secret of 3" in {
Mastermind.check ('blue,'blue,'green)('red,'blue,'blue) should equal (1,1)
}
it should "find 2 misplaced in a secret of with a specific order 3" in {
Mastermind.check ('blue,'blue,'green)('green,'yellow,'blue) should equal (0,2)
}
it should "find 2 misplaced in a secret of with a specific order 4" in {
Mastermind.check ('green,'blue,'yellow,'red)('green,'yellow,'blue,'blue) should equal (1,2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment