· 8 years ago · May 29, 2018, 07:34 AM
1package common;
2
3/**
4 *
5 * @author Joseph Short <Joseph.J.Short at gmail.com>
6 */
7public class PermutationSet {
8
9 private byte[] selection;
10 private byte choose;
11 private int totalPermutations;
12 private byte[][] permutations;
13 private int c = 0;
14
15 public PermutationSet(byte[] selection, byte choose) {
16 this.selection = new byte[selection.length];
17 this.choose = choose;
18 System.arraycopy(selection, 0, this.selection, 0, selection.length);
19 totalPermutations = (int) (Maths.factorial(selection.length)
20 / Maths.factorial(selection.length - choose));
21 permutations = new byte[totalPermutations][choose];
22
23 byte[] permutation = new byte[choose];
24 boolean[] allocation = new boolean[selection.length];
25 seek(permutation, allocation, 0);
26 }
27
28 private void seek(byte[] permutation, boolean[] allocation, int p) {
29 if (p == choose) {
30 System.arraycopy(permutation, 0, permutations[c], 0, choose);
31 c++;
32 } else {
33 for (byte i = 0; i < selection.length; i++) {
34 if (!allocation[i]) {
35 allocation[i] = true;
36 permutation[p] = selection[i];
37 seek(permutation, allocation, p + 1);
38 allocation[i] = false;
39 }
40 }
41 }
42 }
43
44 public long getTotalPermutations() {
45 return totalPermutations;
46 }
47
48 public String getPermutationAsString(int i) {
49 String result = "";
50 for (byte digit : permutations[i]) {
51 result += digit;
52
53 }
54 return result;
55 }
56
57 public byte[] getPermutation(int i) {
58 byte[] permutation = new byte[choose];
59 System.arraycopy(permutations[i], 0, permutation, 0, choose);
60 return permutation;
61 }
62}