Guest User

Untitled

a guest
Nov 17th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. import java.util.regex.Pattern;
  2. import java.util.regex.Matcher;
  3. import java.util.Random;
  4.  
  5. /**
  6. * Used to generate random words, given a pattern and an alphabet
  7. */
  8. class WordGenerator {
  9. public int noiseLength = 10;
  10.  
  11. private Pattern pattern;
  12. private String alphabet;
  13. private Random rand;
  14.  
  15. /**
  16. * Construct the WordGenerator
  17. *
  18. * @param String pattern The regular expression (probably a syllable structure) that is allowed
  19. * @param String alphabet All and only the legal characters in the language
  20. */
  21. public WordGenerator(String pattern, String alphabet) {
  22. this.pattern = Pattern.compile(pattern);
  23. this.alphabet = alphabet;
  24. rand = new Random();
  25. }
  26.  
  27. /**
  28. * Generates a new word consisting of characters from the alphabet that adheres to the pattern
  29. */
  30. public String generate() {
  31. String word = "";
  32. String noise;
  33. Matcher result;
  34.  
  35. // As long as we don't have a word, keep generating noise and checking if something in it matches the
  36. // pattern
  37. while(word.length() == 0) {
  38. noise = generateNoise();
  39. result = pattern.matcher(noise);
  40.  
  41. // If any matches were found, set the output word to the first match
  42. if (result.find()) {
  43. word = result.group(0);
  44. }
  45. }
  46.  
  47. return word;
  48. }
  49.  
  50. /**
  51. * Generates a string of random characters belonging to the alphabet
  52. */
  53. private String generateNoise() {
  54. StringBuilder builder = new StringBuilder();
  55. int nextCharIndex;
  56.  
  57. for (int i = 0; i < noiseLength; i++) {
  58. nextCharIndex = rand.nextInt(alphabet.length());
  59. builder.append(alphabet.charAt(nextCharIndex));
  60. }
  61.  
  62. return builder.toString();
  63. }
  64. }
  65.  
  66. /**
  67. * This would go in some other file. As you can see, all you have to do to use the WordGenerator class is
  68. * instantiate it with the desired syllable structure and alphabet (both strings - the class takes care of
  69. * the compilation for you), and then call generate() on it to get a random word.
  70. */
  71. class Main {
  72. public static void main(String[] args) {
  73. String alphabet = "aæɑbdðeɛəfghiɪjklmnŋopɹsʃtθuʌʊvwzʒ";
  74. String syllable_structure = "(?:[^aæɑeɛəiɪouʌʊ][aæɑeɛəiɪouʌʊ]){1,6}";
  75.  
  76. WordGenerator generator = new WordGenerator(syllable_structure, alphabet);
  77.  
  78. for (int i = 0; i < 10; i++) {
  79. System.out.println(generator.generate());
  80. }
  81. }
  82. }
Add Comment
Please, Sign In to add comment