javaarraysbooleanxornim-game

Java operations on an array of integers


I'm considering an array of integers in Java. The array size is determined at the start of the program by the user

My idea idea is that - given any position for the corresponding binary values - the result should show 1 for any bit where only one of the operands has a 1 and 0 for any other combination. The process can be better explained by the following examples

An array such {4,5,6} should return 3 because:

  100
  101
  110
  ---
= 011

OR for the numbers {12,4,9}

12 = 1100
 4 = 0100
 9 = 1001
---------
Val- 0001

I thought of doing it this way but I realized that - since I worked with XOR - my code for the first example will return 7 :

static void cpuTurn(int[] nimArray){
    int[] val = new int[nimArray.length];
    int holding = 0;

    for (int i = 0; i < nimArray.length; i++) {
        holding = holding^nimArray[i];
    }
}

How to implement this operation correctly?


Solution

  • Understand this way:

    holding = 0
    at 4:
    holding = holding ^ 4; // 0 ^ 4 = 4 i.e. holding = 4, binary => 0 ^ 100 = 100  
    at 5:
    holding = holding ^ 5; // 4 ^ 5 = 1 i.e. holding = 1, binary => 100 ^ 101 = 1 
    at 6:
    holding = holding ^ 6; // 1 ^ 6 = 7 i.e. holding = 7, binary => 1 ^ 110 = 111 
    

    Thus final value of holding is 7.

    If you want to set more than two 1 appearances to 0

        public static int[] split(int num){
            int[] splits = new int[31]; 
            for(int i=0; i < 31; ++i){
                splits[i] = (num>>i & 1);
            }
            return splits;
        }
    
        static void cpuTurn(int[] nimArray){
            int[] val = new int[nimArray.length];
            int holding = 0;
            int [] holdings = split(holding);
            for (int i = 0; i < nimArray.length; i++) {
                int [] splits = split(nimArray[i]);
                for(int j = 0; j < splits.length; ++j)
                     holdings[j]+=splits[j]
            }
    
            int [] newVal = new int[31];
            int k =0;
            for(k = 0; k < 31; ++k)
                if(holdings[k]>1 || holdings[k]==0)
                    newVal[k] = 0;
                else
                    newVal[k] = 1;
    
            int finalValue = 0;
            for(k = 0; k < 31; ++k)
                 finalValue |= newVal[k]<<k;
    
            System.out.println(finalValue);
    
        }