TwoSum
In TwoSum, the goal is to take a given array of numbers (positive or negative) and given a sum (the target number), find all pairs of numbers that can be added together that equal that target.
Example: sum = 10, and the array contains {1, -9, 3, 7, 19, 11} then your function should return (-9, 19) and (3, 7).
using System;
using System.Collections.Generic;
using System.Linq;
class TwoSum
{
public static Tuple FindTwoSum(IList list, int sum)
{
int indexA = 0;
int indexB = 0;
Random rand = new Random();
Tuple result = null;
var results = new Dictionary();
foreach (int v in list) //this is the slow way to do it ( iterative nested loops)
{
foreach (int r in list)
{
Console.WriteLine(v + " + " + r + " = " + (v + r));
if (v + r == sum)
{
Console.WriteLine("Hit! indexA: " + indexA + ", indexB: " + indexB);
Console.WriteLine();
results.Add(indexA, indexB);
break;
}
indexB++;
}
indexA++;
indexB = 0;
}
int i = 0;
int t = 0;
if(results.Count > 0)
{
t = rand.Next(0, (results.Count - 1));
}
Console.WriteLine();
Console.WriteLine("random: " + t);
Console.WriteLine("checking Dictionary");
foreach (KeyValuePair pair in results)
{
Console.WriteLine(pair.Key + ", " + pair.Value);
if (i == t)
{
result = new Tuple(pair.Key, pair.Value);
}
i++;
}
return result;
}
public static void Main(string[] args)
{
Tuple indices = FindTwoSum(new List() { 3, 1, 5, 7, 5, 9 }, 10);
if(indices != null)
{
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}
}