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[]值添加到列表,即!),一旦找到了所有可能的值。
我在网上找了几个小时,似乎无法获得任何适合我特定任务的解决方案。
有人有什么想法吗?
你真的应该自己做作业。或者至少先试试。你没有提供代码,所以我不能从道德上给你完整的解决方案。
但是,这将帮助您入门:
想一想,就好像你要用手做一样。大多数人会选择第一个值和第二个值并将它们写下来。然后他们会把这一对倒过来写。然后他们将执行第一个值和第三个值,然后向后,依此类推。
它看起来会像这样:
{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
}
}
试着理解这段代码在做什么。然后填空。你应该得到正确的答案。不过,一定要理解为什么。此外,试着看看你是否能找出对这段代码的任何改进。
有了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();
感谢 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;
}