Tuesday, September 3, 2013

Recursively Calculate All Possible Pairs in CSharp

A friend of mine challenged me with an algorithm that could find all possible computational pairs within a given list consecutively printing them out. Of course, the challenge was to do this using only one method and all recursion. It took me about 30 minutes before I finally got the code working and though it may not print in 'alphabetically order,' it does just the what I need! I was surprised that this algorithm from for-loops could become such a challenge when attempted with recursion - but that may just be me... trying to wrap my brain around it.


Here is the code:
(It takes a list of any length and prints all possible computational pairs recursively)

static void Function(List<String> list, int z = -1, int x = -1)
{
    if (x == -2 || z == -2) { x = list.Count; z = 0; }

    x--;
    if (x >= z) Function(list, z, x);
    else
    {
        z++;
        x = list.Count - 1;
        if (z < list.Count-1) Function(list, z, x);
    }
         
    Console.Write("{0}-:-{1}, ", list[z], list[x]);
}



And here would be the output for a list of strings { "A", "B", "C", "D"}:

D-:-D, C-:-D, C-:-C, B-:-D, B-:-C, B-:-B, A-:-D, A-:-C, A-:-B, A-:-A

No comments:

Post a Comment