-
Notifications
You must be signed in to change notification settings - Fork 522
/
WalshHadamarTransform.java
58 lines (52 loc) · 1.78 KB
/
WalshHadamarTransform.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
package numeric;
import java.util.Arrays;
public class WalshHadamarTransform {
enum Operation { XOR, OR, AND }
// calculates c[k] = sum(a[i]*b[j] | i op j == k), where op = XOR | OR | AND
// complexity: O(n*log(n))
public static int[] convolution(int[] a, int[] b, Operation op) {
transform(a, op, false);
transform(b, op, false);
for (int i = 0; i < a.length; i++) {
a[i] *= b[i];
}
transform(a, op, true);
return a;
}
static void transform(int[] a, Operation op, boolean inverse) {
int n = a.length;
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; i += 2 * step) {
for (int j = i; j < i + step; ++j) {
int u = a[j];
int v = a[j + step];
switch (op) {
case XOR:
a[j] = u + v;
a[j + step] = u - v;
break;
case OR:
a[j] = inverse ? v : u + v;
a[j + step] = inverse ? u - v : u;
break;
case AND:
a[j] = inverse ? v - u : v;
a[j + step] = inverse ? u : v + u;
break;
}
}
}
}
if (op == Operation.XOR && inverse) {
for (int i = 0; i < n; i++) {
a[i] /= n;
}
}
}
// Usage example
public static void main(String[] args) {
int[] a = {3, 2, 1, 5};
int[] b = {6, 3, 4, 8};
System.out.println(Arrays.toString(convolution(a, b, Operation.AND)));
}
}