import scala.util.Random
object ReplaceRandomWord {
def replaceRandomWord(text: String, replacements: List[String]): String = {
val words = text.split(" ").toList
if (words.isEmpty || replacements.isEmpty)
return text // nothing to do
val rnd = new Random()
// Pick random index in the sentence
val idx = rnd.nextInt(words.length)
// Pick random replacement word
val newWord = replacements(rnd.nextInt(replacements.length))
// Replace it
val updated = words.updated(idx, newWord)
// Rebuild the string
updated.mkString(" ")
}
def main(args: Array[String]): Unit = {
val text = "The quick brown fox jumps over the lazy dog"
val replacementWords = List("c#", "c++", "java", "rust", "python")
val result = replaceRandomWord(text, replacementWords)
println(result)
}
}
/*
run:
The quick brown fox rust over the lazy dog
*/