Sansa and XOR

Sort by

recency

|

45 Discussions

|

  • + 0 comments

    Python 3

    from functools import reduce
    from operator import xor
    
    
    def sansaXor(arr: list[int]) -> int:
        return reduce(xor, arr[::2]) if len(arr) % 2 else 0
    
  • + 0 comments

    Pythonic 1 liner:

    return reduce(lambda res, i: res ^ arr[i], range(0, len(arr), 2), 0) if len(arr) % 2 else 0
    
  • + 0 comments

    XOR for array with even number of elements is always 0

    def sansaXor(arr):

    arr_len = len(arr)
    if arr_len % 2 == 0:
        return 0
    c = 0
    for i in range(arr_len):
        if i % 2 == 0:
            c ^= arr[i]
    return c
    
  • + 0 comments

    c++, crazy Sansa, nice

    int sansaXor(vector<int> arr) {
        const int n = arr.size();
        
        if (n % 2 == 0)
        {
            return 0;
        }
        
        int x = 0;
        
        for (int i = 0; i < n; i += 2)
        {
            x ^= arr[i];
        }
        
        return x;
    }
    
  • + 0 comments

    Java, O(n)

    public static int sansaXor(List<Integer> arr) {
            int n = arr.size();
            if (n % 2 == 0) {
                return 0; 
            } else {
                int result = 0;
                for (int i = 0; i < n; i += 2) {
                    result ^= arr.get(i); 
                }
                return result;
            }
        }