Recursive Permutations

Recursion is a type of programming loop, one that’s deliberately designed to drive some programmers nuts. It’s also a great way to replace nested loops, such as those used in last week’s Lesson.

Back in 2014, I write a series of Lessons on recursion, which can help you to understand the concept if it’s bone-dry. In a nutshell, a recursive function calls itself. The function can keep calling itself to repeat whatever action is necessary. Eventually an end condition unwinds all the calls, returning back to sanity.

For nested loops, recursion presents a solution that allows you to perform calculations when you don’t know the exact number of nested loops required.

As an example, suppose your code must crack a password n characters long. If you knew that n couldn’t be greater than 24, then you write 24 nested for loops and craft some way that the generated string could match the target string. That solution works, but it’s a lot of overhead and repetition. Any experienced programmer recognizes that repetition in the code begs for a more elegant solution.

The following code sets up recursion in the compare() function. The example omits the recursive function, which I’ll cover in next week’s Lesson.

#include <stdio.h>
#include <string.h>

#define TRUE 1
#define FALSE 0

int compare(int pos,int len,char *s1,char *s2);

int main()
{
    char password[24] = "\0";
    char brute[24] = "\0";
    int length;

    /* fetch the password */
    printf("Type a password (23 chars max): ");
    scanf("%24s",password);
    length = strlen(password);

    /* start the recursive comparison */
    compare(0,length,brute,password);

    return(0);
}

int compare(int pos,int len,char *s1,char *s2)
{
    return(FALSE);
}

The code initializes two buffers at Lines 11 and 12. The user is prompted to type a password at Line 16. That’s the text the program’s code attempts to match. The text’s length is calculated at Line 18 and stored in the length variable.

The recursive function compare() is called at Line 21. Its arguments are pos, which is a position indicator for the guessing string brute; len, the length of the target string, password; and the two buffers.

The stub for the compare() function simply returns the FALSE constant. Next week, I’ll fill in the function, which serves two purposes: First to build the guessing string (brute) and to compare it with the target string, password.

If you want a preview, you can click here to see the code from next week’s Lesson. You’ll have to wait until next week, however, to read my explanation of how it works.

Leave a Reply