Array Shuffler (1 Viewer)

Status
Not open for further replies.

ajetrumpet

Banned
Local time
Today, 14:13
Joined
Jun 22, 2007
Messages
5,638
Below is some code that I wrote to shuffle arrays. The first block deals with one-dimensionals, and the second deals with two-dimensionals. I have written the code for pre-defined arrays rather than dynamic ones, but it works for both types:

1 dimension
Code:
Function ArrayShuffler1()

Dim i As Integer
  Dim j As Integer
    Dim int1 As Integer
      Dim int2 As Integer
        Dim strVAR As String
          Dim var(10) As Variant

  For i = LBound(var) To UBound(var)
    
    var(i) = i
    Debug.Print var(i)
  
  Next i

Debug.Print vbCr

Randomize

    For i = LBound(var) To UBound(var)

      int1 = Int(Rnd * (UBound(var) - LBound(var) + 1))
      int2 = Int(Rnd * (UBound(var) - LBound(var) + 1))

        While int1 = int2
          int2 = Int(Rnd * (UBound(var) - LBound(var) + 1))
        Wend

      strVAR = var(int1)
      var(int1) = var(int2)
      var(int2) = strVAR

    Next i

Debug.Print vbCr

  For i = LBound(var) To UBound(var)

    Debug.Print var(i)
    
  Next i

End Function

2 dimensions
Code:
Function ArrayShuffler2()

Dim i As Integer
  Dim j As Integer
    Dim int1 As Integer
      Dim int2 As Integer
        Dim strOLD As String
          Dim strNEW As String
            Dim strVAR As String
              Dim var(5, 9) As Variant

strOLD = ""
strNEW = ""

  For i = LBound(var, 2) To UBound(var, 2)

    For j = LBound(var, 1) To UBound(var, 1)
      var(j, i) = j & "," & i
      strOLD = strOLD & var(j, i) & "  "
    Next j

  Debug.Print strOLD
    strOLD = ""

  Next i

Randomize

    For i = LBound(var, 2) To UBound(var, 2)

      int1 = Int(Rnd * (UBound(var, 2) - LBound(var, 2) + 1))
      int2 = Int(Rnd * (UBound(var, 2) - LBound(var, 2) + 1))

        While int1 = int2
          int2 = Int(Rnd * (UBound(var, 2) - LBound(var, 2) + 1))
        Wend

      For j = LBound(var, 1) To UBound(var, 1)
                                              
        strVAR = var(j, int1)
        var(j, int1) = var(j, int2)
        var(j, int2) = strVAR

      Next j

    Next i

Debug.Print vbCr

  For i = LBound(var, 2) To UBound(var, 2)
  
    For j = LBound(var, 1) To UBound(var, 1)
      strNEW = strNEW & var(j, i) & "  "
    Next j

  Debug.Print strNEW
    strNEW = ""

  Next i

End Function
 
Status
Not open for further replies.

Users who are viewing this thread

Top Bottom