Created
April 30, 2023 00:03
-
-
Save gabrbrand/7fec509a82a8c1703e1d4c3c0f40d4af to your computer and use it in GitHub Desktop.
This file contains 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
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