找到前两位数的总和等于10

时间:2014-05-27 07:28:19

标签: c#

我有一个数组intx[]

int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 

我需要找到前两个数字的总和应该是10。

以下是代码:

Output should like (4 and 6).
Output should like (3 and 7).
Output should like (2 and 8).
Output should like (1 and 9).

public string Test()
{
    int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int i, j = intx.Length-1;
    string s = "";
    for (i = 0; i < 4; i++)
    {
        if ((intx[i] + intx[j - 1]) == 10)
        {
             s = (intx[i].ToString() + " and " + intx[j - 1].ToString());
        }
        j--;
    }
    return s;
} 

2 个答案:

答案 0 :(得分:0)

您可以使用LINQ:

int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var twoDigitsSumEquals10 = intx
    .SelectMany((i1, index) =>
        intx.Skip(index + 1)
            .Select(i2 => Tuple.Create(i1, i2)))
    .Where(t => t.Item1 + t.Item2 == 10);

SelectMany在数组中的所有int和数组中的所有int之间构建一个笛卡尔积,其索引比第一个更大(以防止重复)。

测试:

foreach (var x in twoDigitsSumEquals10)
    Console.WriteLine(string.Join(",", x));

输出:

(1, 9)
(2, 8)
(3, 7)
(4, 6)

或仅与(1 and 9)之间的“和”之间的第一个:

var firstCombi = twoDigitsSumEquals10.First();
Console.Write("({0} and {1})", firstCombi.Item1, firstCombi.Item2);

更新:这里是没有LINQ的相同的

List<Tuple<int, int>> pairs = new List<Tuple<int, int>>();
for (int i = 0; i < intx.Length - 1; i++)
{
    for (int ii = i + 1; ii < intx.Length; ii++)
    { 
       if(i + ii == 10)
           pairs.Add(Tuple.Create(i, ii));
    }
}

答案 1 :(得分:0)

您不能对s做任何事情,只需重新分配即可。尝试将结果添加到列表中并返回列表

public List<string> Test()
{
    int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int j = intx.Length-1;
    List<string> result = new List<string>();
    for (int i = 0; i < 4; i++)
    {
        if ((intx[i] + intx[j - 1]) == 10)
        {
             result.Add(intx[i].ToString() + " and " + intx[j--].ToString());
        }
    }
    return result;
} 


foreach(string s in Test())
    Console.WriteLine(s);

要返回第一个,然后提前退出循环

public string Test()
{
    int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int j = intx.Length-1;
    for (int i = 0; i < 4; i++)
    {
        if ((intx[i] + intx[j - 1]) == 10)
        {
             return (intx[i].ToString() + " and " + intx[j--].ToString());
        }
    }
    return "";
}