2

I am a new C# programmer and am currently stuck on the following problem:

Given an array of numbers = 
   [49, 71, 68, 26, 58, 64, 47, 16, 42, 53, 20, 15, 17, 45, 43, 52, 88, 65, 46, 82, 86, 
    69, 84, 56, 54, 28, 60, 32, 95, 29, 9, 79, 98, 51, 90, 36, 24, 62, 14, 91, 83, 3, 
    74, 30, 33, 6, 92, 40, 70, 2, 44, 31, 55, 12, 8, 89, 37, 72, 25, 81, 23, 100, 13, 
    87, 80, 18, 85, 5, 78, 10, 75, 41, 67, 94, 27, 96, 22, 73, 21, 63, 7, 34, 39, 61, 
    4, 19, 97, 93, 11, 35, 77, 76, 48, 57, 50, 99, 1, 59, 66, 38]

Write a C# function that will return a comma separated string of the first two numbers in the array which sum to 30 and immediately exit.

I've been working on this for a while, and it seems simple enough, however this is all I have been able to come up with:

 using System;
    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
       static void Main()
       {
           int[] array1 = { 49, 71, 68, 26, 58, 64, 47, 16, 42, 53, 20, 15, 17, 45, 43, 52, 88, 65, 46, 82, 86, 69, 84, 56, 54, 28, 60, 32, 95, 29, 9, 79, 98, 51, 90, 36, 24, 62, 14, 91, 83, 3, 74, 30, 33, 6, 92, 40, 70, 2, 44, 31, 55, 12, 8, 89, 37, 72, 25, 81, 23, 100, 13, 87, 80, 18, 85, 5, 78, 10, 75, 41, 67, 94, 27, 96, 22, 73, 21, 63, 7, 34, 39, 61, 4, 19, 97, 93, 11, 35, 77, 76, 48, 57, 50, 99, 1, 59, 66, 38 };
           int sum1 = array1.Sum();
           Console.WriteLine(sum1);
        }
    }

I know that I'm just missing something small and I have found similar problems but none have solved this one for me. Any help or push in the right direction would be appreciated.

AdamMc331
  • 16,492
  • 10
  • 71
  • 133
dustin
  • 23
  • 3
  • Yes,I need to write a function that will find the first two numbers whose sum equals 30. – dustin Nov 18 '14 at 05:12
  • possible duplicate of [find pair of numbers in array that add to given sum](http://stackoverflow.com/questions/8334981/find-pair-of-numbers-in-array-that-add-to-given-sum) – Rahul Singh Nov 18 '14 at 05:18
  • Thank you....i found that solution earlier and it didn't help. – dustin Nov 18 '14 at 05:28
  • 1
    Since this certainly is a homework assignment. Take a look at for loops to iterate trough your array. – user2888973 Nov 18 '14 at 05:33
  • For loops? Where I am having issues is here... int sum1 = array1.Sum(); this is adding the sum of all numbers in the array and i only need to find two numbers that equal 30. – dustin Nov 18 '14 at 05:37
  • Indeed.. try to start with for (int t1 = 0; t1 < array1.Count(); t1++) – user2888973 Nov 18 '14 at 05:42

3 Answers3

1

Function:

static string GetFirstPairOf30(int[] data) {
    for (int i = 0; i < data.Length; i++) {
        for (int j = 0; j < data.Length; j++) {
            if (i != j && data[i] + data[j] == 30) {
                return String.Format("{0},{1}", data[i], data[j]);
            }
        }
    }
    throw new ArgumentException("Array does not contain pairs with sum 30");
}

Usage:

   Console.WriteLine(GetFirstPairOf30(array1));
Ivan
  • 138
  • 6
  • This is not the most efficient solution, as your inner loop starts at 0 every time. Also, you should give some explanation rather than just a block of code that new readers may not understand. -1 – AdamMc331 Nov 18 '14 at 06:27
0

What I would recommend doing here is starting by writing a loop through the array, but making sure that it does not include the last item. The reason being is that you will compare each element and the one next to it, so if you try to reach one element after the end you will have an exception:

for(int i = 0; i < myArray.Length - 1; i++)

Inside of that, you will want a for loop that loops from after that index, until the end of the array. For example, if you start at index 0, you want to check index 1-end for another number that can add to 30:

for(int i = 0; i < myArray.Length - 1; i++)
{
   for(int j = i + 1; j < myArray.Length; j++)
   {
   }
}

Inside of that, you can write your condition statement to see if they add to 30:

for(int i = 0; i < myArray.Length - 1; i++)
{
   for(int j = i + 1; j < myArray.Length; j++)
   {
      if(myArray[i] + myArray[j] == 30)
      {
         return (String.Format("{0},{1}", myArray[i], myArray[j]));
      }
   }
}

If you get through these loops without returning, you can print that there were no values with a sum of 30.


Something I think might make this a little faster is to add a check if each of the outer elements are greater than 30. If they are, nothing will give you a sum of 30 (assuming you don't allow negatives), so don't waste time doing unnecessary looping. For example: If your array is 100 integers, and position 0 has value 32, you're going to loop through the other 99 integers for nothing. So, you could try this:

for(int i = 0; i < myArray.Length - 1; i++)
{
   if(myArray[i] > 30)
   {
      continue;
   }

   for(int j = i + 1; j < myArray.Length; j++)
   {
      if(myArray[i] + myArray[j] == 30)
      {
         return (String.Format("{0},{1}", myArray[i], myArray[j]));
      }
   }
}

EDIT

To clarify how this would look in your actual project, consider this:

public static void main(String[] args)
{
   int[] myArray = // All your stuff here;
   Console.WriteLine(GetElementsWithSum30(myArray));
}

public static String GetElementsWithSum40(myArray)
{
   for(int i = 0; i < myArray.Length - 1; i++)
   {
      if(myArray[i] > 30)
      {
         continue;
      }

      for(int j = i + 1; j < myArray.Length; j++)
      {
         if(myArray[i] + myArray[j] == 30)
         {
            return (String.Format("{0},{1}", myArray[i], myArray[j]));
         }
      }
   }
   // If we finished looping and didn't find anything, return that.
   return("No elements found that sum 30.");
}
AdamMc331
  • 16,492
  • 10
  • 71
  • 133
  • Thank you I understand what you are saying. My new solution is now throwing an error saying "(24:21) Since 'Program.Main()' returns void, a return keyword must not be followed by an object expression" Referencing this line "return (String.Format("{0},{1}", array1[i], array1[j]));" – dustin Nov 18 '14 at 06:38
  • Oh, well the above should go in it's own function, not the main function. – AdamMc331 Nov 18 '14 at 06:45
  • @dustin please see my edit for another quick and brief example. Of course, yours may not look exactly like that, but hopefully it helps. – AdamMc331 Nov 18 '14 at 06:48
  • @ivan I said in my answer that it makes the assumptions negative integers aren't allowed, and I only assumed that because I don't see any in OP's array. – AdamMc331 Nov 18 '14 at 06:49
  • 1
    No, it did not look like that. I'm on the right track though. Thank you so much for your help! – dustin Nov 18 '14 at 06:53
  • @dustin not a problem at all. – AdamMc331 Nov 18 '14 at 06:57
-1

You can write an extension method as follow and use it where ever you need

public static class Extensions{
    public static string Sum30(this int[] array)
    {
        var res = (from a in array
                    from b in array
                    where a + b == 30
                    select new
                    {
                        element = a.ToString() + "," + b.ToString()
                    }).FirstOrDefault(t => t != null);

        return res == null ? string.Empty : res.element;
    }
}
then use it like this
        var arr = new int[] { 86, 12, 39, 14, 90, 0, 16, 19,18, 17 };
        var returnvalue = arr.Sum30();