I am trying to create an evaluator in Kotlin for the Mastermind game which compares two strings and tells how many letters and letters on the right position they share.
I was hoping to get some comments on how I can improve the code below in any way. Many thanks in advance!
fun String.masterCompare(otherString:String): Pair<Int, Int>? {
// If the two strings are not equal in size, return null
if (length != otherString.length)
return null
var letters : Int = 0 // The number of letters the two strings have in common
var positions: Int = 0 // The number of shared letters that are in the same index
var other = otherString // A mutable string copy of the argument string
// Get number of shared indexes (positions)
for ((index, c) in withIndex()){
if (c == otherString[index]) {
positions++
}
}
// Check if a char in this string exists in the other. If so, increment letters and delete the char from the other string (so that it's not rechecked)
for (c in toList()){
if (other.contains(c)){
letters++
other = other.replace(c.toString(), "")
}
}
return letters to positions
}
fun main(args: Array<String>) {
println("ABCD".masterCompare("AFCH")) // 2,2
println("AAAA".masterCompare("AFCH")) // 1,1
println("ABCD".masterCompare("ABCD")) // 4,4
println("ABCD".masterCompare("DCBA")) // 4,0
println("ABCDP".masterCompare("DCBA")) // null
}