| |
Permutation
Algorithm
The general purpose permutation algorithm presented here is a Java
implementation of the algorithm described by Rosen (Discrete
Mathematics and Its Applications).
The
"permute" logic contained within this class is extremely
elegant and efficient, however it's not particularly self-explanatory,
since it's recursive. The program permutes the contents of a copy
of the constant string iAlphabet (e.g. "abcd" in
the test run).
Output results follow the listing.
//* Permuter
//* Andrew Carson 2006
public class
Permuter {
public static void
main(String[] args) {
Permuter p = new
Permuter();
}
/* instance variables
*/
private static
String iAlphabet = "abcd";
private int
iCount = 0;
/* constructor */
public Permuter()
{
System.out.println("Permuting
\"" + iAlphabet + "\"");
char[]
value = new char[iAlphabet.length()];
for
(int i = 0; i < iAlphabet.length();
i++)
value[i] = iAlphabet.charAt(i);
permute(value, 0,
iAlphabet.length());
System.out.println(">>>
found " + iCount + " permutations <<<");
}
void
permute(char[] v, int
a, int b) {
print(v); iCount++;
for
(int i = b - 2; i >= a; i--)
{
for (int
j = i + 1; j < b; j++) {
swap(v, i, j); permute(v, i + 1, b);
}
rotate(v, i, b);
}
}
void
swap(char[] v, int a, int b)
{
char
t = v[a];
v[a] = v[b]; v[b]
= t;
}
void
rotate(char[] v, int a, int
b) {
char
t = v[a];
for
(int i = a; i < b - 1; i++)
v[i] = v[i + 1]; v[b - 1] = t;
}
void print(char[]
v) {
System.out.println("
- " + new String(v));
}
}
Permuting "abcd"
- abcd
- abdc
- acbd
- acdb
- adbc
- adcb
- bacd
- badc
- bcad
- bcda
- bdac
- bdca
- cabd
- cadb
- cbad
- cbda
- cdab
- cdba
- dabc
- dacb
- dbac
- dbca
- dcab
- dcba
>>> found 24 permutations <<<
|
|