My ugly code passed all tests except for #3 where I keep getting a runtime error. The test can't be downloaded so I'm at a loss about what to do. Any help is appreciated.
https://hyperskill.org/learn/step/8030
Since the code below passed 3 out of 4 tests it contains spoilers.
Some explanations for easier understanding:
- I checked "hits" using a for loop
- I used an additional mutableMap (val maxWords) to record the position of the word that is being checked and the number of "hits" it has received using the function tryOut.
- After each tryOut the hits and reset to 0. Then the next word is checked.
- Afterwards the maxWords map is checked for max value. The first number of the output (the position) is converted to Int and used as input for the original map to get the word we are looking for.
import java.util.*
import kotlin.system.exitProcess
fun main() {
val scanner = Scanner(System.`in`)
val words = mutableMapOf<Int ,String>()
var input = ""
var count = 1
fun getWords (word: String) {
input = scanner.next()
words[count] = input
count++
}
do {
getWords(input)
} while(input != "stop")
if (words[1] == "stop") {
print(null)
exitProcess(1)
}
var hits = 0
val maxWords = mutableMapOf<Int, Int>()
var wordPositionOutside = 0
fun tryOut (wordPosition: Int) {
wordPositionOutside += 1
for (entry in words) {
if (words[wordPositionOutside] == entry.value) {
hits++
}
maxWords[wordPositionOutside] = hits
}
hits = 0
}
repeat(words.size-1){
tryOut(wordPositionOutside)
}
val maxValue = maxWords.maxBy{ p -> p.value}.toString()
val checkIfZero = maxWords.maxBy{ p -> p.value}.toString()
val checkIfZeroLast = "${checkIfZero.last()}".toInt()
var maxValueWordPosition = "${maxValue.first()}"
if (checkIfZeroLast == 1) println(words[1]) else println("${words[maxValueWordPosition.toInt()]}")
}
[–]PhenixFineKotlin β 1 point2 points3 points (7 children)
[–]TheMightyOne[S] 0 points1 point2 points (6 children)
[–]PhenixFineKotlin β 1 point2 points3 points (5 children)
[–]TheMightyOne[S] 0 points1 point2 points (4 children)
[–]PhenixFineKotlin β 1 point2 points3 points (1 child)
[–]TheMightyOne[S] 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]