c# check for a poker straight

点点圈 提交于 2019-12-01 04:03:20

This might not be the best performing check, but I'd say it's very readable which is usually a good property.

Just grab 5 cards, skipping cards you've already seen every iteration and check for a straight for each sequence. An ordered sequence is a straight if it does not contain doubles and if the first and last cards difference is 5.

public bool CheckStraight(List<Card> cards)
{
     //maybe check 5 and 10 here first for performance

     var ordered = cards.OrderByDescending(a => a.Value).ToList();
     for(i = 0; i < ordered.Count - 5; i++) {
          var skipped = ordered.Skip(i);
          var possibleStraight = skipped.Take(5);
          if(IsStraight(possibleStraight)) {
               return true;
          }
     }
     return false;
}

public bool IsStraight(List<Card> fiveOrderedCards) {
     var doubles = cards.GroupBy(card => card.Rank).Count(group => group.Count() > 1);
     var inARow = cards[4] - cards[0] = 5; //Ace is 0

     return !doubles && inARow;
}

I have made some small changes to Glubus answer. The code below does the job however you will have to check manually for a wheel (A,1,2,3,4,5) straight.

public bool CheckStraight(List<Card> cards)
    {
        //maybe check 5 and 10 here first for performance

        var ordered = cards.OrderByDescending(a => a.Value).ToList();
        for (var i = 0; i < ordered.Count - 4; i++)
        {
            var skipped = ordered.Skip(i);
            var possibleStraight = skipped.Take(5).ToList();
            if (IsStraight(possibleStraight))
            {
                return true;
            }
        }
        return false;
    }
public bool IsStraight(List<Card> cards)
{
    return cards.GroupBy(card => card.Value).Count() == cards.Count() && cards.Max(card => (int)card.Value) - cards.Min(card => (int)card.Value) == 4;
    }

erm,

function bool IsStraight(IEnumerable<int> cards)
{
    var orderedCards = cards.OrderBy(n => n).ToList();
    var test = orderdCards.Zip(orderdCards.Skip(1), (a, b) => b - a);

    var count = 0;
    foreach(var n in test)
    {
        if (n == 1)
        {
            count++;
            if (count == 4)
            {
                return true;
            }
        }
        else
        {
            count = 0;
        }
    }

    return false;
}

I cannot think about real one liner, since A can be 1 or 14, but this should be good:

int c = 5; // How many cards straight
bool Ais1 = cards.OrderBy(a => a.Value).Select((i,j) => i.Value-j).Distinct().Skip(1).Count() <= (cards.Count - c);
bool Ais14 = cards.OrderBy(a => (a.Value == 1 ? 14 : a.Value)).Select((i,j) => (i.Value == 1 ? 14 : i.Value)-j).Distinct().Skip(1).Count() <= (cards.Count - c);
return Ais1 || Ais14;

(Updated - thank you Janne, I've fixed the code)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!