Skip to content

Instantly share code, notes, and snippets.

@gabrbrand
Created April 30, 2023 00:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrbrand/7fec509a82a8c1703e1d4c3c0f40d4af to your computer and use it in GitHub Desktop.
Save gabrbrand/7fec509a82a8c1703e1d4c3c0f40d4af to your computer and use it in GitHub Desktop.
import kotlin.random.Random
class RandomWordGenerator(words: List<String>) {
private val graph = mutableMapOf<Char, MutableSet<Char>>()
private val firstLetters = mutableSetOf<Char>()
private val lastLetters = mutableSetOf<Char>()
init {
words.forEach { word ->
word.forEachIndexed { index, currentLetter ->
if (currentLetter !in graph) graph[currentLetter] = mutableSetOf()
val nextLetter = if (index < word.lastIndex) word[index + 1] else null
if (nextLetter != null) graph[currentLetter]?.add(nextLetter)
}
firstLetters.add(word.first())
lastLetters.add(word.last())
}
}
fun generateRandomWord(): String {
val randomWord = StringBuilder()
var currentLetter = firstLetters.random()
while (true) {
randomWord.append(currentLetter)
val nextLetter = graph[currentLetter]?.randomOrNull() ?: return randomWord.toString()
if (nextLetter in lastLetters && Random.nextBoolean() && Random.nextBoolean()) {
randomWord.append(nextLetter)
return randomWord.toString()
} else {
currentLetter = nextLetter
}
}
}
}
fun main() {
val words = listOf("apple", "banana", "cabbage")
val generator = RandomWordGenerator(words)
val randomWord = generator.generateRandomWord()
println(randomWord)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment