I start java and try to swap lines from a java book. I define two methods:
public static void displayPermutation(String s) public static void displayPermutation(String s1, String s2)
The first method simply calls displayPermutation(" ", s) . The second method uses a loop to move a character from s2 to s1 and recursively calls it with new s1 and s2. The basic case is that s2 is empty and prints s1 on the console.
Can someone help me find the problem with the following code?
Her example:
public static void displayPermutation(String s) { displayPermuatation("", s); } private static void displayPermuatation(String s1, String s2) { //base case: when s2 is empty, print s1 if (s2.isEmpty()) { System.out.println(s1); } else { for (int i = 0; i < s2.length(); i++) { //move a char from s1 to s2, and recursively invokes it with //new s1 and s2 s1 = s1 + s2.charAt(i); s2 = s2.substring(0, i) + s2.substring(i+1); displayPermuatation(s1, s2); } } }
if s = "abc", it prints only: ACB alphabet
it seems that in the first call to displayPermuatation ("", "abc") it does not end the for loop .... any comments?
Thanks for all the comments below. I think the mistakes I made are that the passing object as an argument to the method actually passes the link. this is not like primitive data (pass by value). When changing an object, it will affect the next method call using this object.
source share