Java Data Type How to - Create all possible combination of words








Question

We would like to know how to create all possible combination of words.

Answer

import java.util.Arrays;
/*from  w w w .  j a  v a2  s. com*/
public class Main {
  static String[] c;
  public static void main(String[] args) {
    c = Arrays.asList("a", "b", "c").toArray(new String[0]);
    permutation(0);
  }
  static void swap(int pos1, int pos2) {
    String temp = c[pos1];
    c[pos1] = c[pos2];
    c[pos2] = temp;
  }
  public static void permutation(int start) {
    if (start != 0) {
      for (int i = 0; i < start; i++){
        System.out.print(c[i]);
      }
      System.out.println();
    }
    for (int i = start; i < c.length; i++) {
      swap(start, i);
      permutation(start + 1);
      swap(start, i);
    }
  }
}