Skip to content

Instantly share code, notes, and snippets.

@xrrocha
Created December 16, 2020 17:26
Show Gist options
  • Save xrrocha/293dd57cec40bc8208ed5253e9ba330a to your computer and use it in GitHub Desktop.
Save xrrocha/293dd57cec40bc8208ed5253e9ba330a to your computer and use it in GitHub Desktop.
code block for README-1
package wscrambler
import java.io.File
// 4+ Latin letters, 2+ distinct inners
private val WORD_REGEX =
"""\p{IsLatin}(\p{IsLatin})\1*(?!\1)\p{IsLatin}\p{IsLatin}+"""
.toRegex()
// Scramble words within text
fun scrambleWords(text: String): String{
// Copy input text to output array
val result = text.toCharArray()
// Examine text looking for matches
WORD_REGEX.findAll(text)
.forEach { match->
// Define range of inner letters
val range = match.range.first + 1
until match.range.last
do {
// Shuffle inner letter array
for (i in range) {
// Choose random region index
val rndIdx = range.random()
// Swap current/random chars
result[rndIdx]=result[i].also {
result[i] = result[rndIdx]
}
}
// Ensure shuffling took place!
} while (range.all {
result[it] == text[it]
})
}
// Return scrambled text as string
return String(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment