import java.util.HashSet; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /* * Permutations.java * * Created on November 3, 2005, 5:40 PM * */ /** * * @author Bill Kraynek */ public class Permutations { static HashSet getPermutations(String word) { if( word.length() == 1 ) { HashSet p = new HashSet(); p.add(word); //JOptionPane.showMessageDialog(null,p); return p; } // end if HashSet p = getPermutations(word.substring(0, word.length()-1)); //JOptionPane.showMessageDialog(null,p); HashSet permutations = new HashSet(); char lastLetter = word.charAt(word.length()-1); for( String next : p ) { StringBuilder rest = new StringBuilder(next); for( int j = 0; j < word.length(); j++ ) { rest.insert(j,lastLetter); permutations.add(rest+""); rest.deleteCharAt(j); } // end for } // end for return permutations; } // end getPermutations public static void main(String[] args) { // Test the permutations method while(true) { String aWord = JOptionPane.showInputDialog("Enter a word. The number of letters must be less than 9"); if( aWord == null) return; if( aWord.length() >= 9 ) continue; HashSet permutations = Permutations.getPermutations(aWord); StringBuilder out = new StringBuilder("Permutations for " + aWord + "\n\n"); for( String next : permutations ) out.append(next + "\n"); JTextArea outArea = new JTextArea(out+"",20,30); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); } // end while } }