Skip to content

Instantly share code, notes, and snippets.

@MohammedAbuissa
Last active January 14, 2017 20:44
Show Gist options
  • Save MohammedAbuissa/b39e7db0d7a9b33465a9b70c442fab55 to your computer and use it in GitHub Desktop.
Save MohammedAbuissa/b39e7db0d7a9b33465a9b70c442fab55 to your computer and use it in GitHub Desktop.
This code shows a way to use switch statement instead of if statement by encoding conditons results as int. The motivation, behind this, is that switch statements normally have better performance than if statement, because compilers create a table of function pointer for switch which avoids the branching that normally slow down the execution of …
using System.Diagnostics;
class Solution {
static Dictionary<bool, int> BoolToInt = new Dictionary<bool, int>()
{
{false, 0},
{true,1}
};
public static void Main(String[] args) {
var conditions = new List<Func<int, bool>>();
conditions.Add(x => x % 2 == 0);
conditions.Add(x => x >= 0);
conditions.Add(x => x < 100);
var n = int.Parse(Console.ReadLine());
var result = ConditionToInt(conditions, n);
switch (result)
{
case 8:
Console.WriteLine("rejected number");
break;
case 9:
Console.WriteLine("Less than 100");
break;
case 10:
Console.WriteLine("Positive");
break;
case 11:
Console.WriteLine("Positive Less Than 100");
break;
case 12:
Console.WriteLine("Even");
break;
case 13:
Console.WriteLine("Even Less than 100");
break;
case 14:
Console.WriteLine("Even Positive");
break;
case 15:
Console.WriteLine("Even Positive Less Than 100");
break;
}
}
static int ConditionToInt<TData>(List<Func<TData, bool>> conditions, TData operand)
{
int combinedConditions = 1;
for (int i = 0; i < conditions.Count; i++)
{
combinedConditions = (combinedConditions << 1) + (BoolToInt[conditions[i](operand)]);
}
return combinedConditions;
}
}
Solution.Main(null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment