spj323
spj323

Reputation: 139

Recursively swap pairs of letters in a string in java

For example, if I call exchangePairs("abcdefg"), I should receive "badcfeg" in return.

This is for a homework assignment, any kind of pseudocode would be very helpful. I am just beginning to learn recursion and up until this problem I haven't had too much of an issue.

Upvotes: 3

Views: 7924

Answers (8)

Yusuf
Yusuf

Reputation: 337

A small adding on Steven's solution, you can use StringBuffer/StringBuilder.reverse() for reversing a string.

 public String swapPairs(String s) {
    if (s.length() < 2)
        return s;
    else {
        return new StringBuffer(s.substring(0, 2)).reverse().toString() + swapPairs(s.substring(2));
    }
}

Upvotes: 0

James
James

Reputation: 1

public static String swapPairs(String s) {
    String even = "";
    String odd = "";
    int length = s.length();

    for (int i = 0; i <= length-2; i+=2) {          
        even += s.charAt(i+1) + "" + s.charAt(i);
    }

    if (length % 2 != 0) {          
        odd = even + s.charAt(length-1);
        return odd;
    } else {
        return even;
    }
}

Upvotes: 0

Ricky Gummadi
Ricky Gummadi

Reputation: 5230

Ok Here is my solution. I dont have Java at my disposal so I did it in C# which is very similar to Java so should be easy to understand/port;

 public static char[] exchangePairs(char[] charArray, int current)
        {
            if(current >= charArray.Length - 1)
            {
                return charArray;
            }

            char nextChar = charArray[current + 1];
            char currentChar = charArray[current];

            charArray[current] = nextChar;
            charArray[current + 1] = currentChar;

            int i = current + 2;

            return exchangePairs(charArray, i);
        }

Call to the method:

exchangePairs("abcdefghij".ToCharArray(), 0);

Upvotes: 0

Ingo
Ingo

Reputation: 36339

You're not just beginning to learn recursion, because recursion is part of your everyday live. You just don't notice, because it is so normal and nobody calls it recursion.

For example, you watch a movie on TV, and in one scene there is someone watching a movie on TV.

In programming, recursion is a way to make hard things easy. Always start with the easy case:

  • What is the result of exchangePairs("")?
  • What is the result of exchangePairs("x") where x is any character?
  • Suppose you have already completed exchangePairs(), how would the result be for "xy..." where "..." is any string? Surely "yx+++", where "+++" is the result of exchangePairs("...").

Now, it turns out that we've covered all cases! Problem solved! Such is the greatness of recursion. You just use your function as if it were complete despite you've not completed it yet.

Upvotes: 1

Jkh2
Jkh2

Reputation: 1030

Use tail recursion

String reverse(String input)
{
   if(String.length()==1)
   {
     return input;
   }
   else
   {
      return reverse(input,"");
   }
}

String reverse(String input, String result)
{
   if(input.length == 0) return result;
   else return result(input.substring(1),input.charAt(0) + result);
}

Upvotes: 0

daxnitro
daxnitro

Reputation: 920

Why use recursion?

for (int i = 0; i + 1 < strlen(str); ++i) {
    char tmp = str[i + 1];
    str[i + 1] = str[i];
    str[i] = tmp;
} 

If you have to use recursion, I suppose you could do something like this:

char* exchangePairs(char* str) {
    if (strlen(str) >= 2) {
        // if there are characters left, swap the first two, then recurse
        char tmp = str[1];
        str[1] = str[0];
        str[0] = str[1];

        exchangePairs(str + 2);
    }

    return str;
}

That's in C, but it should give you the idea (I'm better in C and didn't want to just give you a copy/pasteable solution).

Upvotes: 0

Steven
Steven

Reputation: 2477

public String swapPairs(String s) {
     if (s.length() < 2)
          return s;
     else
          return swap(s.charAt(0), s.charAt(1)) + swapPairs(s.substring(2));
}

Upvotes: 6

Ted Hopp
Ted Hopp

Reputation: 234795

I'd introduce an integer recursion control variable which is how much of the string has already been exchanged. At each level, check the control variable to see if there's more to do and, if so, exchange the next pair, increment by 2, and recurse.

Upvotes: -2

Related Questions