//Permutations.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class Permutations extends JApplet { JTextField inputNField; JTextField outputPField; JTextArea listArea; JLabel errorLabel; java.util.List permsList; public void init() { Container container = getContentPane(); int panelRowsSize = 2; container.setLayout( new GridLayout( 1, panelRowsSize) ); JPanel [] panelRows = new JPanel[panelRowsSize]; //left side panel panelRows[0] = new JPanel(); container.add( panelRows[0] ); panelRows[0].setLayout( new FlowLayout() ); //right side panel panelRows[1] = new JPanel(); panelRows[1].setLayout( new FlowLayout() ); container.add( panelRows[1] ); permsList = new ArrayList(); Font bigFont = new Font( "Monospaced", Font.BOLD, 16 ); TextFieldHandler handleTextField = new TextFieldHandler(); JLabel inputNLabel = new JLabel( "N" ); inputNLabel.setFont( bigFont ); panelRows[0].add( inputNLabel ); inputNField = new JTextField( 3 ); inputNField.setFont( bigFont ); panelRows[0].add( inputNField ); inputNField.addActionListener( handleTextField ); outputPField = new JTextField( 6 ); outputPField.setFont( bigFont ); outputPField.setEditable( false ); panelRows[0].add( outputPField ); errorLabel = new JLabel( "" ); panelRows[0].add( errorLabel ); listArea = new JTextArea( 16, 30 ); Font smallFont = new Font( "Monospaced", Font.BOLD, 12 ); listArea.setFont( smallFont ); JScrollPane listScroll = new JScrollPane( listArea ); panelRows[1].add( listScroll ); } public void start() { inputNField.requestFocusInWindow(); } private class TextFieldHandler implements ActionListener { public void actionPerformed( ActionEvent event ) { listArea.setText( "" ); errorLabel.setText( "" ); outputPField.setText( "" ); int n=0; try { n = Integer.parseInt( inputNField.getText() ); } catch (NumberFormatException e) { errorLabel.setText( "integer please" ); return; } if ( n <= 0 ) { errorLabel.setText( "positive integer please" ); return; } if ( n > 14 ) { errorLabel.setText( "up to 14 only" ); return; } StringBuffer L= new StringBuffer(" abcdefghijklmn"); //14 chars permsList.clear(); perms ( L, 1, n ); outputPField.setText( "" + permsList.size() ); Iterator it = permsList.iterator(); while ( it.hasNext() ) listArea.append( (String)it.next() + "\n" ); } } //permutations from k to N void perms ( StringBuffer L, int k, int n) { char temp; if (k == n) //N to N permsList.add( L.substring( 1, n+1 ) ); else for (int i=k; i<=n; i++) { //for each I from k to N temp = L.charAt(i); //swap with Kth L.setCharAt( i, L.charAt(k) ); L.setCharAt( k, temp ); //recurse to find permutations from K+1 to N in copy of String perms( new StringBuffer( L.toString() ), k+1, n); } } }