Wednesday, July 18, 2012

String Combination Algorithm

Just needed to brush up some old but important algorithms so I thought I'd post them here and on github for my own future reference and anyone elses. This example I did in Java:

class Combo {



        public static void main ( String args[] ) {

                char[] combos = new char[args[0].length()];
                findCombos ( args[0], new String(combos), 0 );

        }



        private static void findCombos( String str, String combos, int index ) {

                char[] comboChars = combos.toCharArray();


                if ( index == str.length()) {

                        System.out.println( new String(comboChars) );

                        return;

                }

                for ( int i = 0; i < str.length(); i++ ) {
                        char[] strChars = str.toCharArray();
                        comboChars[index] = strChars[i];
                        index++;
                        findCombos(str, new String(comboChars), index);
                        index--;

                }




        }


}

Here it is on github: https://github.com/asharif/StringCombo

No comments:

Post a Comment