-
Notifications
You must be signed in to change notification settings - Fork 0
/
PairFinder.cs
39 lines (36 loc) · 845 Bytes
/
PairFinder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
namespace Numbers
{
/// <summary>
/// Finds pairs of numbers
/// </summary>
public static class PairFinder
{
/// <summary>
/// Returns number pairs for the specified sum
/// </summary>
public static IEnumerable<Tuple<int, int>> FindPairsFor(this IList<int> list, int sum)
{
var result = new List<Tuple<int, int>>();
var usedIndexes = new HashSet<int>();
for (int i = 0; i < list.Count - 1; i++)
{
if (usedIndexes.Contains(i)) continue;
for (int j = i + 1; j < list.Count; j++)
{
if (usedIndexes.Contains(j)) continue;
var first = list[i];
var second = list[j];
if (first + second == sum)
{
usedIndexes.Add(j);
result.Add(new Tuple<int, int>(first, second));
break;
}
}
}
return result;
}
}
}