|
-
Sep 12th, 2003, 05:38 PM
#1
Thread Starter
Fanatic Member
Shuffle an Array
I have an array that I want to shuffle. By shuffle I mean move the elements around to different locations.
Does anyone know of a simple way to make this happen? I did a search on "random array" and a search on "shuffle array" but neither turned up the results I had hoped for.
-Matt
-
Sep 12th, 2003, 05:52 PM
#2
Its probably easier to retrieve them randomly then to move them around inside the array to a random order.
-
Sep 12th, 2003, 05:53 PM
#3
Thread Starter
Fanatic Member
cant it has to be programmed in.
-
Sep 12th, 2003, 05:55 PM
#4
Sleep mode
Did you have a look at Reverse() Function in the array obj ? I don't know if that's what want .
-
Sep 12th, 2003, 05:57 PM
#5
Thread Starter
Fanatic Member
Doesn't reverse just reverse the order?? that isnt shuffling the order.
-
Sep 12th, 2003, 07:36 PM
#6
PowerPoster
Do something like this (psudocode):
Code:
For i=0 to array.length
' get a random number between 0 and array.length
Dim Random as ......a random number code.
Dim Temp as String
Temp = array(i)
array(i) = array(Random)
array(Random) = Temp
Next
So basically, you go through each item, and randomly switch it with another item.
-
Sep 13th, 2003, 12:21 PM
#7
Lively Member
I just threw this together... Let me know how it works...
place code inside a button
Code:
Dim items() As String = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
ShuffleArray(items)
Module
Code:
Public Function ShuffleArray(ByRef Obj())
Dim xCount As Integer = 0
Dim TmpArray()
ReDim TmpArray(0)
Dim xVal As Integer
Randomize()
Do Until xCount = Obj.Length
xVal = CInt(Int(Obj.Length * Rnd()))
If Not Obj(xVal) Is Nothing Then
If xCount > 0 Then ReDim Preserve TmpArray(xCount)
TmpArray(xCount) = Obj(xVal)
xCount += 1
Array.Clear(Obj, xVal, 1)
End If
Loop
Dim i As Integer = 0
For i = 0 To xCount - 1
Obj(i) = TmpArray(i)
Next
End Function
-
Sep 13th, 2003, 12:45 PM
#8
PowerPoster
There is no need for all that. I took my psudocode and wrote it out for you.
VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim items() As String = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
items = ShuffleArray(items)
End Sub
Private Function ShuffleArray(ByVal obj() As Object) As Object()
Dim Temp As Object
Dim randomNum As Integer
Dim i As Integer
For i = 0 To obj.Length - 1
randomNum = New System.Random().Next(1, obj.Length - 1)
Temp = obj(i)
obj(i) = obj(randomNum)
obj(randomNum) = Temp
Next
ShuffleArray = obj
End Function
Last edited by hellswraith; Sep 13th, 2003 at 02:01 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|