[英]Recursive Algorithm C#
I need some help with an algorithm using C#.我需要一些关于使用 C# 的算法的帮助。 I have a list of objects, with items multiples of 4, and I should return only the two best items.
我有一个对象列表,项目是 4 的倍数,我应该只返回两个最好的项目。 Each item has a value and a description.
每个项目都有一个值和一个描述。 I must also make comparisons to every two elements.
我还必须对每两个元素进行比较。 And I would like to call this method recursively until I have only 2 elements.
我想递归调用这个方法,直到我只有 2 个元素。
Example:例子:
CardList.Add(new Card("Name A", 150));
CardList.Add(new Card("Name B", 100));
CardList.Add(new Card("Name C", 50));
CardList.Add(new Card("Name D", 556));
CardList.Add(new Card("Name E", 170));
CardList.Add(new Card("Name F", 160));
CardList.Add(new Card("Name G", 30));
CardList.Add(new Card("Name H", 650));
public Lis<Card> BestCards(Lis<Card> list){
List<Card> listResult = new List<Card>();
for(int i=1; i<=list.lenght; i+2)
{
if(list[i].value> list[i+1].value)
listResult.Add(list[i])
else if (list[i].value< list[i+1].value)
listResult.Add(list[i+1])
else if (list[i].value==list[i+1].value)
{
// first element according to alphabetical order of the description
listResult.Add(???)
}
return listResult;
}
Any suggestion?有什么建议吗?
Using the method that you are currently using, you could be losing data, since you are getting rid of an item every time you do a comparison, without checking if it is better than the whole list.使用您当前使用的方法,您可能会丢失数据,因为每次进行比较时您都会删除一个项目,而没有检查它是否比整个列表更好。
I would suggest sorting the list, and then taking the top two items that way, or you can compare one item to every other item, and find the best two.我建议对列表进行排序,然后以这种方式取前两个项目,或者您可以将一个项目与其他每个项目进行比较,然后找到最好的两个。
This solution should meet your requirements.此解决方案应满足您的要求。
The first method iterates while there are more than 2 cards remaining, the second method compares the cards and returns the resulting list:第一种方法在剩余两张以上卡片时进行迭代,第二种方法比较卡片并返回结果列表:
public List<Card> BestCards(List<Card> list){
List<Card> listResult = list;
while (listResult.Count > 2)
listResult = ReduceList(listResult);
return listResult;
}
public List<Card> ReduceList(List<Card> list)
{
var listResult = new List<Card>();
for(int i = 0; i <= list.Count - 1; i+=2)
{
if(list[i].value > list[i+1].value)
listResult.Add(list[i]);
else if (list[i].value< list[i+1].value)
listResult.Add(list[i+1]);
else if (list[i].value==list[i+1].value)
listResult.Add(list[i].name.CompareTo(list[i+1].name) <= 0 ? list[i] : list[i+1]);
}
return listResult;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.