如何从列表>中选择不同的列表?
嗨,我正在开发一个简单的类来组合任何类型的项目...这是一个扑克游戏,它看起来是这样的:
public static List<List<T>> combinar<T>(List<T> items, int take)
{
List<List<T>> combs = new List<List<T>>();
var stuff = permutar<T>(items, take);
var all = from s in stuff
select new Tuple<List<T>, string>(s, String.Join("", s.OrderBy(c => c).Select(c => c.ToString())));
var strs = all.Select(s => s.Item2).Distinct();
foreach (var str in strs)
{
combs.Add(all.First(a => a.Item2 == str).Item1);
}
return combs;
}
public static List<List<T>> permutar<T>(List<T> list, int take)
{
List<List<T>> combs = new List<List<T>>();
foreach (var item in list)
{
var newlist = list.Where(i => !i.Equals(item)).ToList();
var returnlist = take <= 1 ? new List<List<T>> { new List<T>() } : permutar(newlist, take - 1);
foreach (var l in returnlist)
{
l.Add(item);
}
combs.AddRange(returnlist);
}
return combs;
}
所以排列工作完美..但是当 T 是 Card 时,我在组合方面遇到了一些麻烦需要花费大量时间才能完成......所以我的问题是如何从排列结果中选择不同的列表???
这是卡类:
public class Card : IComparable
{
Suite _Suite;
public Suite Suite
{
get { return _Suite; }
set { _Suite = value; }
}
Grade _Grade;
public Grade Grade
{
get { return _Grade; }
set { _Grade = value; }
}
string _symbol;
public string Symbol
{
//stuff
}
public PictureBox Picture
{
//stuff
}
public override string ToString()
{
return _Grade.ToString() + " " + _Suite.ToString();
}
public int CompareTo(object obj)
{
Card card = (Card)obj;
return card.Grade > this.Grade ? -1 : card.Grade < this.Grade ? 1 : 0;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您不想进行任何重大的算法更改,那么您最大的问题是
这没有任何意义。也许你的意思是
但是,那会很慢;如果这就是您想要的,您应该将
all
的结果放入以字符串为键的哈希表中,并使用它而不是循环遍历Distinct
结果。如果你想在不先计算排列的情况下获得组合,方法如下。给定一些对象,找到长度为 K 的组合:如果 K 为 0,则返回空列表。否则,对于每个对象,获取该对象,然后递归地追加其余对象的所有 K 减 1 长度组合。
Assuming you don't want to make any big algorithmic changes, your biggest problem here is
That doesn't make any sense. Perhaps you meant
However, that would be very slow; if that's what you want, you should put the results of
all
into a hash table keyed by the string, and use that instead of looping throughDistinct
results.If you wanted to get combinations without computing permutations first, the way to do it would be like this. Given some objects, to find the combinations of length K: if K is 0, return the empty list. Else, for each object, take that object, and then recursively append all the K-minus-1-length combinations of the rest of the objects.