Skip to content

Instantly share code, notes, and snippets.

@vmichalak
Last active April 25, 2018 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vmichalak/c835a8bdee7f7d354d338c7f2733dbcd to your computer and use it in GitHub Desktop.
Save vmichalak/c835a8bdee7f7d354d338c7f2733dbcd to your computer and use it in GitHub Desktop.
Spintax parser
import java.util.*
fun main(args: Array<String>) {
(1..10).forEach { println(spin("my {little|big} pony")) }
}
fun spin(value: String): String {
var result: String = value
val random: Random = Random()
val regex: Regex = Regex("\\{[^{}]*}")
var matchResult: MatchResult? = regex.find(result)
while (matchResult != null) {
val segment: String = result.substring(matchResult.range.first + 1, matchResult.range.last)
val choices: List<String> = segment.split('|')
result = result.substring(0, matchResult.range.start) + choices[random.nextInt(choices.size)] + result.substring(matchResult.range.last + 1)
matchResult = regex.find(result)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment