Description The idea is to find any 2 values within a list of numbers that satisfy a condition. There are many approaches to this problem but one fast approach is to use a sorted dictionary which reduces iterations

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
static void FindPairs(int[] numbers, int sum) { SortedDictionary<int, int> Map = new SortedDictionary<int, int>(); for (int i = 0; i < numbers.Length; i++) { int number = numbers[i]; if (Map.ContainsValue(sum - number)) { int mKey = Map.Where(x => x.Value == (sum - number)).First().Key; Console.WriteLine("a[{0}]:{1} + a[{2}]:{3}", i, number, mKey, (sum - number)); } Map.Add(i, number); } } |

Using A Condition Using a condition to test the relation between 2 values is easily achievedRead more