/** Let's generate "words" from a set of strings that's recursively defined * by this grammar: * S --> AB * A --> "" * A --> aA * B --> "" * B --> aBb * First, try to figure out what A and B represent. Then this will tell * you about the entire set S. How would you describe this "language" ? */ public class Generate { public static void main(String [] args) { // Generate 10 words. for (int i = 0; i < 10; ++i) { String S = A() + B(); System.out.println(S); } } // This recursive function will either pick the rule "" or the rule aA. // Since nextDouble() returns a number between 0 and 1, if we compare // it to 0.3, then we have a 30% chance of returning the base case. public static String A() { if (Math.random() < .3) return ""; else return "a" + A(); } // B is similar to A, but this time, we also concatenate a 'b' after // returning from recursion. public static String B() { if (Math.random() < .3) return ""; else return "a" + B() + "b"; } } /*=============================================== Example output: ------------------------------------------------- aaaaaaaaaaaaabbbbbbbbbb aab a aaaaabbb aaaabb ab aa aaaabbb aaaaaabbbbbb =================================================*/