Skip to content

Instantly share code, notes, and snippets.

@tbodt
Created July 23, 2014 00:21
Show Gist options
  • Save tbodt/f9e19cee3a64f2752eed to your computer and use it in GitHub Desktop.
Save tbodt/f9e19cee3a64f2752eed to your computer and use it in GitHub Desktop.
Print all anagrams
public class Anagrams {
public static void main(String[] args) {
String start = args[0];
String anagram = start;
do {
System.out.println(anagram);
anagram = nextAnagram(anangram);
} while (!start.equals(anagram))
}
public static String nextAnagram(String word) {
StringBuilder sb = new StringBuilder(word);
for (int i = sb.length() - 1; i > 0; i--) {
if (sb.charAt(i - 1) < sb.charAt(i)) {
int j = sb.length() - 1;
while (sb.charAt(i - 1) > sb.charAt(j))
j--;
swap(sb, i - 1, j);
reverse(sb, i, sb.length() - 1);
return sb.toString();
}
}
reverse(sb, 0, sb.length() - 1);
return sb.toString();
}
private static void swap(StringBuilder sb, int i, int j) {
char temp = sb.charAt(i);
sb.setCharAt(i, sb.getCharAt(j));
sb.setCharAt(j, temp);
}
private static void reverse(StringBuffer sb, int i, int j) {
while (i < j) {
swap(sb, i, j);
i++;
j--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment