3

I'm trying to make a shuffling array function in GML. Here's what I tried, with argument0 being the array to shuffle and argument1 being the size of this array:

///Shuffling array function

//argument0: the array to shuffle
//argument1: the size of the array

var i;
var j;

show_debug_message("----------");
show_debug_message("Original array: ");
show_debug_message(argument0);
show_debug_message("Size: ");
show_debug_message(argument1);

for (i = 0; i < argument1; i++)
{
    j = irandom_range(i, argument1 - 1);

    if (i != j)
    {
        k = argument0[i];
        argument0[i] = argument0[j];
        argument0[j] = k;
    }
}

show_debug_message("Result array: ");
show_debug_message(argument0);
show_debug_message("----------");

return argument0;

When I execute this function, I alway got the same result:

----------
Original array: 
{ { 1,2,3,4,5 },  }
Size: 
5
Result array: 
{ { 5,3,1,4,2 },  }
----------
Rob
  • 4,927
  • 4
  • 26
  • 41
  • Have you tried it with a larger array to confirm this? It has a limited number of elements to shuffle, but there's a small chance you're getting the same ones over and over randomly. Or you could call the shuffle multiple times. – Jeremy Jackson Feb 08 '17 at 18:56

1 Answers1

2

Have you used the function randomize() anywhere in your game? Randomize will set the seed to a random value each time your game is run — without it, random functions will always return the same result because they're always working with the same seed value.

NOTE: [Random functions] will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.

Documentation on randomize(): https://docs.yoyogames.com/source/dadiospice/002_reference/maths/real%20valued%20functions/randomize.html

Fagan
  • 111
  • 4