In Part 1 we examined just one way to randomly reorder an array. In this part we'll look at alternative method!
Now, this is just one way of reordering an array. Another way (which I think looks uber-cool) is to create a separate array that contains the indexes of the first array. So, if our array to reorder had five elements (0 through 4), our index array would contain five elements too. Initially, this array would contain the following values:
Index Array (aTmp) | |
|---|---|
| Index | Value |
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
In our reordering function, we'll jumble up the values of the index array and then use these new values to determine the ordering of the array that we are reordering. I know this may sound a bit confusing, so hopefully this will clear things up a bit. Imagine that the array we wish to reorder contains the following indexes/values.
| Array to Reorder | |
|---|---|
| Index | Value |
| 0 | Scott |
| 1 | Bob |
| 2 | Steve |
| 3 | Frank |
| 4 | Charles |
Now, imagine that, after jumbling about our array of indexes, this array - aTmp -
contains the following values:
Index Array (aTmp) | |
|---|---|
| Index | Value |
| 0 | 3 |
| 1 | 0 |
| 2 | 1 |
| 3 | 4 |
| 4 | 2 |
Then, our reordered array would have the third element listed first, then the zeroth
element, then the first element, then the fourth, and finally the second. (The
order of the values in the aTmp array):
| Array to Reorder | |
|---|---|
| Index | Value |
| 0 | Frank |
| 1 | Scott |
| 2 | Bob |
| 3 | Charles |
| 4 | Steve |
Hopefully that makes sense. Now, in our reordering function, we will create our
indexer array, aTmp, and populate it with the available indexes (0 through
4 in the above example). Then, we will iterate through the values of the array we wish
to reorder. In each iteration, we will randomly select a value from the aTmp
array. Since a value in aTmp is an index, we'll use this information to
know what value from the array to order to put where... We will then resize the aTmp
array, removing the index we just plucked out. OK, OK, I know that all may sound very
confusing, but hopefully an example will help:
|
Obviously the above method is much more complex that the first example we looked
at. Also, the above example has a limitation - since it uses the split
and join functions it will only work with single-dimensional arrays. (For
more information on the split and join functions, be sure to read: Parsing
with split and join!)
In Part 3 we'll examine how to use array reordering to display Recordsets in random order!




