Brute-Force

Brute-Force algorithm (a.k.a brute-force search, exhaustive search) is a very general problem-solving technique that consists of systematically enumerating all possible candidates for the solution and checking whether each candidate satisfies the problem's statement.



									/*****Please include following header files*****/
// stdlib.h
// stdbool.h
// string.h
/***********************************************/

bool BruteForceTest(char* testChars)
{
	bool b = strcmp(testChars, "bbc") == 0;
	return b;
}

int IndexOf(char* str, char chr)
{
	int len = strlen(str);

	for (int i = 0; i < len; ++i)
		if (str[i] == chr)
			return i;

	return -1;
}

bool BruteForce(char* testChars, int startLength, int endLength, bool(*testCallback)(char*))
{
	for (int len = startLength; len <= endLength; ++len)
	{
		char* chars = (char*)malloc(len);

		int i;
		for (i = 0; i < len; ++i)
			chars[i] = testChars[0];

		chars[i + 1] = '\0';
		if (testCallback(chars))
			return true;

		for (int i1 = len - 1; i1 > -1; --i1)
		{
			int i2 = 0;
			int testCharsLen = strlen(testChars);

			for (i2 = IndexOf(testChars, chars[i1]) + 1; i2 < testCharsLen; ++i2)
			{
				chars[i1] = testChars[i2];
				chars[i1 + 1] = '\0';

				if (testCallback(chars))
					return true;

				for (int i3 = i1 + 1; i3 < len; ++i3)
				{
					if (chars[i3] != testChars[testCharsLen - 1])
					{
						i1 = len;
						goto outerBreak;
					}
				}
			}

		outerBreak:
			if (i2 == testCharsLen)
				chars[i1] = testChars[0];
		}
	}

	return false;
}
								


Example

									bool result = BruteForce("abcde", 1, 5, BruteForceTest);
								


Output

									true