Wednesday, November 16, 2011

GameMaker - shuffling an array

In some cases you may want to shuffle contents of array.
Out of those, it may also happen that it can not be easily replaced by ds_list.
The following code can be used to sort an array relatively fast and finely:
var i, j, k;
for (i = 0; i < size; i += 1)
{
    j = irandom_range(i, size - 1)
    if (i != j)
    {
        k = data[i]
        data[i] = data[j]
        data[j] = k
    }
}
Where data is name of array variable, and size is array length (with elements being stored in indexes from 0 to (size - 1)).

1 comment:

Note: Only a member of this blog may post a comment.