【问题标题】:Get all possible pair of strings from a list of length n c# [duplicate]从长度为n c#的列表中获取所有可能的字符串对[重复]
【发布时间】:2019-07-27 22:47:17
【问题描述】:

我有一个字符串列表

List<String> points = new List<String>();

假设点包含 [A,B,C,D,E]。我想要列表中所有可能的配对。我的预期输出是`

[A,B],
[A,C],
[A,D],
[A,E],
[B,A],
[B,C],
[B,D],
[B,E],
[C,A],
[C,B],
[C,D],
[C,E],
[D,A],
[D,B],
[D,C],
[D,E],
[E,A],
[E,B],
[E,C],
[E,D]

我需要获得所有 20 种组合。你能帮我在c#中解决这个问题吗?

【问题讨论】:

标签: c#


【解决方案1】:

我决定使用 LINQ(因为我可以而且很有趣):

public static void Main (string[] args) {
        List<String> points = new List<String> {"A","B", "C", "D", "E"};

        var perm = (from i in points.Select((Value, Index) => new { Value, Index })
                   from j in points.Select((Value, Index) => new { Value, Index })
                   where i.Index != j.Index
                   select (i.Value, j.Value)).ToList();

        foreach(var item in perm)
        {
            Console.WriteLine($"[{item.Item1},{item.Item2}]");
        }    
    }

输出:

[A,B]
[A,C]
[A,D]
[A,E]
[B,A]
[B,C]
[B,D]
[B,E]
[C,A]
[C,B]
[C,D]
[C,E]
[D,A]
[D,B]
[D,C]
[D,E]
[E,A]
[E,B]
[E,C]
[E,D]

【讨论】:

  • 如果数组是 {"A","B", "C", "A", "E"} 应该输出什么。索引 0 中的 A 和索引 3 中的 A 的组合是否应该被认为是有效的?
  • @Anu,嗯,谢谢。这取决于 OP 的定义:列表中是否允许重复值,如果允许,BA(索引 0)和 BA(索引 3)之间有什么区别。
  • 正确。只是想知道如果不是 i!=j,如果考虑索引会更好。例如 points.SelectMany((lhs,lhsIndex)=> points .Where((rhs,rhsIndex)=>rhsIndex!=lhsIndex).Select(rhs=>new {lhs,rhs}));
  • @AnuViswan,非常感谢!我从中吸取了教训。我为此加注了星标,所以我会回来使用该代码。我现在只是觉得很困。
【解决方案2】:

我首先想到的是使用 ValueTuples 和简单的循环,如下所示:

void Main()
{
   List<string> strings = new List<string> () {"A", "B", "C", "D", "E"};

   foreach (var item in OutputCombinations(strings))
   {
      Console.WriteLine($"[{item.Item1}{item.Item2}]");
   }
}

以及组合方法:

public static List<ValueTuple<string, string>> OutputCombinations(List<string> list)
{
   List<ValueTuple<string, string>> pairs = new List<ValueTuple<string, string>>();

   ValueTuple<string, string> currentPair = new ValueTuple<string, string>();
   for (int i = 0; i < list.Count; i++)
   {
       currentPair.Item1 = list[i];

       for (int j = 0; j < list.Count; j++)
       {
           if (i != j)
           {
            currentPair.Item2 = list[j];

            pairs.Add(currentPair);
           }
       }
   }

return pairs;
}

输出:

[AB]
[AC]
[AD]  
[AE]
[BA]
[BC]
[BD]
[BE]
[CA]
[CB]
[CD]
[CE]
[DA]
[DB]
[DC]
[DE]
[EA]
[EB]
[EC]
[ED]

【讨论】:

  • 它没有输出似乎需要的 [BA]。
  • 是的,我的错我有点困,正在编辑……
猜你喜欢
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 2021-06-14
  • 2021-02-22
  • 2011-11-25
  • 2023-04-10
  • 1970-01-01
  • 2020-02-04
相关资源
最近更新 更多