- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathCatalanNumbers.cs
91 lines (76 loc) · 2.79 KB
/
CatalanNumbers.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
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
83
84
85
86
87
88
89
90
91
/***
* Computes the Catalan Numbers. A dynamic-programming solution.
*
* Wikipedia: https://en.wikipedia.org/wiki/Catalan_number
*/
usingSystem.Diagnostics;
usingSystem.Collections.Generic;
usingSystem.Numerics;
namespaceAlgorithms.Numeric
{
publicstaticclassCatalanNumbers
{
/// <summary>
/// Internal cache.
/// By default contains the first two catalan numbers for the ranks: 0, and 1.
/// </summary>
privatestaticreadonlyDictionary<uint,BigInteger>CachedCatalanNumbers=newDictionary<uint,BigInteger>{{0,1},{1,1}};
/// <summary>
/// Helper method.
/// </summary>
/// <param name="rank"></param>
/// <returns></returns>
privatestaticBigInteger_recursiveHelper(uintrank)
{
if(CachedCatalanNumbers.ContainsKey(rank))
returnCachedCatalanNumbers[rank];
BigIntegernumber=0;
varlastRank=rank-1;
for(uinti=0;i<=lastRank;++i)
{
varfirstPart=_recursiveHelper(i);
varsecondPart=_recursiveHelper(lastRank-i);
if(!CachedCatalanNumbers.ContainsKey(i))CachedCatalanNumbers.Add(i,firstPart);
if(!CachedCatalanNumbers.ContainsKey(lastRank-i))CachedCatalanNumbers.Add(lastRank-i,secondPart);
number=number+(firstPart*secondPart);
}
returnnumber;
}
/// <summary>
/// Public API.
/// </summary>
/// <param name="rank"></param>
/// <returns></returns>
publicstaticBigIntegerGetNumber(uintrank)
{
// Assert the cache is not empty.
Debug.Assert(CachedCatalanNumbers.Count>=2);
return_recursiveHelper(rank);
}
/// <summary>
/// Calculate the number using the Binomial Coefficients algorithm
/// </summary>
/// <param name="rank"></param>
/// <returns></returns>
publicstaticBigIntegerGetNumberByBinomialCoefficients(uintrank)
{
// Calculate by binomial coefficient.
returnBinomialCoefficients.Calculate(rank);
}
/// <summary>
/// Return the list of catalan numbers between two ranks, inclusive
/// </summary>
/// <param name="fromRank"></param>
/// <param name="toRank"></param>
/// <returns></returns>
publicstaticList<BigInteger>GetRange(uintfromRank,uinttoRank)
{
varnumbers=newList<BigInteger>();
if(fromRank>toRank)
returnnull;
for(vari=fromRank;i<=toRank;++i)
numbers.Add(GetNumber(i));
returnnumbers;
}
}
}