Advertisement
jules0707

mastermind.kt

Jun 17th, 2021
925
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.45 KB | None | 0 0
  1. package mastermind
  2.  
  3. import kotlin.math.min
  4.  
  5. data class Evaluation(val rightPosition: Int, val wrongPosition: Int)
  6.  
  7. fun evaluateGuess(secret: String, guess: String): Evaluation {
  8.  
  9.     val wp = secret.zip(guess).count { it.first == it.second /*(s, g) -> s == g*/ }
  10.  
  11.     val common = "ABCDEF".sumBy { c ->
  12.         min(
  13.             secret.count { it == c /*s -> s==c*/ },
  14.             guess.count { it == c /*g -> g == c*/ }
  15.         )
  16.     }
  17.     return Evaluation(wp, common - wp)
  18. }
  19.  
  20.  
  21. // ------ MY INITIAL IMPERATIVE SOLUTION  .-< ----------//
  22. fun evalGuess(secret: String, guess: String): Evaluation {
  23.  
  24.     var rp = 0
  25.     var wp = 0
  26.     val se = secret.toCharArray() // defensive copies
  27.     val ge = guess.toCharArray()
  28.  
  29.     for ((index, element) in guess.withIndex()) { // find right position first
  30.         if (element == secret[index]) {
  31.             rp += 1
  32.             se[index] = '-'// replace element from secret and guess
  33.             ge[index] = '#'// that do not match
  34.         }
  35.     }
  36.  
  37.     for ((index, element) in ge.withIndex()) { // find wrong positions
  38.         if (element in se.toList()) {
  39.             wp += 1
  40.             se[se.indexOf(element)] = '@' // same here
  41.             ge[index] = '!'
  42.         }
  43.     }
  44.     return Evaluation(rp, wp)
  45. }
  46.  
  47. fun main() {
  48.     evalGuess("ABC", "ADC") // 0,1
  49.     // evaluateGuess("ABCD", "EAAA") // 0,1
  50.     // evaluateGuess("BDAD", "AAAE") // 1,0
  51.     // evalGuess("ABC", "CAA") // 1,0
  52.  
  53. }
  54.  
  55.  
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement