Skip to main content
2 of 6
added 110 characters in body
syb0rg
  • 21.9k
  • 10
  • 113
  • 193

Brute Force Algorithm in C

This is a simple brute force algorithm I have in C. All the program does it print out every possible combination of the given alphabet for the given length.

I would prefer suggestions on how to improve the algorithm, or decrease run-time. Any other suggestions are acceptable though.

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

static const char alphabet[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";

static const int alphabetSize = sizeof(alphabet) - 1;

void bruteImpl(char* str, int index, int maxDepth)
{
    int i;
    for (i = 0; i < alphabetSize; ++i)
    {
        str[index] = alphabet[i];
        
        if (index == maxDepth - 1)
        {
            printf("%s\n", str);
        }
        else
        {
            bruteImpl(str, index + 1, maxDepth);
        }
    }
}

void bruteSequential(int maxLen)
{
    char* buf = malloc(maxLen + 1);
    int i;
    
    for (i = 1; i <= maxLen; ++i)
    {
        memset(buf, 0, maxLen + 1);
        bruteImpl(buf, 0, i);
    }
    
    free(buf);
}

int main(void)
{
    bruteSequential(3);
    return 0;
}
syb0rg
  • 21.9k
  • 10
  • 113
  • 193