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*****/
// string
/***********************************************/

/*****Please use following namespaces*****/
// std
/*****************************************/

static bool BruteForceTest(char* testChars)
{
	string str(testChars);
	return (str == "bbc");
}

static bool BruteForce(string testChars, int startLength, int endLength, bool(*testCallback)(char*))
{
	for (int len = startLength; len <= endLength; ++len)
	{
		char* chars = new char[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;

			for (i2 = testChars.find(chars[i1]) + 1; i2 < testChars.size(); ++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[testChars.size() - 1])
					{
						i1 = len;
						goto outerBreak;
					}
				}
			}

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

	return false;
}
								


Example

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


Output

									true