/** Program to create random balanced properly formed expressions. */ import java.io.IOException; import java.util.Random; import java.util.Scanner; public class Balanced { private static Scanner keyboard = new Scanner(System.in); private static Random rand = new Random(); private static final String PAIRS = "{}[]()<>"; public static void main(String[] args) throws IOException { int size; size = getLength(); System.out.println("nested: " + nest(size / 2)); System.out.println("sequenced: " + sequence(size / 2)); System.out.println("mixed: " + expr(size)); System.out.println(); } /** Get an even length from the user. @return the length */ public static int getLength() { int size = 1; do { System.out.print("enter even expression length: "); size = keyboard.nextInt(); } while (size % 2 != 0); return size; } // STEP 1 /** Randomly choose a pair of matched symbols. @return the pair */ public static String pair() { int choice = rand.nextInt(4); return PAIRS.charAt(choice * 2) + "" + PAIRS.charAt(choice * 2 + 1); } // STEPS 2 & 3 /** Generate a random balanced nested expression. @param length the number of pairs in the expression @return the generated expression */ public static String nest(int length) { if (length == 0) { // base case! return ""; } if (length == 1) { // another base case return pair(); // pick a pair to use } // if length > 1 - pick the outside pair and recurse inside String symbs = pair(); return symbs.charAt(0) + nest(length - 1) + symbs.charAt(1); } // STEP 4 /** Generate a random balanced expression from sequencing only @param length the number of pairs in the expression @return the generated expression */ public static String sequence(int length) { if (length == 0) // base case! return ""; if (length == 1) { // another base case, pick a pair to use return pair(); } // otherwise generate the first pair, and the rest recursively return sequence(1) + sequence(length - 1); } // PHASE V ---------------------------------------------------------- /** Generate a random balanced expression @param length the total number of characters in the expression @return the generated expression */ public static String expr(int length) { if (length == 0) // base case! return ""; if (length % 2 == 1) return "Can't form an expression of an odd length"; if (length == 2) { // another base case, pick a pair to use return pair(); } // if length > 2, first decide on nest or sequence int choice = rand.nextInt(100); String symbs; if (choice < 40) { // nest symbs = pair(); return symbs.charAt(0) + expr(length - 2) + symbs.charAt(1); } // else sequence - decide on split choice = rand.nextInt(length / 2 - 1) + 1; // #pairs for left part return expr(choice * 2) + expr(length - choice * 2); } }