Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive string reverse function

writing a recursive string reverse function out of curiosity, but having a bit of problem with XOR there. The whole point of this function, is to not use iterator, which is why it is a recursive function. this is not homework, just curiosity.

    private static char[] ReverseNL(char[] arr, int index)
    {
        var len = arr.Length;
        if (index > 0)
            arr[len - index] ^= arr[index - 1];
        return index-- < 1 ? arr : ReverseNL(arr, index);
    }

it seems to jamble the first part of my string

"hey there stack!" becomes "I♫→A ←E↨reht yeh"

it is always the first half of the phrase that gets jumbled...

UPDATE..

i suppose XOR wasn't really needed here.. so used basic assignment, also got rid of return.

    private static void ReverseNL(char[] arr, int index) {
        var len = arr.Length;
        if (index > 0 && index > len / 2) {
            var c = arr[len - index];
            arr[len - index] = arr[index - 1];
            arr[index - 1] = c;
            index--;
            ReverseNL(arr, index);
        }
    }
like image 826
Sonic Soul Avatar asked Dec 02 '22 04:12

Sonic Soul


1 Answers

Recursion is almost always used to make problems simpler. Recursive algorithms are typically functional in nature as well (though they don't have to be).

In the case of reversing a string (or a char[]), "simpler" means "operating on a smaller array".

For example, you can reduce as follows:

"test"
"est"   't'
"st"    'e'
"t"     's'
""      't'

(On the left is the data reduced; on the right is the cut data).

In pseudocode, you can perform the reduction as follows:

char[] reverse(char[] data) {
    if (data.Count() == 0) {
        return new char[] { };
    }

    char cut = data.First();
    char[] rest = data.Skip(1);

    char [] restReversed = reverse(rest);

    // ???
}

I'll leave it up to you to figure out what needs to be done next with the data you have.

like image 89
strager Avatar answered Dec 23 '22 16:12

strager