0

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 :

  1. Firstly what type of variable is this: used = new boolean[ in .length()] ? I've never seen such a boolean variable declaration.

  2. 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);
    }
  }
}
  • one question per question –  May 19 '15 at 18:18
  • At most half of this question is a duplicate of the cited question, and even then, that part is about a *declaration*, not an *initialization*. – Scott Hunter May 19 '15 at 18:19
  • @JarrodRoberson i don't think so. –  May 19 '15 at 18:21
  • what part of *one question per question* is not clear, and the the duplicate explains what that syntax is pretty clearly, if it does not make sense then you probably need more information that would be **too broad** as well. As for the *rest of the question*, that should be another question, and it would be a pretty poor one at that. If you disagree **edit** the question and **improve it so it is conformant** and see what happens. –  May 19 '15 at 18:29
  • @JarrodRoberson: The cited "duplicate" does not say anything about specifying the size of the array, syntax or semantics; its does spell out how to initialize an array, which this question is not about. Try again. – Scott Hunter May 19 '15 at 19:27

1 Answers1

0
  1. It is an array of booleans.
  2. Once you find an unused character (used[i] is false), append it to out, flag it as used (used[i]=true) & permute() what is left. Once that is done, mark it as unused (used[i]=false) & remove the character you appended to out (out.setLength(out.length()-1)), so your loop can continue looking for unused characters.
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101