VB.NET School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

VB.NET Source Code


Welcome to Dream.In.Code
Become a VB.NET Expert!

Join 306,756 VB.NET Programmers for FREE! Get instant access to thousands of VB.NET experts, tutorials, code snippets, and more! There are 1,815 people online right now. Registration is fast and FREE... Join Now!





FindCombinations

Creates a list of the combinations of length K in a range 1 -> N.

Submitted By: AdamSpeight2008
Actions:
Rating:
Views: 118

Language: VB.NET

Last Modified: October 28, 2009
Instructions: Requires .net >=3.5

Snippet


  1. Module Combinations_Module
  2.  Sub Main()
  3.   ' examp
  4.   Dim r As List(Of Integer()) = FindCombinations(16, 2)
  5.  
  6.  End Sub
  7.  
  8.  <DebuggerStepperBoundary(), DebuggerHidden()> _
  9.  Public Function FindCombinations(ByVal n As Integer, ByVal k As Integer) As List(Of Integer())
  10.   If n < 1 Then Throw New ArgumentException("N must be at least 1")
  11.   If k < 1 Then Throw New ArgumentException("K must be at least 1")
  12.   If k > n Then Throw New ArgumentException(String.Format("K mustn't be greater than {0}", n))
  13.   Dim C As New List(Of Integer())
  14.   Dim CN As New List(Of Integer)
  15.   CN.Add(0)
  16.   FindNextCombination(CN, C, n, k)
  17.   Return C
  18.  
  19.  End Function
  20.  <DebuggerStepperBoundary(), DebuggerHidden()> _
  21. Private Sub FindNextCombination(ByRef CN As List(Of Integer), ByRef C As List(Of Integer()), ByRef n As Integer, ByRef k As Integer)
  22.   If CN.Count > k Then
  23.    'Found a combination, so add it to list.
  24.    C.Add(CN.Take(CN.Count - 1).ToArray())
  25.   Else
  26.    While CN.Last < n
  27.     CN.Add(CN.Last + 1)
  28.     FindNextCombination(CN, C, n, k)
  29.     CN.RemoveAt(CN.Count - 1)
  30.     CN(CN.Count - 1) += 1
  31.    End While
  32.   End If
  33.  End Sub
  34.  
  35. End Module
  36.  
  37.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live VB.NET Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

VB.NET Tutorials

Reference Sheets

VB.NET Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month