【问题标题】:Finding all possible combinations of int[] array, constrained by length in C#查找 int[] 数组的所有可能组合,在 C# 中受长度限制
【发布时间】:2017-05-19 14:16:21
【问题描述】:
int[] listOfValues = {1, 2, 5, 2, 6};

我需要能够找到这个数组的所有对组合,包括重复。数组中的每个值都来自一副纸牌。因此,如果值“2”在数组中出现两次,例如,我们可以假设这是两个 不同 值,因此需要分别处理。

预期的卡片对示例:

{1, 2}
{1, 2}
{2, 1}
{2, 1}
{2, 2}
{1, 5}
{1, 6}
etc.......

一旦找到所有可能的值,就需要将这些单独的 int[] 结果添加到列表中(如果您甚至可以将重复的 int[] 值添加到列表中,那就是!)。

我在网上搜索了几个小时,但似乎无法找到任何适合我的特定任务的解决方案。

请问有人有什么想法吗?

【问题讨论】:

标签: c# arrays combinations


【解决方案1】:

你真的应该自己做作业。或者至少先尝试一下。你没有提供代码,所以我不能从道德上给你完整的解决方案。

但是,这会让你开始:

想一想,就好像你要用手做一样。大多数人会选择第一个值和第二个值并将它们写下来。然后他们会倒着写那对。然后他们会执行第一个值和第三个值,然后倒退,依此类推。

它看起来像:

{1,2}

{2,1}

{1,5}

{5,1}

{1,2}

{2,1}

{1,6}

{6,1}

{2,5} - 现在我们再次迭代,从第二个值开始

那么我们如何在代码中表达它呢? 嵌套循环!

这是解决您的问题的算法框架:

List<int[]> pairs = new List<int[]>();

for(int x = 0; x < listOfValues.Length - 1; x++)
{
    for(int y = x+1; y < listOfValues.Length; y++)
    {
        // Create an array of the [x] position and [y] position of listOfValues
        // Create another array, except swap the positions {[y],[x]}

        // Add both arrays to the "pairs" List
    }
}

试着理解这段代码在做什么。然后填空。你应该得到正确的答案。不过,请始终确保了解原因。另外,请尝试看看您是否可以找出对此代码的任何改进。

【讨论】:

  • 这极大地启动了我的工作,谢谢。
【解决方案2】:

使用 linq,您可以这样做。

int[] listOfValues = { 1, 2, 5, 2, 6 };
        var combination = listOfValues.Select(i => listOfValues.Select(i1 => new Tuple<int, int>(i, i1)).ToList())
            .ToList()
            .SelectMany(list => list.Select(x => x)).ToList();

【讨论】:

    【解决方案3】:

    感谢 Clay07g 的帖子,我能够使用以下代码解决问题:

    public static List<int[]> getCardCombos(int[] values)
    {
      List<int[]> pairs = new List<int[]>();
    
      for (int x = 0; x < values.Length - 1; x++)
      {
        for (int y = x + 1; y < values.Length; y++)
        {
          int firstValue = values[x];
          int secondValue = values[y];
    
          // Create an array of the [x] position and [y] position of listOfValues 
          int[] xAndY = { firstValue, secondValue};
          // Create another array, except swap the positions {[y],[x]}
          int[] yAndX = { secondValue, firstValue };
    
          pairs.Add(xAndY);
          pairs.Add(yAndX);
          // Add both arrays to the "pairs" List
        }
      }
      return pairs;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 2011-08-10
      • 1970-01-01
      相关资源
      最近更新 更多