循环 - 控制流程,用于处理2个未知长度的列表

时间:2014-03-19 13:35:36

标签: c# control-flow

假设2个未知的字符串列表,可能长度不同。 第二个列表中的项目必须与第一个列表中的项目匹配,但匹配可能取决于以下项目的内容:

列出lst_1: [0] Apple [1]橙色 [2]桃子 [3] ......

列出lst_2: [0]盐 [1]龙舌兰酒 [2]亲爱的 [3]伏特加 [4]威士忌 [5] ......

lst_1中的项目必须根据几个条件与lst_2中的项目匹配。例如,对于每种水果,必须至少有一种酒;威士忌不能搭配桃子;在任何给定的鸡尾酒等中必须少于5种醇。

如果我将苹果与盐和龙舌兰酒,橙子加蜂蜜和伏特加酒相匹配,我会用桃子加威士忌,这会破坏其中一种条件......但如果我把苹果,龙舌兰酒和蜂蜜放在一起,我会得到橘子 - 伏特加 - 威士忌,这是一种有效的饮料。

最重要的是,我需要遍历这两个列表,每次检查当前项目的多个条件以及它对列表中的下一个项目和前一个项目的含义,我可能需要返回跟踪几次并修复一切,直到一切正常。

我在想这样一个很大的while(bNotReady){...}循环:

int i = 0;
int j = 0;
string fruit, additive;
bool bContainsAlcohol = false;
dictionary<string, string> dic = new dictionary<string,string>();
while(bNotReady){
  fruit = lst_1[i];
  additive = lst_2[j];
  if (is_valid_match(fruit,additive) && bContainsAlcohol)
  {
     dic.Add(fruit,additive);
     i++; j++;
     continue;
  }
  else if(...)

}

并且在列表中工作,但我可以看到这很快就会变成一个巨大的,不可读的循环。

是否有更好的方法来计算此任务的控制流程?

1 个答案:

答案 0 :(得分:0)

如果您决定使用约束编程路径,我认为这是一个更好的主意,但您可以使用强力和.Net集合来实现。它不会很漂亮,但应该有效。

  • 首先,您需要一种方法来将添加剂的所有可能分区枚举成基数等于成分数的集合。 [a,b,c]分为三组可以[abc,,]然后[ab,c,]然后[a,bc,]等等。
  • 枚举所有这些集合,您需要枚举这些集合的所有排列
  • 最后,对于集合的每个排列,您需要检查成分和添加剂集之间的当前匹配是否满足所有规则

我没有时间创建分区方法,但我有一个排列扩展可用,所以我创建了程序的第二步

private static IList<string> Ingredients { get; set; }
private static IList<string> Additives { get; set; }
private static IList<Func<string, string, bool>> Rules { get; set; }

private static void Main(string[] args)
{
    Ingredients = new List<string>() { "Apple", "Orange", "Peach" };
    Additives = new List<string>() { "Vodka", "Rum", "Whiskey" };
    Rules = new List<Func<string, string, bool>>() { (ingredient1, ingredient2) => { return (ingredient1 != "Peach" && ingredient2 != "Whiskey"); } };
    var additivesOrganisationMatchingAllTheRules = FindMatch();
}

private static IList<string> FindMatch()
{
    // here we should enumerate all sets and then enumerate permutation of all the sets
    // instead for the example we just enumerate the permutations
    foreach (var additivesPermutation in Additives.GetCombinations())
    {
        for (int i = 0; i < additivesPermutation.Count; i++)
        {
            var thisSituationIsOk = Rules.All(r => r(Ingredients[i], Additives[i]));
            if (thisSituationIsOk) return additivesPermutation;
        }
    }
    return null;
}

它使用置换方法扩展;从我记忆中,这个扩展名不保留初始列表。没有测试就不要使用

public static class CombinatorialExtension
{
    public static IEnumerable<IList<TSource>> GetCombinations<TSource>(
        this IList<TSource> source)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        return GetCombinationsImpl<TSource>(source);
    }

    private static IEnumerable<IList<TSource>> GetCombinationsImpl<TSource>(
        this IList<TSource> list)
    {
        return Permutations(list, list.Count);
    }

    private static void ShiftRight<TSource>(IList<TSource> list, int cardinality)
    {
        var lastElement = list[cardinality - 1];
        list.RemoveAt(cardinality - 1);
        list.Insert(0, lastElement);
    }

    private static IEnumerable<IList<TSource>> Permutations<TSource>(IList<TSource> list, int cardinality)
    {
        if (cardinality == 1)
        {
            yield return list;
        }
        else
        {
            for (int i = 0; i < cardinality; i++)
            {
                foreach (var perm in Permutations(list, cardinality - 1))
                    yield return perm;
                ShiftRight(list, cardinality);
            }
        }
    }
}

这个算法可以让你找到一个与你的成分和规则相匹配的解决方案,但它不是很漂亮,而且真的没有效率:许多组合会多次计算。您还必须调整规则以获得令人愉快的结果(即添加剂的最小和最大数量等)


修改

甚至可以避免必须创建所有组,您可以简单地在添加剂中添加尽可能多的分离剂,因为您的成分减去1。然后进行排列,根据分离器将添加剂分成添加剂列表。然后,您的规则可以采用一种成分和添加剂列表作为检查是否受到尊重的基础。这是一些示例代码

private static IList<string> Ingredients { get; set; }
private static IList<string> Additives { get; set; }
private static IList<Func<string, IList<string>, bool>> Rules { get; set; }

private static void Main(string[] args)
{
    Ingredients = new List<string>() { "Apple", "Orange", "Peach" };
    Additives = new List<string>() { "Vodka", "Rum", "Whiskey" };
    Additives.Add("Separator");
    Additives.Add("Separator"); // add as many separators as the number of ingredients - 1
    Rules = new List<Func<string, IList<string>, bool>>() {
        (ingredient1, ingredient2) => { return (ingredient1 != "Peach" && ingredient2.All(s => s != "Whiskey")); }
        , 
        (ingredient1, ingredient2) => { return ingredient2.Count > 0; }
    };
    var additivesOrganisationMatchingAllTheRules = FindMatch();
}

private static IList<IList<string>> FindMatch()
{
    // separators will create the sets
    foreach (var additivesPermutation in Additives.GetCombinations())
    {
        var Sets = Split(additivesPermutation);
        var thisSituationIsOk = true;
        for (int i = 0; i < Sets.Count && thisSituationIsOk ; i++)
        {
            thisSituationIsOk = thisSituationIsOk && Rules.All(r => r(Ingredients[i], Sets[i]));
        }
        if (thisSituationIsOk) return Sets;
    }
    return null;
}

private static IList<IList<string>> Split(IList<string> values)
{
    var splitValues = new List<IList<String>>();
    var currentList = new List<string>();
    foreach (var value in values)
    {
        if (value == "Separator")
        {
            splitValues.Add(currentList);
            currentList = new List<string>();
        }
        else
        {
            currentList.Add(value);
        }
    }
    splitValues.Add(currentList);
    return splitValues;
}