/** Program to create random balanced properly formed expressions. */ import java.io.*; import java.util.*; 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; for (int count=1; count <= 5; count++) { size = getLength(); System.out.println("nested: " + nested(size/2)); System.out.println("sequenced: " + sequenced(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() throws IOException { int size = 1; do { System.out.print("enter even expression length: "); size = keyboard.nextInt(); } while (size%2 != 0); return size; } // PHASES I & II /** Generate a random balanced nested expression @param length the number of pairs in the expression @return the generated expression */ public static String nested(int length) { if (length == 0) // base case! return ""; int choice; if (length == 1) // another base case { // pick a pair to use choice = rand.nextInt(4); return PAIRS.substring(choice*2, choice*2 + 2); } // if length > 1 - pick the outside pair and recurse inside choice = rand.nextInt(4); return PAIRS.charAt(choice*2) + nested(length-1) + PAIRS.charAt(choice*2+1); } // PHASE IV ---------------------------------------------------------- /** Generate a random balanced expression from sequencing only @param length the number of pairs in the expression @return the generated expression */ public static String sequenced(int length) { if (length == 0) // base case! return ""; int choice; if (length == 1) // another base case, pick a pair to use { choice = rand.nextInt(4); return PAIRS.substring(choice*2, choice*2 + 2); } // otherwise generate the first pair, and the rest recursively return sequenced(1) + sequenced(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"; int choice; if (length == 2) // another base case, pick a pair to use { choice = rand.nextInt(4); return PAIRS.substring(choice*2, choice*2 + 2); } // if length > 2, first decide on nest or sequence boolean nest = rand.nextBoolean(); if (nest) { choice = rand.nextInt(4); return PAIRS.charAt(choice*2) + expr(length-2) + PAIRS.charAt(choice*2+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); } }