How to randomize a List/Array ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By vonflyhighace2
:warning: Old Version Published before Godot 3 was released.

I Have a list of objects that I need randomized. Is there no easier way to accomplish this in Godot but to spin a custom function?

:bust_in_silhouette: Reply From: krnk
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

DarkShroom | 2018-12-01 03:36

:bust_in_silhouette: Reply From: jarlowrey

A void shuffle function will be available for arrays in 3.1 Array — Документація до Godot Engine (4.x) українською мовою

And sampling can be done via

func sample(list,amt):
	var shuffled = list.duplicate()
	shuffled.shuffle()
	var sampled = []
	for i in range(amt):
		sampled.append( shuffled.pop_front() )
	return sampled
:bust_in_silhouette: Reply From: TitanTre3

var array = [1,2,3,4,5,6,7,8]

func _ready():
randomize()
array.shuffle()
print(array)

:bust_in_silhouette: Reply From: marywilliams

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

this will randomize the array