Skip to content

Instantly share code, notes, and snippets.

@xrrocha
Created December 16, 2020 17:26
Show Gist options
  • Save xrrocha/24603c82c969c3268c425df0570be394 to your computer and use it in GitHub Desktop.
Save xrrocha/24603c82c969c3268c425df0570be394 to your computer and use it in GitHub Desktop.
code block for README-0
public class WordScrambler {
// 4+ letters, 2+ distinct inners
// \p{IsLatin} equals [a-zA-ZÀ-ÿ]
// Range [À-ÿ]: accented letters
private static final Pattern WORD_REGEX =
Pattern.compile("\\p{IsLatin}(\\p{IsLatin})\\1*(?!\\1)\\p{IsLatin}\\p{IsLatin}+");
// Scramble words within text
public static String
scrambleWords(String text) {
// Copy input text to output array
final var result =
text.toCharArray();
// Create randomizer for this run
final var random = new Random();
// Examine text looking for matches
WORD_REGEX.matcher(text).results()
.forEach(match -> {
// 2nd letter
final var start =
match.start() + 1;
// Penultimate letter
final var end = match.end() - 1;
final var length = end - start;
do {
// Shuffle inner letter array
for (var i = start;i < end;i++){
// Choose random inner index
final var rndIdx = start +
random.nextInt(length);
// Swap current/random chars
final var save = result[i];
result[i] = result[rndIdx];
result[i] = save;
}
// Ensure shuffling took place!
} while (
IntStream.range(start, end)
.allMatch(i ->
result[i] ==
text.charAt(i))
); // do/while
}); // forEach
// Return scrambled text as string
return new String(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment