查找int []数组的所有可能组合,受C#中的长度约束

时间:2017-05-19 14:16:21

标签: c# arrays combinations

int[] listOfValues = {1, 2, 5, 2, 6};

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

预期的一对卡片样本:

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

然后需要将这些单独的int []结果添加到List中(如果在找到所有可能的值后,甚至可以将重复的int []值添加到列表中,即!)。

我已经在线寻找了几个小时,似乎无法让任何解决方案适用于我的特定任务。

有人有任何想法吗?

3 个答案:

答案 0 :(得分:3)

你应该自己做功课。或者至少先尝试一下。您还没有提供代码,因此我无法在道德上为您提供完整的解决方案。

但是,这会让你开始:

想一想,就好像你是亲手做的那样。大多数人会选择第一个值和第二个值并将其写下来。然后他们会向后写那对。然后他们会做第一个值,第三个值,然后是倒退,依此类推等等。

看起来像是:

{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
    }
}

尝试了解此代码的用途。然后填写空白。你应该得到正确的答案。但总是要确保理解为什么。另外,请尝试查看是否可以找出对此代码的任何改进。

答案 1 :(得分:0)

使用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();

答案 2 :(得分:0)

感谢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;
}