java - My puzzle about getting a function to return a permutation array -
i want method returns permutations of input string. have searched internet , found of them similar robert sedgewick's code:http://introcs.cs.princeton.edu/java/23recursion/permutations.java.html
however, want return permutations, not print them. robert sedgewick's code copied here:
public class permutations { // print n! permutation of characters of string s (in order) public static void perm1(string s) { perm1("", s); } private static void perm1(string prefix, string s) { int n = s.length(); if (n == 0) system.out.println(prefix); else { (int = 0; < n; i++) perm1(prefix + s.charat(i), s.substring(0, i) + s.substring(i+1, n)); } } public static void main(string[] args) { perm1("abcd"); } }
and code recoding robert sedgewick's myself below:
import java.util.arraylist; public class test { public static arraylist<string> permute(string prefix, string s){ int len = s.length(); arraylist<string> list = new arraylist<string>(); if(s.length() == 0) list.add(prefix); else for(int = 0; < len; i++) permute(prefix + s.charat(i), s.substring(0, i) + s.substring(i+1, len)); return list; } public static void main(string[] args) { string str = "abcd"; arraylist<string> array = permute("", str); system.out.print(array.size()); } }
but code doesn't return permutations. returns nothing. don't know why. can me?
you need add result of permute method arraylist:
import java.util.arraylist; public class test { public static arraylist<string> permute(string prefix, string s){ int len = s.length(); arraylist<string> list = new arraylist<string>(); if(s.length() == 0) list.add(prefix); else for(int = 0; < len; i++) list.addall(permute(prefix + s.charat(i), s.substring(0, i) + s.substring(i+1, len))); return list; } public static void main(string[] args) { string str = "abcd"; arraylist<string> array = permute("", str); system.out.print(array.size()); } }
Comments
Post a Comment