如何在递归中一起执行布尔表达式列表

时间:2019-10-03 12:10:14

标签: c# algorithm recursion

我有一个Dictinarybool中的一个string,其中包含一个操作,并且希望递归获取输出,以实现该目标。

IDictionary<bool , string> lstIfResult = null;

假设此列表包含:

{
  { true,  "AND" },
  { false, "OR"  },
  { true,  "AND" }
}

我的代码是:

for (int i = 0; i < lstIfResult.Count(); i++)
{
    bool res = getBinaryOprResult(lstIfResult.ElementAt(i) , lstIfResult.ElementAt(i + 1));
}

private static bool getBinaryOprResult(KeyValuePair<bool, string> firstIfResult, 
                                       KeyValuePair<bool, string> secondIfResult)
{
    switch (firstIfResult.Value)
    {
        case "AND":
            return firstIfResult.Key && secondIfResult.Key;
        case "OR":
            return firstIfResult.Key || secondIfResult.Key;
        default:
            return false;
    }
}

我该如何递归此函数以使键元素1等于2,然后其结果等于第三个。 在1和2之间使用的运算是第一,在其输出到第三之间的运算是第二。最后一个关键元素操作将被忽略。 预先感谢。

2 个答案:

答案 0 :(得分:1)

首先,让我们提取模型(在给定名称的情况下,例如"OR",我们返回要执行的操作):

private static Dictionary<string, Func<bool, bool, bool>> s_Operations =
  new Dictionary<string, Func<bool, bool, bool>>(StringComparer.OrdinalIgnoreCase) {
    {  "AND", (a, b) => a && b},
    {   "OR", (a, b) => a || b},
    {  "XOR", (a, b) => a ^ b },
    { "TRUE", (a, b) => true  },
    {"FALSE", (a, b) => false },
    //TODO: add more operations, synonyms etc.
  };

然后,您可以在 Linq 的帮助下Aggregate(注意,上一个操作-"OR"将被忽略):

using System.Linq;

...

// I've created list, but any collection which implements
// IEnumerable<KeyValuePair<bool, string>> will do
IEnumerable<KeyValuePair<bool, string>> list = new List<KeyValuePair<bool, string>>() {
  new KeyValuePair<bool, string>( true, "AND"),
  new KeyValuePair<bool, string>(false,  "OR"),
  new KeyValuePair<bool, string>( true,  "OR"),
};

...

// ((true && false) || true) == true
bool result = list
 .Aggregate((s, a) => new KeyValuePair<bool, string>(
    s_Operations[s.Value](s.Key, a.Key), 
    a.Value))
 .Key;

答案 1 :(得分:0)

由于for循环中的lstIfResult.ElementAt(i + 1),您会遇到类似“ OutOfRange”的错误。 如果要忽略最后一个元素,请尝试使用

for (int i=0; i<lstIfResult.Count-1; i++) {
bool res = getBinaryOprResult(lstIfResult.ElementAt(i) , lstIfResult.ElementAt(i+1));