Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to XOR all int elements of an array after reading from console?

My real purpose is to get the only array element that appears odd number of times. So I found out it can be done via XOR-ing all elements of the array. Like this:

int[] arr = { 3, 4, 7, 7, 0, 4, 0, 7, 3 };
Console.WriteLine(arr[0] ^ arr[1] ^ arr[2] ^ arr[3] ^ arr[4] ^ arr[5] ^ arr[6] ^ arr[7] ^ arr[8]);

The problem however is that the array is not given, but is being read from the console, thus I don't know how to XOR the elements after they are entered. The code I could work out so far is:

EDIT: I managed to finish the code properly, thanks to your help.

static void Main()
        {                
        int N = int.Parse(Console.ReadLine());
        long[] rectArray = new long[N];           

        for (int i = 0; i < N; i++)
        {
            rectArray[i] = long.Parse(Console.ReadLine());
        }
        long initial = rectArray[0]; 
        for (int i = 1; i < rectArray.Length; ++i)
        {
            initial ^= rectArray[i];
        }            
        Console.WriteLine(initial);
        }
}

P.S I'm real noob, so please be patient! :)

like image 927
Todo Avatar asked Nov 28 '12 19:11

Todo


3 Answers

Along the same lines as Esailija's answer, but using foreach - taking advantage of the fact that 0 ^ x == x for all values of x:

int current = 0;
foreach (int value in array)
{
    current ^= value;
}
Console.WriteLine(current);

EDIT: As noted in comments, LINQ's Aggregate method will do this too - and as we're happy to use the first two values in the first step, we don't even need to provide a seed:

int xor = array.Aggregate((x, y) => x ^ y);
like image 120
Jon Skeet Avatar answered Sep 18 '22 00:09

Jon Skeet


You could write a loop:

int initial = 0;
for( int i = 0; i < arr.Length; ++i ) {
    initial ^= arr[i];
}
Console.WriteLine( initial );
like image 23
Esailija Avatar answered Sep 21 '22 00:09

Esailija


for (int i = 0; i < rectArray.Length; i++)
{                      
    sum ^= rectArray[i];
}
like image 37
Matt Burland Avatar answered Sep 19 '22 00:09

Matt Burland