TruthTables.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using ExpressionLib.Contexts;
  6. namespace ExpressionLib
  7. {
  8. public class TruthTables
  9. {
  10. public static void PrintTable(string expression)
  11. {
  12. Evaluator<bool> eval = new Evaluator<bool>(expression, new ExpressionLib.Contexts.SimpleLogic());
  13. foreach (string var in eval.Variables)
  14. Console.Write("| " + var + " ");
  15. Console.WriteLine("| " + expression);
  16. Console.WriteLine();
  17. Permutations(eval.Variables, (vals) => {
  18. foreach ( bool v in vals.Values )
  19. Console.Write("| " + SimpleLogic.ToString(v) + " ");
  20. Console.WriteLine("| " + SimpleLogic.ToString(eval.Eval(vals)));
  21. });
  22. Console.WriteLine();
  23. }
  24. delegate void processorFunc(Dictionary<string, bool> vals);
  25. private static void Permutations(List<string> vars, processorFunc func)
  26. {
  27. var dict = new Dictionary<string, bool>();
  28. foreach (string name in vars)
  29. dict.Add(name, false);
  30. Permutations(0, vars, dict, func);
  31. }
  32. private static void Permutations(int index, List<string> vars, Dictionary<string, bool> vals, processorFunc func)
  33. {
  34. for ( int b = 0; b <= 1; b++ )
  35. {
  36. vals[vars[index]] = ( b == 1 );
  37. if (index < vars.Count - 1)
  38. Permutations(index + 1, vars, vals, func);
  39. else
  40. func(vals);
  41. }
  42. }
  43. }
  44. }