Java implementation of the Brute Force Algorithm
A brief code explanation:
The fCharList array holds the characters involved in the algorithm. You can add or remove characters according to your needs.
The StartBruteForce method starts a brute force word generation. The length parameter of this method determins how many characters a word can have.
The OnBruteForceWordGenerated is called for every Brute-Force generated word.
Example #1: For a length of 4 the StartBruteForce method will generate the following words "aaaa","aaab","aaac".....,"zzzz"
Example #2: For a length of 8 the StartBruteForce method will generate the following words "aaaaaaaa","aaaaaaab","aaaaaaac".....,"zzzzzzzz"
/** * * @author Nikos Siatras */ public class BruteForce { private static final char[] fCharList = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static void main(String[] args) { for (int i = 1; i < 17; i++) { StartBruteForce(i); } } /** * This method is called every time a new word is generated * * @param word is the brute force generated word */ private static void OnBruteForceWordGenerated(String word) { System.out.println(word); } /** * Start a new Brute Force * * @param length is the words length (how many characters a word can have) */ private static void StartBruteForce(int length) { StringBuffer sb = new StringBuffer(length); char currentChar = fCharList[0]; for (int i = 1; i <= length; i++) { sb.append(currentChar); } ChangeCharacters(0, sb, length); } private static StringBuffer ChangeCharacters(int pos, StringBuffer sb, int length) { for (int i = 0; i <= fCharList.length - 1; i++) { sb.setCharAt(pos, fCharList[i]); if (pos == length - 1) { // Write the Brute Force generated word. OnBruteForceWordGenerated(sb.toString()); } else { ChangeCharacters(pos + 1, sb, length); } } return sb; } }
0 comments:
Post a Comment