Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.rmb;
- import java.util.Random;
- /**
- * Test of recursion using the idea of a brute force password attack by
- * generating all permutations of a sequence of characters until we find the
- * correct one.
- */
- public class RecursionTest {
- public static void main(String[] args) {
- RecursionTest rt = new RecursionTest(4);
- rt.checkWord("");
- }
- /**
- * @param theMaxLength
- * how many characters should our target words have
- */
- public RecursionTest(int theMaxLength) {
- maxLength = theMaxLength;
- }
- /** Build up words as permutations of all characters in this sequence. */
- private final String seq = "0123456789abcdefghijklmnopqrstuvwxyz";
- /** How long should our target word be. */
- private int maxLength = 0;
- /** Have we finished? */
- private boolean solved = false;
- /**
- * If currentWord is one less than the correct length, go through every
- * letter in the sequence, adding that letter to the word (making it the
- * correct length) and check it to see if we have the correct work (changing
- * solved to true). If currentWord is less than
- * <em>one less than the correct length</em> call this function again for
- * every letter in the sequence.
- *
- * @param currentWord
- * word to check or build next character onto
- */
- private void checkWord(String currentWord) {
- // If puzzle was already marked as solved, stop.
- if (solved) {
- return;
- }
- // If word is one less than the correct length.
- if (currentWord.length() == (maxLength - 1)) {
- // Go through every letter in the sequence.
- for (int index = 0; index < seq.length(); index++) {
- // Make a word of the correct length by adding next character
- // in the sequence.
- String newPass = currentWord + seq.charAt(index);
- // Check if it is correct.
- if (wordCorrect(newPass)) {
- // It is! Wow, we are done then.
- solved = true;
- return;
- }
- }
- } else {
- // Word is not long enough. Go through every letter in the sequence.
- for (int index = 0; index < seq.length(); index++) {
- // Add next letter to the word and call this function again.
- String newPass = currentWord + seq.charAt(index);
- checkWord(newPass);
- }
- }
- }
- /**
- * This check is completely random because this is just testing code. There
- * is a 1 in 300 chance that the word will be correct.
- *
- * @param currentWord
- * word to check
- * @return true if word is the one we are looking for, false otherwise.
- */
- private boolean wordCorrect(final String currentWord) {
- Random random = new Random();
- if (random.nextInt(300) == 0) {
- System.out.println(currentWord + " correct!");
- return true;
- }
- System.out.println(currentWord + " ...");
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement