Quick challenge after work, avoiding putting a front end on the lego app sigh.
package com.company;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String inputText = "The legend, propagated by email and message boards, purportedly demonstrates that readers can understand the "
+ "meaning of words in a sentence even when the interior letters of each word are scrambled. As long as all the necessary letters "
+ "are present, and the first and last letters remain the same, readers appear to have little trouble reading the text.";
String aPattern = "\\w+";
Pattern pattern = Pattern.compile(aPattern);
Matcher matcher = pattern.matcher(inputText);
ArrayList<String> words = new ArrayList<>();
while (matcher.find()) {
words.add(matcher.group());
}
StringBuilder outputWords = new StringBuilder(inputText.length());
String shuffledWord, middle;
char firstLetter, lastLetter;
for (String word : words) {
if(word.length() > 3) {
//build messed up words keeping edges same
firstLetter = word.charAt(0);
lastLetter = word.charAt(word.length()-1);
middle = wordShuffler(word.substring(1, word.length() - 1));
shuffledWord = firstLetter + middle + lastLetter;
} else {
shuffledWord = word;
}
outputWords.append(shuffledWord);
}
String nonWord = "\\W+";
pattern = Pattern.compile(nonWord);
matcher = pattern.matcher(inputText);
while (matcher.find()) {
outputWords.insert(matcher.start(), matcher.group());
}
System.out.println(inputText);
System.out.println(outputWords);
}
public static String wordShuffler(String wordToShuffle) {
char[] letterArray = wordToShuffle.toCharArray();
Random random = new Random();
int nextValue;
char swap;
for (int i = 0; i < letterArray.length; i++) {
swap = letterArray[i];
nextValue = random.nextInt(letterArray.length);
letterArray[i] = letterArray[nextValue];
letterArray[nextValue] = swap;
}
return new String(letterArray);
}
}
No comments:
Post a Comment