1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | //Substring using recursion substring( "" , userinput, 0 , userinput.length()); public static void substring(String fixed, String str, int step, int len) { if (step < len) { System.out.printf( "%d :%s \n" , ++counter, fixed); while (step < len) { substring(fixed + str.charAt(step), str, step + 1 , len); step ++; } } else System.out.printf( "%d :%s \n" , ++counter, fixed); } //Anagram using recursion public static void anagram(String str, int len) { anagram0( "" , str, len); } public static void anagram0(String first, String str, int len) { String left = "" , right = "" ; if (len == 1 ) { System.out.println( ":" + first + str); } else { for ( int pos = 0 ; pos < len; pos++) { String temp = "" + str.charAt(pos); left = str.substring( 0 , pos); if (pos + 1 == len) right = "" ; else right = str.substring(pos + 1 , len); anagram0(first + temp, left + right, len - 1 ); } } } |
Writing code and seeing our application automating a task is a great fun to see.
Sunday, March 8, 2015
Using recursion
Subscribe to:
Posts (Atom)