Skip to content

Instantly share code, notes, and snippets.

@lamchau
Created June 8, 2014 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamchau/3cc46e074e8bbc8ee28a to your computer and use it in GitHub Desktop.
Save lamchau/3cc46e074e8bbc8ee28a to your computer and use it in GitHub Desktop.
package com.lchau;
public class Permutations {
public static void main(String[] args) {
String str = "Hello, world";
Permutations.permute(0, str.length() - 1, str.toCharArray());
}
private static boolean match(int i, int j, char[] chars) {
if (i != j) {
for (; i < j; i++) {
if (chars[i] == chars[j]) {
return true;
}
}
}
return false;
}
private static void permute(int index, int length, char[] str) {
if (index == length) {
System.out.println(new String(str));
return;
}
for (int i = index; i <= length; i++) {
if (Permutations.match(index, i, str)) {
continue;
}
Permutations.swap(index, i, str);
Permutations.permute(index + 1, length, str);
Permutations.swap(index, i, str);
}
}
private static void swap(int i, int j, char[] str) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment