【问题标题】:How to perform List of boolean expression together in recursion如何在递归中一起执行布尔表达式列表
【发布时间】:2019-10-03 12:10:14
【问题描述】:

我有一个boolstring 中的Dictinary,其中包含一个操作并希望以递归方式获取输出,如何实现这一点。

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

【问题讨论】:

    标签: c# algorithm recursion


    【解决方案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;
    

    【讨论】:

    • 这太棒了。正是我想要的。
    【解决方案2】:

    由于 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));
    

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      • 2010-09-21
      相关资源
      最近更新 更多