Rearrange rows with recursion

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.

+6
source share
3 answers

Do not change s1 and s2 in the loop, which causes an error. Just pass these definitions as arguments to the recursive function. Like this:

 . . for (int i = 0; i < s2.length(); i++) { displayPermuatation(s1 + s2.charAt(i), s2.substring(0, i) + s2.substring(i+1)); } . . 
+5
source

The problem with your code is that you are changing the values ​​of s1 and s2 in the loop, which affects the next iterations in the loop, see the following code where I fixed this problem.

 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 displayPermuatation(s1 + s2.charAt(i), s2.substring(0, i) + s2.substring(i + 1)); } } } 
+2
source

Do not change the initial values ​​for s1 , s2 in the loop:

 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 string new_s1 = s1 + s2.charAt(i); string new_s2 = s2.substring(0, i) + s2.substring(i+1); displayPermuatation(new_s1 , new_s2 ); } } 
+1
source

All Articles