-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp.linq
More file actions
82 lines (67 loc) · 1.73 KB
/
temp.linq
File metadata and controls
82 lines (67 loc) · 1.73 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<Query Kind="Program" />
List<int> compareList = new List<int>();
// GetPossibleCombination method.
// This method finds out the unique number of possible combinations where
// addition of any 2 values from the list is exactly equal to 'totalValue'
int GetPossibleCombinations(List<int> intList, long totalValue)
{
var dictionary = new int[intList.Max() + 1];
foreach (var i in intList)
{
dictionary[i]++;
}
return CombinationsHelper(totalValue, dictionary, 2);
}
int CombinationsHelper(long sum, int[] dictionary, int k)
{
if (sum == 0 && k == 0)
{
return 1;
}
else if ((sum == 0 && k != 0) || (sum != 0 && k == 0))
{
return 0;
}
int result = 0;
for (int i = 1; i < dictionary.Length; i++)
{
if (dictionary[i] > 0)
{
dictionary[i]--;
result += CombinationsHelper(sum - i, dictionary, k - 1);
dictionary[i]++;
}
}
return result;
}
// This method creates a list of possible values we have
bool IsPairUnique(int v1, int v2)
{
if (compareList.Contains(v1 * 10 + v2) == true || compareList.Contains(v2 * 10 + v1) == true)
return false;
else
{
// else add a new one
compareList.Add(v1 * 10 + v2);
compareList.Add(v2 * 10 + v1);
}
return true;
}
void Main(string[] args)
{
int intListSize = 500000; // Optimize it for numbers upto 500,000
long totalValue = 5000;
List<int> intList = new List<int>();
Random r = new Random();
for (int i = 0; i < intListSize; i++)
{
intList.Add(r.Next(0, 10000)); // populate random values.
}
Stopwatch sw = new Stopwatch();
sw.Start();
// Find the number of unique pairs in 'intList' such that
// their addition is exactly equal to 'totalValue'
int res = GetPossibleCombinations(intList, totalValue).Dump();
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString());
}