Home

C# Two Sum Problem - Slow Answer

The Code

namespace Test
{
    public class Program
    {
        public static Boolean Loop = true;


        static void Main(string[] args)
        {
            do
            {
                Console.WriteLine("Input number with separating commas - 1,2,3,4...");
                string qwe = Console.ReadLine();
                Console.WriteLine("Input the sum you're looking for");
                int SumVar = 0;

                SumVar = Convert.ToInt32(Console.ReadLine());

                string[] VarSplit = qwe.Split(",");

                if (VarSplit.Length > 2 && SumVar > 0)
                {
                    DoWork(VarSplit, SumVar);
                }
            }
            while (Loop == true);
        }

        static void DoWork(string[] VarSplit, int SumVar)
        {
            List<int> NumList = new List<int>();

            foreach (string x in VarSplit)
            {
                int y = Convert.ToInt32(x);
                if (y < SumVar)
                {
                    NumList.Add(Convert.ToInt32(x));
                }
            }

            for (int i = 0; i <= NumList.Count; i++)
            {
                for (int a = 1 + i; a < NumList.Count; a++)
                {
                    //Console.WriteLine(i + "-" + a);
                    if (NumList[i] + NumList[a] == SumVar)
                    {
                        string qwe = "Position " + Convert.ToString(i) + "(" + NumList[i] + ") ";
                        qwe += " and Position " + Convert.ToString(a) + "(" + NumList[a] + ") ";
                        qwe += "  - NB Position count starts at 0";

                        Console.WriteLine(qwe);
                    }
                }
            }
        }
    }
}

The Explanation

This is one of "them" test questions. 

Enter a list of numbers - for example "1,3,5,7,9,11,13,15". Now enter a single number - for example "16"

You have to produce which (if any) of TWO numbers from the list that when added together will give the single number. For example in from the above list we can use 5 and 11 to give the answer 16.

I'm not going to explain the code above in detail. Suffice to say we double loop through the list checking to see which numbers in the list add up to the second number we entered. NOTE! This is my first go at this and this is considered the "brute force" method. There are better ways to do this using HashMaps (JS) or Dictionaries (C#). I... I just don't know how to do this yet. 

Onwards!

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog