How to access a random type object

Community Forums/General Help/How to access a random type object

Flanker(Posted 2016) [#1]
Hello, for some reason I need to access a random type object.

For now i'm doing this like that :
random = rand(1,cellsCount)
count = 0

for c.cell = each cell
 count = count + 1
 if count = random then return c
next

The problem is that it's not efficient at all in CPU cost with a high number of objects.

How would you do that differently ?

I'm thinking to store type handles in an array, then randomly access the array, but as the type list changes all the time, I can't figure how to update the array at the same time so I can't pick an object that doesn't exist anymore.


RemiD(Posted 2016) [#2]
I would also store the handle of each instance of a customtype in a dim array :
dim Thing_H%(1000000) ;even with 1 000 000 handles stored, this would corresponds to only around 4mo in memory...


if you don't plan to create/destroy many instances you don't need to reorganize the dim array list, simply set the Thing_H(I) to 0

but if you plan to create/destroy many instances you may need to reorganize the dim array list, you don't need to do it each time you delete an instance, maybe once a loop.
depending on the size of the list, it takes less than 1ms...

i would do something like this :
;array list where you store the handles
global ThingsCount%
dim Thing_H%(1000)

;array list uses for the reorganization of the Thing array list
global SwapThingsCount%
dim SwapThing_H%(1000)

;Copy the remaining entries in the Thing array to the SwapThing array (keep a SwapThingsCount)

;Delete all entries in the Thing array (facultative in this case since there are only integers)

;Copy all entries in the SwapThing to the Thing array (keep a ThingsCount)

;Delete all entries in the SwapThing array (facultative in this case since there are only integers)


Flanker(Posted 2016) [#3]
Thanks RemiD, I solved the problem using an array to store type handles, and everytime an object is deleted, the last type handle is swapped in the array from last position to the deleted object position. This way I don't need to reorganize the whole array.


RemiD(Posted 2016) [#4]
Here is another way which seems to work but you will have to use only one customtype :
Graphics3D(640,480,32,2)

SeedRnd(MilliSecs())

Global ThingsCount%
Type Thing
 Field Value%
End Type

;create some Things
For n% = 1 To 10 Step 1
 ThingsCount = ThingsCount + 1
 t.Thing = New Thing
 t\Value = Rand(1,100)
 DebugLog("Thing"+Handle(t)+"\Value = "+t\Value)
Next

;delete some Things
For n% = 1 To 5 Step 1
 H% = Rand(1,ThingsCount)
 t.Thing = Object.Thing(H)
 If( t <> Null )
  Delete(t)
 EndIf
Next

;randomly select a Thing
.LineSelectThingH
H% = Rand(1,ThingsCount)
t.Thing = Object.Thing(H)
If( t <> Null )
 DebugLog("Thing"+Handle(t)+"\Value = "+t\Value)
Else 
 Goto LineSelectThingH
EndIf

WaitKey()

End()