Randomizing An Array In GameMaker Studio 2

Randomizing The Array

Arrays in GameMaker Studio are essentially lists of values or objects. You can declare arrays using something like this.
numbers[0] = "One";
numbers[1] = "Two";
numbers[2] = "Three";
numbers[3] = "Four";
numbers[4] = "Five";
The code above declares an array of numbers containing the words "One" through "Five". Now say we wanted to mix those words up for some reason. We could do something like this.

for(count = 0; count < array_length_1d(numbers); count++)
	var i = irandom_range(1, array_length_1d(numbers) - 1);
	var tmp = numbers[i];
	numbers[i] = numbers[0];
	numbers[0] = tmp;

The first line, "randomize();" makes the function "irandom_range" return a truely random number. Otherwise it uses the same seed value and will return the same series of random numbers every time you run this section of code. The for loop says we'll perform 10 times the number of values in the array, or 50 in this case, iterations of our randomization technique. "var i = irandom_range(1, array_length1d(numbers) - 1);" says give us a random number somewhere in the range of 1 to the length of our array, in this case a position between 1 and 5. The next line "var tmp = numbers[i];" places the value at index i in the array inside a temporary placeholder. Then we set numbers[i] = the first value in the array, essentially moving the first value from index 0 to a random point at position i. Then we take the temporary placeholder and assign it to index 0 of the array. After these three steps we've essentially swapped the objects in position 0 and position i. After doing this 50 times we've completed our randomization.