Last active
April 25, 2018 20:08
-
-
Save vmichalak/c835a8bdee7f7d354d338c7f2733dbcd to your computer and use it in GitHub Desktop.
Spintax parser
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 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