【问题标题】:How to get combination of List of values in C# [closed]如何在 C# 中获取值列表的组合 [关闭]
【发布时间】:2020-09-03 11:11:37
【问题描述】:

我正在创建一个由 6 张卡片组成的游戏,我想组合这些卡片,但问题是我一直在创建该功能。以下是我制作的代码

public class Cards
{
   
    public int number{ get; set; }
    public string symbol{ get; set; }

    public Cards(int number, string symbol)
    {
       
        number= Number;
        symbol = Symbol;
    }
}

//populate list
List<Cards> CardList = new List<Cards>();
void InitCards()
{
            CardList.Add(new Cards(1, "dogman"));
            CardList.Add(new Cards(2, "dogman"));
            CardList.Add(new Cards(1, "catman"));
            CardList.Add(new Cards(2, "catman"));
            CardList.Add(new Cards(1, "birdman"));
            CardList.Add(new Cards(2, "birdman"));
}

void MakeCombination()
{
    foreach (var card in CardList)
        {
           //make combination
        }
}

我的预期输出是用一组两张卡获得所有可能的组合 下面的示例预期输出

1 dogman, 2 dogman
1 dogman, 1 catman
1 catman, 2 birdman

【问题讨论】:

  • 预期的结果是什么?你说的组合是什么意思?也许相关:stackoverflow.com/questions/30081908
  • 为什么你的输出中只有 3 个组合?例如,为什么没有 1dogman、2catman 或根本没有 dogman/birdman?
  • 与你的问题没有太大关系,但最好打电话给你的卡类Card。并且属性应该是 Pascal 大小写(以大写字符开头)
  • 同意汉诺;在 C# 中使类名单数。如果一个类代表一个集合,那么附加单词“Collection”比复数名称更有意义。作为 Card 的数组/列表的原因实际上应该称为 Cards(作为属性)-> List&lt;Card&gt; Cards。如果你打电话给你的班级卡片,你应该写List&lt;Cards&gt; CardssList&lt;Cards&gt; CardsesList&lt;Card&gt; 得到一个复数名称,因为它是某个其他类的属性。当一个类的唯一目的是成为其他东西的集合时,称之为-Collection。可以确定的细微差别
  • 基本相同的问题as here。您只使用对象而不是整数。我只是使用 hashcode as a single value for your object

标签: c# list linq class


【解决方案1】:

根据您的要求,即获得所有可能的卡片对组合,以下双嵌套循环应该为您带来魔力:

void MakeCombination()
{
    for (int i = 0; i < CardList.Count - 1; i++)
        for (int g = i + 1; g < CardList.Count; g++)
            Console.WriteLine($"{CardList[i].number} {CardList[i].symbol}, {CardList[g].number} {CardList[g].symbol}");
}

【讨论】:

  • 谢谢,我花了一个小时来解决这个问题,但我不敢相信这个解决方案只包含 3 行代码。
  • 欢迎您!请记住,下次请写下您的预期输出,这样我们就可以更轻松地为您提供帮助,而无需所有这些问题。
  • 再次感谢先生,我会应用所有这些。先生,如果我在此处发布与我的问题相关的另一个问题,可以吗?还是我需要发布另一个新问题?
  • 把它放在 cmets 中,如果它可以轻松回答,我会回答你,否则我会重定向你问一个新的。 :)
  • 问题的限制使得代码很短。这里子集的大小是固定的。对于 3 个元素,您将需要另一个循环,例如 this。但主要的简化来自 {A,B} == {B,A}。
猜你喜欢
  • 1970-01-01
  • 2016-05-06
  • 2022-11-28
  • 2013-10-22
  • 2023-03-26
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多