Newer
Older
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import type3.FiniteStateMachine;
public class WordGenerator {
Random random = new Random();
public String wordGenerator(int maxLength) {
return wordGeneratorOverAlphabet(maxLength, 26);
}
public String wordGeneratorOverAlphabet(int maxLength, int alphaSize) {
return random.ints(random.nextInt(maxLength + 1), 97, 97 + alphaSize)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
public String wordGeneratorOverType2Grammar(int maxLength, Map<String, List<List<String>>> cnfGrammar) {
String s = "";
while (s.equals("") || !s.equals(s.toLowerCase())) {
s = wordGeneratorOverType2GrammarTry(random.nextInt(maxLength - 1) + 1, cnfGrammar);
}
return s;
}
private String wordGeneratorOverType2GrammarTry(int maxLength, Map<String, List<List<String>>> cnfGrammar) {
List<String> sb = new ArrayList<>();
sb.add(cnfGrammar.containsKey("S'") ? "S'" : "S");
int i = 0;
wordGeneratorOverType2GrammarTry(maxLength, sb, cnfGrammar, sb.size(), i);
return sb.stream().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
}
private void wordGeneratorOverType2GrammarTry(int maxLength, List<String> sb,
Map<String, List<List<String>>> cnfGrammar, int size, int i) {
if (size <= maxLength && i < size) {
if (cnfGrammar.containsKey(sb.get(i))) {
List<List<String>> options = cnfGrammar.get(sb.get(i));
List<String> option = options.get(random.nextInt(options.size()));
sb.remove(i);
for (int j = 0; j < option.size(); j++) {
sb.add(i + j, option.get(j));
}
wordGeneratorOverType2GrammarTry(maxLength, sb, cnfGrammar, sb.size(), i);
} else {
wordGeneratorOverType2GrammarTry(maxLength, sb, cnfGrammar, size, ++i);
}
}
}
public String wordGeneratorOverType3Grammar(int maxLength, FiniteStateMachine fsm, int alphaSize) {
String word;
while (true) {
word = wordGeneratorOverType3GrammarTry(random.nextInt(maxLength - 1) + 1, fsm, alphaSize);
if (fsm.canStop()) {
break;
}
fsm.resetStateMachine();
}
return word;
}
public String wordGeneratorOverType3GrammarTry(int maxLength, FiniteStateMachine fsm, int alphaSize) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxLength; i++) {
String s = (char) (random.nextInt(alphaSize) + 97) + "";
sb.append(s);
fsm.switchStates(s);
}
return sb.toString();
}