gpt4 book ai didi

c# - 如何找到同一个对象在列表中出现了多少次,然后找到出现次数最多的对象的属性

转载 作者:行者123 更新时间:2023-11-30 12:40:27 24 4
gpt4 key购买 nike

我正在为我已经提交给 codereview 堆栈交换的一些编程实践制作扑克牌评估器。我需要能够正确地比较手牌,为此我需要看到对子的值(value)。我当前的双人过牌牌

 private static PokerHandsRank CheckHandForPairs(Hand hand)

{
var faceCount = (from card in hand.Cards
group card by card.Face
into g
let count = g.Count()
orderby count descending
select count).Take(2).ToList(); // take two to check if multiple pairs of pairs, if second in list is 1 there will be two pairs

switch (faceCount[0])
{
case 1: return PokerHandsRank.HighCard;
case 2: return faceCount[1] == 1 ? PokerHandsRank.Pair : PokerHandsRank.TwoPair;
case 3: return faceCount[1] == 1 ? PokerHandsRank.ThreeOfKind : PokerHandsRank.FullHouse;
case 4: return PokerHandsRank.FourOfKind;
default: throw new Exception("something went wrong here");
}
}

如您所见,我已经使用 linq 获取出现次数最多的配对列表,但是我不确定如何完成它以在我将它们分开后获得卡片的面值。

这是我目前的比较方法

 public int CompareTo(Hand other)
{
if (HandRank == other.HandRank) //if the hand rank is equal, sort the cards by face value and compare the two biggest
{
sortHandbyFace(this); // sorts cards into order by face
sortHandbyFace(other);
for (int i = 4; 0 <= i; i--)
{
if (Cards[i].Face == other.Cards[i].Face)
{
if (i == 0) return 0;
continue;
}
return Cards[i].Face > other.Cards[i].Face ? 1 : -1;
}
}
return HandRank > other.HandRank ? 1 : -1;

比较非常适合比较高牌问题,但我需要添加检查两手牌的等级是否相等,然后检查它们的值是一对、两对、满屋还是三(然后找到最高面值的货币对)

如果您需要有关我的程序的更多信息,请随时查看我的代码审查帖子 https://codereview.stackexchange.com/questions/152857/beginnings-of-a-poker-hand-classifier-part-2?noredirect=1&lq=1

最佳答案

这可能不是您要查找的内容,因为您比较的是 object 而不仅仅是 int,但这可以帮助您开始.基于这里的这个问题:How to get frequency of elements stored in a list in C# .

using System.Linq;

List<int> ids = //
int maxFrequency = 0;
int IDOfMax = 0;

foreach(var grp in ids.GroupBy(i => i))
{
if (grp.Count() > maxFrequency)
{
maxFrequency = grp.Count();
IDOfMax = grp.Key;
}
}

// The object (int in this case) that appears most frequently
// can be identified with grp.key

更新:重读问题后,听起来您需要尝试返回一个新对象,其中包含查询中的计数和面值。

你可以这样做:

public class FaceCountResult
{
public int Count { get; set; }
public Face FaceValue { get; set; }

public FaceCountResult(int count, Face faceValue)
{
Count = count;
FaceValue = faceValue;
}
}

然后,faceCount 应该看起来像这样:

var faceCount = (from card in hand.Cards
group card by card.Face
into g
let count = g.Count()
orderby count descending
select new FaceCountResult(count, card.Face);

我不确定 Take(2) 部分会如何影响这一点,因为我不太理解那部分代码。

然后您可以在 faceCount[0].Count 上做一个switch 并使用 faceCount[0].FaceValue 来获取面值.

关于c# - 如何找到同一个对象在列表中出现了多少次,然后找到出现次数最多的对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com