Randomise a list of objects
Blitz3D Forums/Blitz3D Programming/Randomise a list of objects
| ||
| I have a list of objects in an array I want to randomise. I'm looking for the most efficient way of doing this. Current methods involve systematically stepping through the array and, with a random number generatator, picking two points of the array to 'swap' with each other. Theres got to be a faster method though, so if anyone has any ideas I'd appreciate them. |
| ||
| You have an array of 10 elements Make a rnd number 1-10 (returns 7) index that (7th) element as 1st remove from list You now have an array of 9 elements. do the same to get the 2nd. and so on. just one technique. |
| ||
I wrote a function for this long ago, you can use it if you want:
;You need the array you want the elements to be randomly arranged, and the max number of elements that array should have:
Const MaxSlots = 10
Dim Array(MaxSlots-1)
Function RandomlyArrangeArray()
Local Temp[MaxSlots-1]
Local TempSlots = MaxSlots-1
Local Random
For I = 0 To MaxSlots-1
Temp[I] = I ;This loop populates the temporary array. You should change this to fit your needs.
Next
For I = 0 To MaxSlots-1
Random = Rand(0,TempSlots)
Array(I) = Temp[Random] ;Note that you need to specify which array to re-arrange.
For I2 = 0 To MaxSlots-1
If (I2 < TempSlots) Then
If (I2 >= Random) Then Temp[I2] = Temp[I2+1]
EndIf
Next
TempSlots = TempSlots - 1
Next
End Function
PRO's: Uses a local array and variables, so it's very light.CON's: You need to write the name of the array you want to re-arrange, inside the function. Don't mind the function's big name. |