有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过索引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];

"


共 (2) 个答案

  1. # 1 楼答案

    如果性能允许,我建议使用for循环。 初始化为0,然后在for循环内检查索引并执行XOR或continue

  2. # 2 楼答案

    我想尝试一些通用的解决方案

    int source[] = ...; // fill the source array
    int steps[] = ...; // fill the array of steps
    int startIndex = 0; // assign value of first, 0 being the first element of the array
    int result = xorMethod(startIndex, source, steps);
    
    public int xorMethod (int startIndex, int sourceArray[], int stepsArray[]) {
        // going to ignore all tests, because I'm lazy
        int xorResult = sourceArray[startindex];
        for (int i=1, step=startIndex+stepsArray[0] ; step<sourceArrray.length ; i++, step+=stepsArray[i%stepsArray.length]+1) {
            tmpInt ^= sourceArray[step];
        }
        return xorResult;
    }
    

    还可以指定上边界。for循环的条件将更改为for (... ; step<endIndex ; ...)(或者<=是您希望endIndex是包含的),并且endIndex必须作为方法参数传递,否则if应该作为问题的通用解决方案

    如果你不想要一个步骤,而是想要连续的索引,你只需要有一个值0就是steps数组,比如int steps[] = {0};int steps[] = {2, 0}

    例如:

    int source[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int steps[] = {2};
    int startIndex = 2;
    int result = xorMethod(startIndex, source, steps);
    

    结果应该包含source[2]^source[5]^source[8]2^5^8

    另一个例子:

    int source[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19};
    int steps[] = {1, 2};
    int startIndex = 0;
    int result = xorMethod(startIndex, source, steps);
    

    结果应该包含source[0]^source[2]^source[5]^source[7]^source[10]^source[12]^source[15]^source[17]