c# - 如何在递归中一起执行 bool 表达式列表

标签 c# algorithm recursion

我有一个 dictinaryboolstring 包含一个操作,我想以递归方式获取输出如何实现。

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 之间使用的操作是第一个,在它们的输出到第三个之间使用的操作是第二个。最后的关键元素操作将被忽略。 提前致谢。

最佳答案

首先,让我们提取模型(给定一个名称,例如“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 的帮助下进行聚合(注意,最后一个运算 - “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;

关于c# - 如何在递归中一起执行 bool 表达式列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218830/

相关文章:

PHP:获取当前数组键?

typescript - 递归函数的类型

Python:使用递归来查看一个字符串是否是另一个字符串的旋转

c# - 使用正则表达式查找具有随机顺序的可选组

c# - 如何使用一致的语法重写此 LINQ 表达式?

c# - 从数据点c#计算指数增长方程

c# - 我应该把我的存储库放在哪一层?

python - 动画网络图以显示算法的进度

javascript - JavaScript 中变量错误的非线性回归

arrays - 查找修改数组以满足条件的最小操作集