通过索引Java在数组中查找异或
我有一个长度为15的字符串:“10101000000010”。我想对数组中的每一个备选索引进行如下排他性处理,如下所示
"
int s = a[3] ^ a[ 5] ^ a[ 7] ^ a[ 9] ^ a[11] ^ a[13] ^ a[15];'
//此处^一直跳过1个索引,直到字符串长度结束
"
int t = a[3] ^ a[ 6] ^ a[ 7] ^ a[10] ^ a[11] ^ a[14] ^ a[15];'
//这里^skips 2 index and lets 2 go,skips 2 lets 2 go。。。等等
我不知道如何接近这一点。制作一个参数为数组长度的方法,并让该方法返回一个整数(0或1),这主要是因为它是异或
所以为了再次澄清。。。我想对任何大小的数组都这样做。现在大概17岁
int z = a[3] ^ a[ 5] ^ a[ 7] ^ a[ 9] ^ a[11] ^ a[13] ^ a[15] ^ a[17]
这是汉明码
一个字节的数据:10011010 创建数据字,为奇偶校验位留出空间:_1 0 0 1 0 1 0 计算每个奇偶校验位的奇偶校验(a?表示设置的位位置):
位置1检查位1,3,5,7,9,11: ? _ 1 _ 0 0 1 _ 1 0 1 0. 偶数奇偶校验,因此将位置1设置为0:0 1 0 1 0 1 位置2检查位2,3,6,7,10,11:
0?1 _ 0 0 1 _ 1 0 1 0. 奇偶校验,因此将位置2设置为1:011 001 010 位置4检查位4,5,6,7,12:
01??0 0 1 _ 1 0 1 0. 奇数奇偶校验,因此将位置4设置为1:0 1 0 1 1 0 位置8检查位8,9,10,11,12:
0110101?1 0 1 0. 偶数奇偶校验,所以将位置8设置为0:01101010 代号:0111100101010
"
int d[]=new int[7];
for(int i=0;i<7;i++)
{
d[i]=sc.nextInt();
}
int p[]=new int[4];
p[0]=d[0]^d[1]^d[3]^d[4]^d[6];
p[1]=d[0]^d[2]^d[3]^d[5]^d[6];
p[2]=d[1]^d[2]^d[3];
p[3]=d[4]^d[5]^d[6];
"
# 1 楼答案
如果性能允许,我建议使用for循环。 初始化为0,然后在for循环内检查索引并执行XOR或continue
# 2 楼答案
我想尝试一些通用的解决方案
还可以指定上边界。
for
循环的条件将更改为for (... ; step<endIndex ; ...)
(或者<=
是您希望endIndex是包含的),并且endIndex
必须作为方法参数传递,否则if应该作为问题的通用解决方案如果你不想要一个步骤,而是想要连续的索引,你只需要有一个值
0
就是steps
数组,比如int steps[] = {0};
或int steps[] = {2, 0}
例如:
结果应该包含
source[2]^source[5]^source[8]
或2^5^8
另一个例子:
结果应该包含
source[0]^source[2]^source[5]^source[7]^source[10]^source[12]^source[15]^source[17]