Kirjautuminen

Haku

Tehtävät

Keskustelu: Koodit: VB.NET: Kombinaatioitten generointi

tnb [18.11.2003 23:23:14]

#

Kombinaatioiden generointi muuttujaan, esim 3 numeroa 5:stä
- sama numero ei voi esiintyä kahdesti samassa sarjassa
- samaa sarjaa ei saa esiintyä listassa
- kaikki vaihtoehtoiset sarjat listataan
VB.net ohjelma, soveltuu pienin muutoksin VB6:lle

Testaus ohjelma

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     '
     ' test Combins
     '
     Dim level As Long
     Dim elem As Long
     Dim n As Long
     Dim m As Long
     Dim j As Long
     Dim k As Long
     Dim A(,) As Long = New Long(1000, 10) {}
     n = 3
     m = 5
     level = 0
     elem = 0

     Combins(n, m, level, elem, A)
     'print
     TextBox1.Text = "Combinations " & Format(n) & " out of " & Format(m) & Chr(13) & Chr(10)
     For j = 1 To 10
         For k = 1 To n
             TextBox1.Text = TextBox1.Text & Format(A(j, k))
         Next
         TextBox1.Text = TextBox1.Text & Chr(13) & Chr(10)
     Next
 End Sub

Varsinainen ohjelma Combins

Public Sub Combins(ByVal n As Long, ByVal m As Long, ByVal level As Long, ByRef elem As Long, ByRef A(,) As Long)
        ' n out of m combinations to array A(,)
        Dim illeg As Boolean
        Dim counter As Long
        Dim k As Long
        Dim j As Long
        Dim i As Long
        level = level + 1
        If level > n Then
            ' is it a new combination
            illeg = False
            For k = 1 To elem
                counter = 0
                For j = 1 To n
                    For i = 1 To n
                        If A(elem + 1, i) = A(k, j) Then counter = counter + 1
                    Next i
                Next j
                If counter = n Then illeg = True 'combination already exists
            Next k
            If Not illeg Then
                ' so add it
                elem = elem + 1
                'remember values from previoius levels
                For j = 1 To level - 1
                    A(elem + 1, j) = A(elem, j)
                Next j
            End If
            Exit Sub 'return up one level
        Else
            For k = 1 To m
                A(elem + 1, level) = k
                If level > 1 Then
                    'check if the number is already used
                    illeg = False
                    For j = 1 To level - 1
                        If A(elem + 1, level) = A(elem + 1, j) Then illeg = True
                    Next j
                End If
                'if not used add it and call myself
                If Not illeg Then Combins(n, m, level, elem, A)
            Next k
        End If
    End Sub

Vastaus

Aihe on jo aika vanha, joten et voi enää vastata siihen.

Tietoa sivustosta