Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mastermind
- import kotlin.math.min
- data class Evaluation(val rightPosition: Int, val wrongPosition: Int)
- fun evaluateGuess(secret: String, guess: String): Evaluation {
- val wp = secret.zip(guess).count { it.first == it.second /*(s, g) -> s == g*/ }
- val common = "ABCDEF".sumBy { c ->
- min(
- secret.count { it == c /*s -> s==c*/ },
- guess.count { it == c /*g -> g == c*/ }
- )
- }
- return Evaluation(wp, common - wp)
- }
- // ------ MY INITIAL IMPERATIVE SOLUTION .-< ----------//
- fun evalGuess(secret: String, guess: String): Evaluation {
- var rp = 0
- var wp = 0
- val se = secret.toCharArray() // defensive copies
- val ge = guess.toCharArray()
- for ((index, element) in guess.withIndex()) { // find right position first
- if (element == secret[index]) {
- rp += 1
- se[index] = '-'// replace element from secret and guess
- ge[index] = '#'// that do not match
- }
- }
- for ((index, element) in ge.withIndex()) { // find wrong positions
- if (element in se.toList()) {
- wp += 1
- se[se.indexOf(element)] = '@' // same here
- ge[index] = '!'
- }
- }
- return Evaluation(rp, wp)
- }
- fun main() {
- evalGuess("ABC", "ADC") // 0,1
- // evaluateGuess("ABCD", "EAAA") // 0,1
- // evaluateGuess("BDAD", "AAAE") // 1,0
- // evalGuess("ABC", "CAA") // 1,0
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement