Snippet
Module Combinations_Module
Sub Main()
' examp
Dim r As List(Of Integer()) = FindCombinations(16, 2)
End Sub
<DebuggerStepperBoundary(), DebuggerHidden()> _
Public Function FindCombinations(ByVal n As Integer, ByVal k As Integer) As List(Of Integer())
If n < 1 Then Throw New ArgumentException("N must be at least 1")
If k < 1 Then Throw New ArgumentException("K must be at least 1")
If k > n Then Throw New ArgumentException(String.Format("K mustn't be greater than {0}", n))
Dim C As New List(Of Integer())
Dim CN As New List(Of Integer)
CN.Add(0)
FindNextCombination(CN, C, n, k)
Return C
End Function
<DebuggerStepperBoundary(), DebuggerHidden()> _
Private Sub FindNextCombination(ByRef CN As List(Of Integer), ByRef C As List(Of Integer()), ByRef n As Integer, ByRef k As Integer)
If CN.Count > k Then
'Found a combination, so add it to list.
C.Add(CN.Take(CN.Count - 1).ToArray())
Else
While CN.Last < n
CN.Add(CN.Last + 1)
FindNextCombination(CN, C, n, k)
CN.RemoveAt(CN.Count - 1)
CN(CN.Count - 1) += 1
End While
End If
End Sub
End Module
Copy & Paste
|