更面向对象的解决方案
使用已知长度
final String target = "ABC";
final char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
BruteForce.bruteForce(charset, 5, string -> {
System.out.println(string);
return string.equals(target);
});
使用未知长度
final String target = "ABC";
final char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
// Use your looping method of choice
boolean found = false;
int length = 1;
while (!found) {
found = BruteForce.bruteForce(charset, length, string -> {
System.out.println(string);
return string.equals(target);
});
length++;
}
执行
public class BruteForce {
public static boolean bruteForce(@NonNull final char[] input, final int length, @NonNull final Closure closure) {
final char[] chars = new char[length];
final IncrementalCharSequence incrementalCharSequence = new IncrementalCharSequence(input, chars);
// Use your looping method of choice
do {
if (closure.compare(new String(chars))) {
return true;
}
} while (incrementalCharSequence.increment());
return false;
}
}
public interface Closure {
boolean compare(@NonNull final String string);
}
public class IncrementalCharSequence {
@NonNull
private final char[] input;
@Nullable
private final IncrementalCharSequence subIncrementalCharSequence;
@NonNull
private final char[] chars;
private final int index;
private int currentIndex;
public IncrementalCharSequence(@NonNull final char[] input, @NonNull final char[] chars) {
this(input, chars, 0);
}
private IncrementalCharSequence(@NonNull final char[] input, @NonNull final char[] chars, final int index) {
this.input = input;
this.chars = chars;
this.index = index;
if (index + 1 < chars.length) {
this.subIncrementalCharSequence = new IncrementalCharSequence(input, chars, index + 1);
} else {
this.subIncrementalCharSequence = null;
}
currentIndex = 0;
chars[index] = input[currentIndex];
}
/**
* Increment the char sequence
*
* @return {@code true} if incremented, {@code false} if rolled over to zero index
*/
public boolean increment() {
if (subIncrementalCharSequence != null && subIncrementalCharSequence.increment()) {
return true;
} else if (currentIndex < input.length) {
chars[index] = input[currentIndex];
currentIndex++;
return true;
} else {
currentIndex = 0;
chars[index] = input[currentIndex];
return false;
}
}
}