Permutations of a String

void permutate( char[] str, int index )
{
    int i = 0;
    static lastChar = 0;
    if( index == strlen(str) )
    { // We have a permutation so print it
        printf(str);
        return;
    }
    // Permutate once without any swaps.
    permutate( str, index + 1 );
    lastChar = str[index];
    for( i = index + 1; i < strlen(str); i++ )
    {
        if( lastChar == str[i] ) {
            continue;
        } else {
            lastChar = str[i];
        }
        swap( str[index], str[i] ); // It doesn't matter how you swap.
        permutate( str, index + 1 );
        swap( str[index], str[i] );
    }
}

permutate( sort("Hello World"), 0 );

Comments

Popular posts from this blog

Pick a Random Byte

The Fox and The Duck

First Non-Repeated Character