Randomize array elements

retkehing

Well-known member
Joined
Feb 5, 2006
Messages
153
Programming Experience
Beginner
I tried to randomize the elements in a two dimension array by using the following code, the FirstUBound and SecondUBound are declared as global variables and a RandomArray function is used to determine whether any random value has been occupied previously. If no then return the value or else keep looping itself until a new value is generated. Suppose one value should assign one time and the remaining value for assignment must be different from the previous but still there are repeating elements exist in the output. After that, I have checked through my coding for several times and have no idea on where went wrong. So please help me to solve the problem if you can, thank you.

VB.NET:
Dim IniPop(FirstUBound, SecondUBound) As Integer
Dim Random As New System.Random
 
For i = 0 To FirstUBound
    For j = 0 To SecondUBound
        Dim Index As Integer = Random.Next(1, (SecondUBound+1)+ 1)
 
        array(i, j) = RandomArray(i, Index, array)
    Next j
Next i
 
Public Function RandomizePop(ByVal i As Integer, ByVal Index As Integer, ByVal array(,) As Integer)
    Dim Random As New System.Random
    Dim j As Integer
 
    For j = 0 To SecondUBound
        If array(i, j) = Index Then
            Index = Random.Next(1, (SecondUBound+1)+ 1)
            RandomArray(i, Index, array)
        End If
    Next j
 
    Return Index
End Function
 
Last edited:
When the FirstUBound equals to 3 and SecondUBound is 3 then the array will be
0: 0 1 2 3
1: 0 1 2 3
2: 0 1 2 3
3: 0 1 2 3
The maximum random number of (SecondUBound+1)+ 1=5 ensures that the random number will be range from 1 to 5, which means 1, 2, 3, 4 because i want to start the number for occupation from 1 instead of 0.
 
Back
Top