及时计算组合 [英] Just in time computation of combinations
本文介绍了及时计算组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对N个变量的三元组的每个组合做一些事情:
I want to do something with every combination of ternaries for N variables:
示例1:
T
F
U
示例2:
TT
FT
UT
TF
FF
UF
UU
是否有一种计算方法,但仅根据需要:例如:
Is there a way to compute this but only as needed: For example:
var combinator = new Combinator<string>(2, {"T","F","U"});
List<String> tt = combinator.Next();
//tt contains {"T","T"}
推荐答案
您可以在迭代器方法中实现它:
You can implement it in an iterator method:
private IEnumerable<List<T>> Combinations<T>(int n, T[] values)
{
if (n == 0) yield return new List<T>();
else
{
foreach (var list in Combinations(n - 1, values))
foreach (var item in values)
{
var items = new List<T>(list);
items.Add(item);
yield return items;
}
}
}
这会创建所有组合,但会以一种懒惰的方式进行.
This creates all combinations, but does it in a lazy way.
如果需要,可以这样创建Combinator
类:
If you want you can create Combinator
class like this:
class Combinator<T>
{
IEnumerator<List<T>> enumerator;
public Combinator(int n, T[] values)
{
enumerator = Combinations(n, values).GetEnumerator();
}
public List<T> Next()
{
return enumerator.MoveNext() ? enumerator.Current : null;
}
private IEnumerable<List<T>> Combinations<T>(int n, T[] values) { ... }
}
这篇关于及时计算组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文