Skip to content

Instantly share code, notes, and snippets.

@wesleyduff
Created March 11, 2018 03:20
Show Gist options
  • Save wesleyduff/c780e8cc2dac9206fe1f95e02c755231 to your computer and use it in GitHub Desktop.
Save wesleyduff/c780e8cc2dac9206fe1f95e02c755231 to your computer and use it in GitHub Desktop.
Get the number(s) missing from an array. C#. XOR. : Working example : https://dotnetfiddle.net/PKpGEm
using System;
public class Program
{
public static int GetMissingNumberFromArray(int[] arr)
{
Console.WriteLine("=======================");
int totalXor = 0;
int totalArrXor = 0;
for(int i = 1; i <= arr.Length + 1; i++){
totalXor ^= i;
}
Console.WriteLine("totalXor : {0}", totalXor);
foreach(int i in arr) totalArrXor ^= i;
Console.WriteLine("totalArrXor : {0}", totalArrXor);
return totalXor ^ totalArrXor;
}
public static int[] GetMissingTwoNumbers(int[] arr){
int size = arr.Length + 2;
Console.WriteLine("size : {0}", size);
long totalSum = size*(size+1)/2;
Console.WriteLine("totalSum : {0}", totalSum);
long arrSum = 0;
foreach(int i in arr) arrSum += i;
Console.WriteLine("arrSum : {0}", arrSum);
int pivot = (int)((totalSum - arrSum) / 2);
Console.WriteLine("pivot : {0}", pivot);
int totalXorRight = 0;
int totalXorArrayRight = 0;
int totalXorLeft = 0;
int totalXorArrayLeft = 0;
//find first array
for(int i = 1; i <= pivot; i++) totalXorLeft ^= i;
Console.WriteLine("totalXorLeft : {0}", totalXorLeft);
//find second
for(int i = pivot +1; i <= size; i++) totalXorRight ^= i;
Console.WriteLine("totalXorRight : {0}", totalXorRight);
foreach(int i in arr) {
if(i <= pivot){
totalXorArrayLeft ^= i;
} else {
totalXorArrayRight ^= i;
}
}
Console.WriteLine("totalXorArrayLeft : {0}", totalXorArrayLeft);
Console.WriteLine("totalXorRight : {0}", totalXorArrayRight);
return new int[] {(totalXorLeft ^ totalXorArrayLeft), (totalXorRight ^ totalXorArrayRight)};
}
public static void Main()
{
int[] testArrayMissing2 = {1,2,5,6};
int[] testArrayMissing1 = {1,2,4,5,6};
int[] missingTwoNumbers = GetMissingTwoNumbers(testArrayMissing2);
int missingOneNumber = GetMissingNumberFromArray(testArrayMissing1);
Console.WriteLine("=======================");
foreach(int i in missingTwoNumbers) Console.WriteLine("Number Missing : {0}", i);
Console.WriteLine("--------------------");
Console.WriteLine("Number Missing single : {0}", missingOneNumber);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment