Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- import java.util.Random;
- /**
- * Used to generate random words, given a pattern and an alphabet
- */
- class WordGenerator {
- public int noiseLength = 10;
- private Pattern pattern;
- private String alphabet;
- private Random rand;
- /**
- * Construct the WordGenerator
- *
- * @param String pattern The regular expression (probably a syllable structure) that is allowed
- * @param String alphabet All and only the legal characters in the language
- */
- public WordGenerator(String pattern, String alphabet) {
- this.pattern = Pattern.compile(pattern);
- this.alphabet = alphabet;
- rand = new Random();
- }
- /**
- * Generates a new word consisting of characters from the alphabet that adheres to the pattern
- */
- public String generate() {
- String word = "";
- String noise;
- Matcher result;
- // As long as we don't have a word, keep generating noise and checking if something in it matches the
- // pattern
- while(word.length() == 0) {
- noise = generateNoise();
- result = pattern.matcher(noise);
- // If any matches were found, set the output word to the first match
- if (result.find()) {
- word = result.group(0);
- }
- }
- return word;
- }
- /**
- * Generates a string of random characters belonging to the alphabet
- */
- private String generateNoise() {
- StringBuilder builder = new StringBuilder();
- int nextCharIndex;
- for (int i = 0; i < noiseLength; i++) {
- nextCharIndex = rand.nextInt(alphabet.length());
- builder.append(alphabet.charAt(nextCharIndex));
- }
- return builder.toString();
- }
- }
- /**
- * This would go in some other file. As you can see, all you have to do to use the WordGenerator class is
- * instantiate it with the desired syllable structure and alphabet (both strings - the class takes care of
- * the compilation for you), and then call generate() on it to get a random word.
- */
- class Main {
- public static void main(String[] args) {
- String alphabet = "aæɑbdðeɛəfghiɪjklmnŋopɹsʃtθuʌʊvwzʒ";
- String syllable_structure = "(?:[^aæɑeɛəiɪouʌʊ][aæɑeɛəiɪouʌʊ]){1,6}";
- WordGenerator generator = new WordGenerator(syllable_structure, alphabet);
- for (int i = 0; i < 10; i++) {
- System.out.println(generator.generate());
- }
- }
- }
Add Comment
Please, Sign In to add comment