简体   繁体   中英

Recursive Algorithm C#

I need some help with an algorithm using C#. I have a list of objects, with items multiples of 4, and I should return only the two best items. 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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM