Skip to content

Instantly share code, notes, and snippets.

@dgkanatsios
Last active January 6, 2016 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgkanatsios/ab9952602b980675e88d to your computer and use it in GitHub Desktop.
Save dgkanatsios/ab9952602b980675e88d to your computer and use it in GitHub Desktop.
Code to insert/check existence of an item using binary operations
static void Main(string[] args)
{
int storage = 19; //10011
int a = 1; //1
int b = 2; //10
int c = 4; //100
int d = 8;//1000
int e = 16;//10000
Console.WriteLine("--------------------------------");
Console.WriteLine("Check for the value 19 - 10011");
Console.WriteLine($"Does {storage} contain \"a\" with the value of 1? " + ((storage & a) == a)); //true
Console.WriteLine($"Does {storage} contain \"b\" with the value of 2? " + ((storage & b) == b)); //true
Console.WriteLine($"Does {storage} contain \"c\" with the value of 4? " + ((storage & c) == c)); //false
Console.WriteLine($"Does {storage} contain \"d\" with the value of 6? " + ((storage & d) == d)); //false
Console.WriteLine($"Does {storage} contain \"e\" with the value of 8? " + ((storage & e) == e)); //true
//using multiples of 2
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("Athens", (int)Math.Pow(2, 0)); //1
dict.Add("Thessaloniki", (int)Math.Pow(2, 1)); //2
dict.Add("Kozani", (int)Math.Pow(2, 2)); //4
dict.Add("Larisa", (int)Math.Pow(2, 3)); //8
dict.Add("Komotini", (int)Math.Pow(2, 4)); //16
dict.Add("Trikala", (int)Math.Pow(2, 5)); //32
dict.Add("Patra", (int)Math.Pow(2, 6)); //64
int myStorage = dict["Athens"] + dict["Komotini"] + dict["Larisa"];
Console.WriteLine("--------------------------------");
Console.WriteLine("Let's check some cities");
//does it contain Komotini?
Console.WriteLine("Does it contain Komotini? " + ((myStorage & dict["Komotini"]) == dict["Komotini"])); //true
//does it contain Larisa?
Console.WriteLine("Does it contain Larisa? " + ((myStorage & dict["Larisa"]) == dict["Larisa"]));//true
//does it contain Patra?
Console.WriteLine("Does it contain Patra? " + ((myStorage & dict["Patra"]) == dict["Patra"]));//false
Console.WriteLine("--------------------------------");
Console.WriteLine("Let's check *all* cities");
foreach (var item in dict)
{
if ((myStorage & item.Value) != 0) //check every city
Console.WriteLine($"It does contain {item.Key}");
else
Console.WriteLine($"It does not contain {item.Key}");
}
Console.WriteLine("--------------------------------");
Console.WriteLine("Let's remove Larisa");
//remove Larisa
myStorage = myStorage - dict["Larisa"];
//does it contain Larisa?
Console.WriteLine("Now, does it contain Larisa? " + ((myStorage & dict["Larisa"]) == dict["Larisa"]));
Console.ReadLine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment