How to pick a random Object in a List

BlitzMax Forums/BlitzMax Programming/How to pick a random Object in a List

Matt McFarland(Posted 2006) [#1]
First, get the maximum number in the list.

If the maximum number is 35 then do this:

picked(Rand1,35)

Now do a FOR / NEXT loop..

For Local Enemy:Tenemy = EachIn EnemyList
        selector:+1 			 	
	If selector = picked
        Print "You picked me"
        EndIf
Next


Everytime you destroy the an enemy the Maxenemies goes down :D


taxlerendiosk(Posted 2006) [#2]
Why not just
MyList.ValueAtIndex(Rand(0,MyList.Count()-1))



Matt McFarland(Posted 2006) [#3]
Does that always pick one though?


Tom(Posted 2006) [#4]
Let's complicate things :)

Type test
	Global list:TList = CreateList()
	
	Field link:TLink
	Field x:Int
	
	Method New()
		link = ListAddLast(list,Self)
	End Method
	
	Method info()
		Print "I am test No. "+x
	End Method
End Type

Local t:test, i:Int

For i = 0 Until 100
	t = New test
	t.x = i
Next

SeedRnd(MilliSecs())

test(ListToArray(test.list)[Rand(test.list.Count()-1)]).info

'or

t = test(ListToArray(test.list)[Rand(test.list.Count()-1)])
t.info



taxlerendiosk(Posted 2006) [#5]
Does that always pick one though?

Sure, why wouldn't it? Rand(0,MyList.Count()-1) chooses a random valid index, the ValueAtIndex method gets the object held at that index. It's basically exactly the same process as your loop.

Tom - why are you converting the list to an array and then indexing that? ValueAtIndex does the same thing faster.


Tom(Posted 2006) [#6]
I was just being an arse, sorry :)


Eric(Posted 2006) [#7]
SuperStrict
Global ItemList:Tlist=New Tlist

Type Item
	Field A:Int
	Function  Create:Item(B:Int)
		Local Item:Item=New Item 
		Item.A=B
		ListAddLast ItemList,Item
	End Function  
End Type 

For Local Index:Int=1 To 10
	Item.Create(Index)
Next

For Local Temp:Item=EachIn ItemList
	Print Temp.A
Next 

For Local Index:Int=1 To 10

Local RandomItem:Item=ItemList.ValueAtIndex(Rand(0,CountList(ItemList)-1)) 

Next 


Can someone please help... I want RandomItem to be a randomly selected Type instance.


Scott Shaver(Posted 2006) [#8]
Local RandomItem:Item=Item(ItemList.ValueAtIndex(Rand(0,CountList(ItemList)-1)) )


Eric(Posted 2006) [#9]
Wow how simple... but how did you know that where is it in the docs?


Scott Shaver(Posted 2006) [#10]
I've been using OOP languages for a long time, type casting is second nature to me I guess. I don't know where in the docs it says how to do this, I must have seen it in some example code. I'm used to the casting working in reverse (type)exp not type(exp).