比较C#数组与自身

3
我正在尝试解决一个可能很简单的任务,但我对于以复杂方式处理数组还不太熟悉。我想找出两个输入是否对应的数字总和相等(例如123和321,1+3、2+2和1+3都等于4)。
到目前为止,我的代码已将每个输入拆分为数组,并且我可以将这些数组相加到第三个数组中,但我无法弄清如何使用它自己进行检查。我应该放弃第三个数组,只需在循环中找出数组的总和吗?
public static void Main()
{
    Console.Write("\n\n"); //begin user input
    Console.Write("Check whether each cooresponding digit in two intigers sum to the same number or not:\n");
    Console.Write("-------------------------------------------");
    Console.Write("\n\n");
    Console.Write("Input 1st number then hit enter: ");
    string int1 = (Console.ReadLine());//user input 1


    Console.Write("Input 2nd number: ");
    string int2 = (Console.ReadLine());//user input 2

    int[] numbers = new int[int1.ToString().Length]; //changing user inputs to strings for array
    int[] numbers2 = new int[int2.ToString().Length];
    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = int.Parse(int1.Substring(i, 1));//populating arrays
        numbers2[i] = int.Parse(int2.Substring(i, 1));
    }


    int[] numbers3 = new int[numbers.Length];

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers3[i] = (numbers[i] + numbers2[i]);
    }
}

}

2个回答

2

您可以即时创建集合...

bool isEqual = Console.ReadLine()
                      .ToCharArray()
                      .Select(i => Convert.ToInt32(i.ToString()))
                      .Zip(Console.ReadLine()
                                  .ToCharArray()
                                  .Select(i => Convert.ToInt32(i.ToString())),
                           (i, j) => new
                           {
                               First = i,
                               Second = j,
                               Total = i + j
                           })
                      .GroupBy(x => x.Total)
                      .Count() == 1;

输出结果将等于true,如果所有元素加起来的值相等...
测试用例:
应该成功
12345
54321

应该失败

12345
55432

为了理解上述查询,让我们将其分成几个部分。
// Here I'm just converting a string to an IEnumerable<int>, a collection of integers basically
IEnumerable<int> ints1 = Console.ReadLine()
                                .ToCharArray()
                                .Select(i => Convert.ToInt32(i.ToString()));

IEnumerable<int> ints2 = Console.ReadLine()
                                .ToCharArray()
                                .Select(i => Convert.ToInt32(i.ToString()));

// Zip brings together two arrays and iterates through both at the same time.
// I used an anonymous object to store the original values as well as the calculated ones
var zippedArrays = ints1.Zip(ints2, (i, j) => new
                                    {
                                        First = i,    // original value from ints1
                                        Second = j,   // original values from ints2
                                        Total = i + j // calculated value ints1[x] + ints2[x]
                                    });



// if the totals are [4,4,4], the method below will get rid of the duplicates.
// if the totals are [4,3,5], every element in that array would be returned
// if the totals are [4,4,5], only [4,5] would be returned.
var distinctByTotal = zippedArrays.GroupBy(x => x.Total);

// So what does this tell us? if the returned collection has a total count of 1 item,
// it means that every item in the collection must have had the same total sum
// So we can say that every element is equal if the response of our method == 1.

bool isEqual = distinctByTotal.Count() == 1;

1
这对我非常有用,我经常看到zip被使用,但只偶尔得到这样的解释。谢谢! - ba7399
1
很棒的解决方案。如果两个可枚举对象的长度可能不同,还可以考虑使用https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/ZipLongest.cs。 - mjwills
@mjwills 谢谢你分享这个,我也想到了,如果这两个集合的长度不同会怎样,但是选择不去追究它... 我喜欢他们对此所做的处理! - Aydin

0
你已经完成了99%的工作。只需删除第三个数组,并在最后的循环中检查每个单独的总和即可。
bool isOK = numbers.Length = numbers2.Length && numbers.Length > 0;
if(isOK)
{
    int expectedSum = numbers[0] + numbers2[0];
    for (int i = 1; i < numbers.Length; i++)
    {
        var sum = (numbers[i] + numbers2[i]);
        if(sum != expectedSum)
        {
            isOK = false;
            break;
        }
    }
}
Console.WriteLine(isOk ? "Good job." : "You got some learning to do.");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接