Games
Problems
Go Pro!

Randomizing an Array

Reference > Science > Technology > Beginner Programming Tips
 

You have an array of elements (integers, strings, or another variable type; it doesn't really matter) and you want to scramble the order of these elements. This is something you'll need to do occasionally if you are trying to write a game program, or you are trying to simulate a real world random situation.

But how do you go about doing it? Take a look at this piece of code, and then I'll talk you through it. This is not the only way to do it. In fact, it might not even be the most efficient. But it works, and it's easy to program. 
 

Dim MyArray(9) As String
Dim I As Integer
Dim Index1 As Integer
Dim Index2 As Integer
Dim Temp As String

'Scramble the Order
For I = 1 To 20
   Index1 = Int(Rnd * 10)
   Index2 = Int(Rnd * 10)
   While Index1 = Index2
      Index2 = Int(Rnd * 10)
   Wend
   Temp = MyArray(Index1)
   MyArray(Index1) = MyArray(Index2)
   MyArray(Index2) = Temp
Next I


Did that make sense to you? Let's talk through what is happening here. After declaring my variables (and presumably assigning some values to MyArray(0) through MyArray(9), we get to my For-Next loop. This loop runs twenty times, which I figured was enough to randomize my array. If my array wasbigger I would need to run this loop more, to make sure the list was well scrambled.

Now I pick two different array indexes. Once I've picked them, I'm going to swap those two array elements. Since I don't want to swap an array element with itself (that wouldn't do a whole lot towards scrambling the array, would it?) I check to see if Index1 = Index2.

As long as Index1 = Index2, I keep picking another random Index2, until it's different from Index1.

Now that Index1 and Index2 are two different indices into the array, I swap them. To do this, I use a temporary storage place (the variable Temp) to put one of them in so neither value gets lost.

Now I go back and do it again and again, until the For-Next loop is finished.

Like I said, this is not the only way to randomize an array, and in my next article, I'll talk about another method, which you might find useful.

Questions

1.
Suppose your array had five elements. How many times do you think you should run the For-Next loop to thoroughly randomize the array? What if you had twenty array elements? Fifty? Test out each one, and see what it takes to thoroughly randomize the array. Do you think you can come up with an equation that describes how many times you should run the loop, based on the size of the array?
Assign this reference page
Click here to assign this reference page to your students.
Copy and Paste Rule of ThumbCopy and Paste Rule of Thumb
Randomizing an Array of IndicesRandomizing an Array of Indices
 

Blogs on This Site

Reviews and book lists - books we love!
The site administrator fields questions from visitors.
Like us on Facebook to get updates about new resources
Home
Pro Membership
About
Privacy