Created
April 5, 2021 09:37
-
-
Save iamdejan/fb053c513e4f6b22e7139837d2a66b42 to your computer and use it in GitHub Desktop.
Sample CP Problem with Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val rectangleRaw = """ | |
KOTE | |
NULE | |
AFIN | |
""" | |
val dictionaryRaw = "Kotlin, fun, file, line, null" | |
val directions = listOf(1 to 0, 0 to -1, 0 to 1, -1 to 0) | |
fun main() { | |
val rectangle = rectangleRaw.trimIndent().split("\n") | |
val dictionary = dictionaryRaw.toUpperCase().split(", ").toHashSet() | |
val prefixes = dictionary.flatMap { word -> | |
println("word = ${word}") | |
List(word.length + 1) { it -> | |
println("[word] it = ${it}") | |
val taken = word.take(it) | |
println("[word] taken = ${taken.toString()}") | |
taken | |
} | |
}.toHashSet() | |
fun search(x: Int, y: Int, word: String) { | |
if (word !in prefixes) { | |
return | |
} | |
if (word in dictionary) { | |
println(word) | |
} | |
for ((dx, dy) in directions) { | |
val xNew = x + dx | |
val yNew = y + dy | |
val letter = rectangle.getOrNull(xNew)?.getOrNull(yNew) ?: continue | |
search(xNew, yNew, word + letter) | |
} | |
} | |
for(x in rectangle.indices) { | |
for(y in rectangle[0].indices) { | |
search(x, y, rectangle[x][y].toString()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment