作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
(顺便说一句,圣诞快乐 ^^)
这是我的问题(在 JAVA 中),但这绝对是一个算法问题,我不知道如何解决它:/举个例子(仅供引用,我所有的计算都是二进制的,所以 1+1 = 0)
让我们命名变量:
N : the number of elements in kernel.
M : the length of an element in the kernel.
int[][] Kernel:
....
i : 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 0 1 0 1 1 1 0 (length = M)
i+1 : 1 0 1 0 1 1 0 1 0 1 0 0 0 0 0 1 0 1 0 1 1 0 1 0 1 (length = M)
....
N : ....
我对这些东西的目标是生成所有可能的组合(所以 2^N 个元素)我想生成它们。通过生成我的意思就是这个:
Result[0] = 0 0 0 0 0 0 0 0 0 0 0 0 0
Result[1] = Kernel[0]
Result[2] = Kernel[1]
....
Result[i] = Kernel[i-1]
Result[N-1] = Kernel[N-2]
Result[N] = Kernel[0] + Kernel[1]
Result[N+1] = Kernel[0] + Kernel[2]
Result[N+i] = Kernel[0] + Kernel[i]
Result[2N-1] = Kernel[0] + Kernel[N-1]
....
Result[I] = Kernel[0] + Kernel[1] + Kernel[2]
Result[I+1] = Kernel[0] + Kernel[1] + Kernel[i]
Result[I+J] = Kernel[0] + Kernel[1] + Kernel[N-1]
....
Result[2^N+1] = Kernel[0] + Kernel[1] + ... + Kernel[i] + ... + Kernel[N-1]
这是我已经成功完成的事情,但还不完整,我不知道如何概括计算以便处理任何 N...
public static int[][] combinaisons(int[][] kernel) {
/* if the kernel is empty, there is no possible combinaison */
if(kernel.length == 0) return kernel;
/* We allocate the good number of space... */
int[][] result = new int[(int) (Math.pow(2, noyau.length)+1)][];
/* Every element in result has the same length as in kernel's elements. */
for(int i = 0; i < resultat.length; i++) {
result[i] = new int[kernel[0].length];
}
/* The first element of result has to be only 0 0 0 0 0 0 0 */
for(int j = 0; j < kernel[0].length; j++) {
result[0][j] = 0;
}
/* We rewrite the element of kernel because they are a part of the solution... */
for(int i = 0; i < kernel.length; i++) {
for(int j = 0; j < kernel[i].length; j++) {
result[i+1][j] = kernel[i][j];
}
}
/*
I managed to do it when it's the sum of only 2 elements,
but it has to be with 3, 4 ... N-1 :/
*/
for(int i = 0; i < kernel.length; i++) {
for(int j = 0; j < kernel[i].length; j++) {
for(int k = i+1; k < kernel.length; k++) {
result[k*kernel.length+i][j] = (kernel[i][j]+kernel[k][j])%2;
}
}
}
return result;
}
编辑:
举个例子:
N = 2
M = 4
Kernel:
0 1 1 0
1 0 0 1
In result I want:
0 0 0 0
0 1 1 0
1 0 0 1
1 1 1 1 (the sum of the 2 elements in Kernel)
所以这是一个简单的例子(非常特别的值,如果你想要更大的,就问 :) )
即使最后的数组看起来非常大 :) 这正是我想要生成的(不关心内存,它肯定没问题)
最佳答案
我将使用 boolean[][]
而不是 int[][]
。 0
表示false
,1
表示true
。
public static boolean[][] combinations(boolean kernel[][]) {
int n = kernel.length;
int m = kernel[0].length;
int p = 1 << n;
boolean[][] temp = new boolean[p][m];
for (int i = 0; i < p; i++)
for (int j = 0; j < n; j++)
if (((1 << j) & i) != 0)
for (int k = 0; k < m; k++)
temp[i][k] ^= kernel[j][k];
return temp;
}
关于java - 2^N 与整数的组合(内核),如何生成它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642283/
我是一名优秀的程序员,十分优秀!