您可以使用LINQ轻松解决这类问题。
var solutions = from pair1 in listOne
where IsCandidate(pair1)
from pair2 in listTwo
where IsCandidate(pair1, pair2)
from pair3 in listThree
where IsCandidate(pair1, pair2, pair3)
from pair4 in listFour
where IsCandidate(pair1, pair2, pair3, pair4)
from pair5 in listFive
where IsCandidate(pair1, pair2, pair3, pair4, pair5)
from pair6 in listSix
where IsCandidate(pair1, pair2, pair3, pair4, pair5, pair6)
from pair7 in listSeven
where IsSolution(pair1, pair2, pair3, pair4, pair5, pair6, pair7)
select new { pair1, pair2, pair3, pair4, pair5, pair6, pair7 };
当然,这种方法是有效的,因为列表数量在编译时是已知的。另一种方法是建立可能的组合的通用方法,如Eric Lippert shows in his post。
遍及查询的所有中介where
都将尽快过滤出无效组合。
EDIT
固定溶液有效地计数相同组合多少次发生时,忽略原始源的密钥。
为了实现这一点,我将对每个字典应用一个转换。我将把每个字典转换为一个新的字典,其中键是枚举值,并且该值将是枚举值在原始字典中发生的次数。
IDictionary<MyEnum, int> CountOccurrences(IEnumerable<MyEnum> values)
{
return (from e in values group e by e).ToDictionary(grp => grp.Key, grp => grp.Count());
}
var solutions = from p1 in CountOccurrences(listOne.Values)
where IsCandidate(p1)
from p2 in CountOccurrences(listTwo.Values)
where IsCandidate(p1, p2)
from p3 in CountOccurrences(listThree.Values)
where IsCandidate(p1, p2, p3)
from p4 in CountOccurrences(listFour.Values)
where IsCandidate(p1, p2, p3, p4)
from p5 in CountOccurrences(listFive.Values)
where IsCandidate(p1, p2, p3, p4, p5)
from p6 in CountOccurrences(listSix.Values)
where IsCandidate(p1, p2, p3, p4, p5, p6)
from p7 in CountOccurrences(listSeven.Values)
where IsSolution(p1, p2, p3, p4, p5, p6, p7)
select new {
E1 = p1.Key,
E2 = p2.Key,
E3 = p3.Key,
E4 = p4.Key,
E5 = p5.Key,
E6 = p6.Key,
E7 = p7.Key,
Times = p1.Value * p2.Value * p3.Value * p4.Value * p5.Value * p6.Value * p7.Value
};
你可以定义什么样的组合看起来像你在组合上使用的一些示例逻辑?你能定义所有可能的组合的含义吗? – mellamokb 2011-05-02 17:11:47
如果该方法是通用的,那么您别无选择,只能检查每个组合,并且需要运行eon。一个短暂但典型的输入 - >输出是必要的。 – 2011-05-02 17:14:42