forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arrangements.java
105 lines (96 loc) · 3.13 KB
/
Arrangements.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package combinatorics;
import java.util.Arrays;
// https://en.wikipedia.org/wiki/Partial_permutation
public class Arrangements {
public static boolean nextArrangement(int[] a, int n) {
boolean[] used = new boolean[n];
for (int x : a) used[x] = true;
int m = a.length;
for (int i = m - 1; i >= 0; i--) {
used[a[i]] = false;
for (int j = a[i] + 1; j < n; j++) {
if (!used[j]) {
a[i++] = j;
used[j] = true;
for (int k = 0; i < m; k++) {
if (!used[k]) {
a[i++] = k;
}
}
return true;
}
}
}
return false;
}
public static int[] arrangementByNumber(int n, int m, long number) {
int[] a = new int[m];
int[] free = new int[n];
for (int i = 0; i < n; i++) {
free[i] = i;
}
for (int i = 0; i < m; i++) {
long cnt = countOfArrangements(n - 1 - i, m - 1 - i);
int pos = (int) (number / cnt);
a[i] = free[pos];
System.arraycopy(free, pos + 1, free, pos, n - 1 - pos);
number %= cnt;
}
return a;
}
public static long numberByArrangement(int[] a, int n) {
int m = a.length;
long res = 0;
boolean[] used = new boolean[n];
for (int i = 0; i < m; i++) {
int cnt = 0;
for (int j = 0; j < a[i]; j++) {
if (!used[j]) {
++cnt;
}
}
res += cnt * countOfArrangements(n - i - 1, m - i - 1);
used[a[i]] = true;
}
return res;
}
public static long countOfArrangements(int n, int m) {
long res = 1;
for (int i = 0; i < m; i++) {
res *= n - i;
}
return res;
}
public static boolean nextArrangementWithRepeats(int[] a, int n) {
for (int i = a.length - 1; i >= 0; i--) {
if (a[i] < n - 1) {
++a[i];
Arrays.fill(a, i + 1, a.length, 0);
return true;
}
}
return false;
}
// Usage example
public static void main(String[] args) {
// print all arrangements
int[] a = {0, 1, 2};
int cnt = 0;
int n = 4;
do {
System.out.println(Arrays.toString(a));
if (!Arrays.equals(a, arrangementByNumber(n, a.length, numberByArrangement(a, n)))
|| cnt != numberByArrangement(arrangementByNumber(n, a.length, cnt), n))
throw new RuntimeException();
++cnt;
} while (nextArrangement(a, n));
// print all arrangements with repeats
a = new int[2];
do {
System.out.println(Arrays.toString(a));
} while (nextArrangementWithRepeats(a, 2));
a = new int[] {2, 3, 4};
System.out.println(32 == numberByArrangement(a, 5));
System.out.println(Arrays.equals(a, arrangementByNumber(5, a.length, 32)));
}
}