Part of a task I'm trying to solve is building all possible combinations of letters and whitespace. I'm trying to find a specific String, while building the combinations. I think i implemented the solution well, but my test tells me otherwise.
I'm taking the chars from an array and in a for loop I build a String from them, then print the solution. When I built all the combinations of let's say "1 character combinations", then i move on to "2 character combinations". I have a boolean to check if the contents of the StringBuilder is equal to the given String that i want to find. I checked, and the example String was indeed built, but the boolean didn't change.
public static void main(String[] args) throws InterruptedException {
findString("rxc");
}
public static void findString(String string) {
boolean isFound = false;
String allChars = "abcdefghijklmnopqrstuvwxyz ";
char[] sequence = allChars.toCharArray();
int lengthOfExpression = 3;
//builder contains 3 whitespaces at the beginning
StringBuilder builder = new StringBuilder(" ");
int[] pos = new int[lengthOfExpression];
int total = (int) Math.pow(allChars.length(), lengthOfExpression);
for (int i = 0; i < total; i++) {
for (int x = 0; x < lengthOfExpression; x++) {
if (pos[x] == sequence.length) {
pos[x] = 0;
if (x + 1 < lengthOfExpression) {
pos[x + 1]++;
}
}
builder.setCharAt(x, sequence[pos[x]]);
}
pos[0]++;
if (builder.toString() == string) {
isFound = true;
}
System.out.println(builder.toString());
}
System.out.println(isFound);
}
Expected result would be a 'true' printed at the end. Instead, my result is as follows:
//lots of lines of combinations omitted
r
s
t
u
v
w
x
y
z
false