3

I'm trying to solve whats probably an easy task, but I'm extremely new to this and don't quite have my head around working with arrays in a complex fashion. I'm trying to figure out if two inputs each corresponding numbers sum to the same number (for example with 123 and 321, 1+3 2+2 and 1+3 all equal 4).

The code I have so far has broken down each input into arrays, and I can sum those arrays into a third array, but I cant figure out how to check it with itself. Should I even bother with the 3rd array, and just figure out how to check the sums of the array in a loop?

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]);
    }
}

}

0

2 Answers 2

2

You can create the collections on the fly...

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;

The output will equal true if all elements add up to the same value...

Test cases:

Should succeed

12345
54321

Should fail

12345
55432

To understand the above query, lets break it up into sections.

// 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;
Sign up to request clarification or add additional context in comments.

3 Comments

this is super useful for me, I see zip used alot and only get explanations like this every so often. thanks!
Great solution. Also consider github.com/morelinq/MoreLINQ/blob/master/MoreLinq/ZipLongest.cs if the two enumerables may be different lengths.
@mjwills thank you for sharing that, it did run through my mind, the thought of what if the two collections are different lengths, but chose to not pursue it... I like what they did with it!
0

You're 99% of the way there already. Just lose the third array and check each individual sum in your final loop.

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.");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.