Different numbers from 1 to 10

前端 未结 5 1079
太阳男子
太阳男子 2020-12-02 00:20

I want to generate 10 different numbers from a range of 0-9. the desired output may look like this, 9 0 8 6 5 3 2 4 1 7

Dim arraynum(9) As Integer
Dim crmd A         


        
5条回答
  •  时光取名叫无心
    2020-12-02 00:56

    Option Explicit 'Force variable declaration
    
    Private Sub Form_Load()
        Dim Ar(1 To 100) As Integer 'The array to store it in
        Dim i, j As Integer 'Counters for loops
        Dim X As Integer 'Variable to store the random generated number
        Dim bFound As Boolean 'Boolean to check if the value has been generated before
    
        Randomize 'Just once to ensure that we get random values
    
        For i = 1 To 100
            Do 'Start the loop that generates a random number and checks if it has already been generated
                X = RandomInteger(1, 100) 'Generate a random number
                bFound = False 'Set the boolean to false, if we find the number while searching the array, we'll set it to true which means that we already have that number
                For j = 1 To i 'We only need to check up to i (since we haven't put any values in the rest of the array)
                    If Ar(j) = X Then 'If an item of the arrray is the same as the last generated number
                        bFound = True 'Set the boolean to true (it already exists)
                        DoEvents 'To not freeze until the looping is done
                        Exit For 'Since we found it there is no need to check the rest
                    End If
                Next
            Loop Until bFound = False 'If it wasn't found then we'll add it, if it was found then we go back to generating a new number and comparing it with all the items of the array
            Ar(i) = X 'Add it to the array
        Next
    
        ShowInTextBox Text1, Ar 'Just to print the data and see it
    End Sub
    
    Private Function RandomInteger(Lowerbound As Integer, Upperbound As Integer) As Integer 'The random number generator code
        RandomInteger = Int((Upperbound - Lowerbound + 1) * Rnd + Lowerbound)
    End Function
    
    Private Sub ShowInTextBox(TB As TextBox, A() As Integer) 'Just a sub to show the data in a textbox
        Dim i As Integer
    
        TB.Text = ""
    
        For i = 1 To UBound(A)
            TB.Text = TB.Text & CStr(A(i)) & vbCrLf
        Next
    
        TB.Text = Left$(TB.Text, Len(TB.Text) - 2)
    End Sub
    

提交回复
热议问题