Juggler_IN
Active Member
- Joined
- Nov 19, 2014
- Messages
- 349
- Office Version
- 2003 or older
- Platform
- Windows
How can we generate the partitions of a given set using VBA. For example, the set {1, 2, 3} has these five partitions (one partition per item):
{ {1}, {2}, {3} }, sometimes written 1|2|3.
{ {1, 2}, {3} }, or 12|3.
{ {1, 3}, {2} }, or 13|2.
{ {1}, {2, 3} }, or 1|23.
{ {1, 2, 3} }, or 123.
Wikipedia Reference: Set-Partition
There is an article with a non-vba code which is generating the sets using Stirling numbers of second kind, Set-Generate but I could not comprehend the same. I have the Stirling number UDF.
{ {1}, {2}, {3} }, sometimes written 1|2|3.
{ {1, 2}, {3} }, or 12|3.
{ {1, 3}, {2} }, or 13|2.
{ {1}, {2, 3} }, or 1|23.
{ {1, 2, 3} }, or 123.
Wikipedia Reference: Set-Partition
There is an article with a non-vba code which is generating the sets using Stirling numbers of second kind, Set-Generate but I could not comprehend the same. I have the Stirling number UDF.
VBA Code:
Public Function StirlingType2( _
ByVal n As Long, _
ByVal k As Long) As Long
Dim u, v, i, j
u = k ^ n
v = 0
i = 0
j = 0
If k = n Then
StirlingType2 = 1&
ElseIf k > n Then
StirlingType2 = 0&
ElseIf k = 0& Then
StirlingType2 = 0&
Else
For i = 1 To (k - 1)
j = Application.WorksheetFunction.Combin(k, i) * (k - i) ^ n
If i Mod 2 = 0 Then
v = v + j
Else
v = v - j
End If
Next
StirlingType2 = (u + v) / Application.WorksheetFunction.Fact(k)
End If
End Function