var array - [0,1,2,3,4,5]
randomize()
print(array[randi()%array.size()])
array[randi()%array.size()] is random element from array
This is helpfull. Just thought i’d ask but is there a way to randomize the entire list? like in pythons random.shuffle(myList) method?
vonflyhighace2 | 2016-04-02 22:17
Sadly GDScript isn’t Python and isn’t as feature rich. But this should work:
func shuffleList(list):
var shuffledList = []
var indexList = range(list.size())
for i in range(list.size()):
var x = randi()%indexIist.size()
shuffledList.append(list[indexList[x]])
indexList.remove(x)
return shuffledList
Note: haven’t tested it myself
Edit: fixed appending the wrong thing into shuffled list
batmanasb | 2016-04-02 23:04
Thanks :batmanasb: it worked. i just did some teaking to it to get it to work the way i wanted.
func shuffleList(list):
var shuffledList = []
var indexList = range(list.size())
for i in range(list.size()):
randomize()
var x = randi()%indexList.size()
shuffledList.append(list[x])
indexList.remove(x)
list.remove(x)
return shuffledList`
vonflyhighace2 | 2016-04-03 00:33
Woops, appended the index instead of the item at the index, good catch! Fixed it. Oh and I think you only need to call randomize() once per instance. So I usually call it in _ready()
batmanasb | 2016-04-03 01:35
this line “list.remove(x)” is wrong
you affect the input list, this function still works if you remove this line
func sample(list,amt):
var shuffled = list.duplicate()
shuffled.shuffle()
var sampled = []
for i in range(amt):
sampled.append( shuffled.pop_front() )
return sampled
func shuffleList(list):
var shuffledList =
var indexList = range(list.size())
for i in range(list.size()):
randomize()
var x = randi()%indexList.size()
shuffledList.append(list)
indexList.remove(x)
return shuffledList