Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C中两个整数的和元组#_C#_Sum_Tuples - Fatal编程技术网

C# C中两个整数的和元组#

C# C中两个整数的和元组#,c#,sum,tuples,C#,Sum,Tuples,我试图解决这个问题,只是为了准备一次求职面试: 编写一个函数,给定一个列表和一个目标和,返回任意两个不同元素(其和等于目标和)的从零开始的索引。如果没有这样的元素,函数应该返回null 例如,FindTwoSum(new List(){1,3,5,7,9},12)应该返回以下任何一个索引元组: 1,4(3+9=12) 2,3(5+7=12) 3,2(7+5=12) 4,1(9+3=12) 以下是我迄今为止所做的工作 public static Tuple<int, int> Find

我试图解决这个问题,只是为了准备一次求职面试: 编写一个函数,给定一个列表和一个目标和,返回任意两个不同元素(其和等于目标和)的从零开始的索引。如果没有这样的元素,函数应该返回null

例如,FindTwoSum(new List(){1,3,5,7,9},12)应该返回以下任何一个索引元组:

1,4(3+9=12)

2,3(5+7=12)

3,2(7+5=12)

4,1(9+3=12)

以下是我迄今为止所做的工作

public static Tuple<int, int> FindTwoSum(List<int> list, int sum)
    {
        List<Tuple<int, int>> ListOfInt = new List<Tuple<int, int>>();
        for (int i=0; i<list.Count; i++)
        {
            for(int j=0; j<list.Count; j++)
            {
                if (list[i] + list[j] == sum)
                {
                    ListOfInt.Add(new Tuple<int, int>(i,j));
                }
            }
        }

        foreach ( var elemt in ListOfInt)
        {
            return elemt;
        }
        return null;

    }

有什么建议吗

此部分将在找到列表中的第一个元素后立即返回

    foreach ( var elemt in ListOfInt)
    {
        return elemt;
    }
您需要返回
列表
,然后通过打印出
Item1
Item2
此循环进入消费代码循环:

    foreach ( var elemt in ListOfInt)
    {
        return elemt;
    }
永远不会“循环”回来。在第一次迭代中,如果列表中有第一个元素,它将返回退出并放弃循环的

如果你真的只想要第一对好的,那就扔掉
列表

公共静态元组FindTwoSum(列表,int-sum)
{

对于(int i=0;i将方法的返回值更改为
IEnumerable
,然后使用
yield return
返回值。在循环中枚举结果时(在Main()方法中)将得到该值

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
命名空间控制台应用程序13
{
班级计划
{
静态void Main(字符串[]参数)
{
var output=FindTwoSum(新列表(){1,3,5,7,9},12);
foreach(输出中的变量x)
Console.WriteLine(x.Item1+“”+x.Item2);
Console.ReadKey(true);
}
公共静态IEnumerable FindTwoSum(列表,整数和)
{
List LISTOFIT=新列表();
for(int i=0;i
要读取元组中的值,可以调用.Item1、.Item2等

var myTuple = new Tuple<int, string, string>(123, "Cat", "Dog");

var id = myTuple.Item1;
var pet1 = myTuple.Item2;
var pet2 = myTuple.Item3;
var myTuple=新元组(123,“猫”、“狗”);
var id=myTuple.Item1;
var pet1=myTuple.Item2;
var pet2=myTuple.Item3;

好吧,如果
a+b=sum
那么
b+a=sum
,那么您可以切断内部循环,一次返回两对;当前实现的另一个问题和反例是
a+a=sum
不算数,例如

  {3, 6, 9}, 12
只应返回

  0, 2 // 3 + 9
  2, 0 // 9 + 3
而不是

  1, 1 // 6 + 6 is wrong
我宁愿实现返回
IEnumerable
的解决方案:

应该是

  if ((list[i] + list[j] == sum) && (list[i] != list[j]))
不同的值,但不是索引不是一种情况,因为
a[i]==a[i]
所以每当索引不不同时,值也不不同。我们有条件

  if ((list[i] + list[j] == sum) && (list[i] != list[j]))
测试:

  // note that I can pass an array (int[]) or list (List<int>) whatever collection
  String report = String.Join(Environment.NewLine, 
    FindTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12));

  // (1, 4)
  // (4, 1)
  // (2, 3)
  // (3, 2)
  Console.Write(report);
//注意,我可以传递数组(int[])或列表(list)任何集合
String report=String.Join(Environment.NewLine,
FindTwoSum(新int[]{1,3,5,7,9},12));
// (1, 4)
// (4, 1)
// (2, 3)
// (3, 2)
控制台。编写(报告);

我是LINQish的粉丝之一。所以我只是用LINQ方法编写了函数:

private static IEnumerable<Tuple<int, int>> FindTwoSum(IEnumerable<int> candidates, int expectedSum)
{
    return candidates.SelectMany((Lhs, LhsIndex) => candidates.Select((Rhs, RhsIndex) => new { Rhs, RhsIndex }).Where(r => r.RhsIndex != LhsIndex).Select(r => new { Lhs, r.Rhs }))
                        .Where(pair => pair.Lhs + pair.Rhs == expectedSum)
                        .Select(pair => Tuple.Create(pair.Lhs, pair.Rhs));
}

考虑到问题的措辞,我注意到您的示例中存在一个潜在问题。您提到了不同的元素,但似乎没有采取任何措施来确保所使用的值是不同的。您似乎还能够对相同的元素求和(I==j)

下面的解决方案展示了如何避免上述问题,以及如何避免在执行时将元素放入列表:

public static Tuple<int, int> FindTwoSum(int[] collection, int sum)
{
    int[] distinct = collection.Distinct().ToArray();
    for (int x = 0; x < distinct.Length; x++)
    {
        for (int y = 0; y < distinct.Length; y++)
        {
            if (y != x && distinct[x] + distinct[y] == sum)
                return Tuple.Create(Array.IndexOf(collection, distinct[x]), Array.IndexOf(collection, distinct[y]));
        }
    }
    return null;
}
公共静态元组FindTwoSum(int[]集合,int-sum)
{
int[]distinct=collection.distinct().ToArray();
for(int x=0;x
然后,您可以使用以下方法打印此结果:

Tuple<int, int> result = FindTwoSum(new[] { 1,3, 5, 7, 9}, 12);
if (result != null)
    Console.WriteLine(result.Item1 + "," + result.Item2);
else
    Console.WriteLine("No solution!");
Tuple result=FindTwoSum(新[]{1,3,5,7,9},12);
如果(结果!=null)
Console.WriteLine(result.Item1+“,”+result.Item2);
其他的
控制台。WriteLine(“没有解决方案!”);

如果您想获得更多乐趣,可以使用Linq:

var numbers = new List<int> {1, 3, 5, 7, 9};

int target = 12;
var items = numbers.Select((value, index) => new {index, value});

var hits = 
    from a in items
    from b in items
    where (a.index != b.index) && (a.value + b.value == target)
    select new {index1 = a.index, index2 = b.index};

Console.WriteLine(string.Join("\n", hits.Select(x => 
    $"{x.index1}, {x.index2} ({numbers[x.index1]} + {numbers[x.index2]} = {target})")));
它从元组序列生成所有项的组合

然后,它使用
where
筛选出具有相同索引的所有项目(使用
(a.index!=b.index)
,并确定哪些总和与目标值匹配(使用
(a.value+b.value==target)

接下来,它将结果选择到一个具有属性
index1
index2
的新元组中


最后,它使用
string.Join()
从该元组输出结果。

但我仍然无法将结果打印到控制台
->这是什么意思?你不知道要使用什么命令。使用
元组
解决这个问题听起来不对。你不应该使用yield return elemt而不是retrun elemt!你的任务是编写一个“返回任意两个不同元素的从零开始的索引,其和。。。"。因此,您不需要收集并输出所有元素。我说得对吗?“任何两个不同的元素”不意味着结果可能不是使用相同incides的总和。也许您需要检查
I!=j
?或者我错了吗?这是真的,我也注意到了我喜欢您的解决方案,但是有没有办法将重用直接返回给ma在方法中不使用foreach循环?是的,但必须更改返回值的类型
  // note that I can pass an array (int[]) or list (List<int>) whatever collection
  String report = String.Join(Environment.NewLine, 
    FindTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12));

  // (1, 4)
  // (4, 1)
  // (2, 3)
  // (3, 2)
  Console.Write(report);
private static IEnumerable<Tuple<int, int>> FindTwoSum(IEnumerable<int> candidates, int expectedSum)
{
    return candidates.SelectMany((Lhs, LhsIndex) => candidates.Select((Rhs, RhsIndex) => new { Rhs, RhsIndex }).Where(r => r.RhsIndex != LhsIndex).Select(r => new { Lhs, r.Rhs }))
                        .Where(pair => pair.Lhs + pair.Rhs == expectedSum)
                        .Select(pair => Tuple.Create(pair.Lhs, pair.Rhs));
}
var results = FindTwoSum(new[] { 1, 3, 5, 7, 9 }, 12);

foreach (var tuple in results)
{
    Console.WriteLine(tuple);
}
public static Tuple<int, int> FindTwoSum(int[] collection, int sum)
{
    int[] distinct = collection.Distinct().ToArray();
    for (int x = 0; x < distinct.Length; x++)
    {
        for (int y = 0; y < distinct.Length; y++)
        {
            if (y != x && distinct[x] + distinct[y] == sum)
                return Tuple.Create(Array.IndexOf(collection, distinct[x]), Array.IndexOf(collection, distinct[y]));
        }
    }
    return null;
}
Tuple<int, int> result = FindTwoSum(new[] { 1,3, 5, 7, 9}, 12);
if (result != null)
    Console.WriteLine(result.Item1 + "," + result.Item2);
else
    Console.WriteLine("No solution!");
var numbers = new List<int> {1, 3, 5, 7, 9};

int target = 12;
var items = numbers.Select((value, index) => new {index, value});

var hits = 
    from a in items
    from b in items
    where (a.index != b.index) && (a.value + b.value == target)
    select new {index1 = a.index, index2 = b.index};

Console.WriteLine(string.Join("\n", hits.Select(x => 
    $"{x.index1}, {x.index2} ({numbers[x.index1]} + {numbers[x.index2]} = {target})")));
from a in items
from b in items