I was searching for a method to permute a word in java and came across this code.I'm actually learning it myself and facing some difficulty in understanding certain portions of the code :
Firstly what type of variable is this:
used = new boolean[ in .length()]
? I've never seen such a boolean variable declaration.What is the basic logic behind the functioning of this snippet?
for (int i = 0; i < in .length(); ++i) { if (used[i]) { continue; } out.append( in .charAt(i)); used[i] = true; permute(); used[i] = false; out.setLength(out.length() - 1);
THE ORIGINAL PROGRAM WAS
public class Permutations {
boolean[] used;
StringBuffer out = new StringBuffer();
String in ;
public Permutations(String str) { in = str;
used = new boolean[ in .length()];
}
public void permute() {
if (out.length() == in .length()) {
System.out.println(out);
return;
}
for (int i = 0; i < in .length(); ++i) {
if (used[i]) {
continue;
}
out.append( in .charAt(i));
used[i] = true;
permute();
used[i] = false;
out.setLength(out.length() - 1);
}
}
}