Using Fisher-Yates Shuffle For Array

I’ve got an array that I need to shuffle, but I need the results to be deterministic based on a seeded PRNG. I’m attempting to use the following code which I found at

I’ve replaced “Math.random()” with “myrng()” and my array is called “aDev”. The array contains a list of functions that are called in Draw.

function shuffle(aDev) {
  var m = aDev.length, t, i;
  while (m) {
    i = Math.floor(myrng() * m--);
    t = aDev[m];
    aDev[m] = aDev[i];
    aDev[i] = t;
  return aDev;

My question is where do I put this function? Do I place it inside Setup, after creating the array, or outside of Setup and then call it inside Draw before the functions in the array are called?


I presume it is linked to your previous question randomizing ellipses position and background color.

That function should be outside setup() and draw() since you can call it anytime and anywhere you want (that’s the point of using a function: not coding 5 times the same thing).

Then, you need to call it in your setup() function since you want to randomize your ellipses only once, at the start of the program.

Another thing to note: if you really want your function to be deterministic (i.e. it always return the same shuffle when given a seed) it is better to use a new random object inside the function (or at least resetting the seed in the begining of your function). The reason is that if you use myrng() outside of the function before shuffling and for some reason some times it runs a different number of times, then you won’t get the same shuffle.

For example imagine you have something like this:

void setup() {
  aDev = { ... };

  for (int i = 0; i < hour(); i++) {
    int rnd = myrng();


In that case, even if you give a at the begining of setup(), since the rng will provide 1 to 24 different numbers depending on the time of the day, the shuffle function won’t always give the same result.

Thanks. Still not shuffling for me but I’ll keep working on it.

So, am I calling it correctly as shown here, right after the array is created?

(inside Setup)

aDev = [aDev1, aDev2, aDev3, aDev4, aDev5, aDev6, aDev7, aDev8, aDev9, aDev10, aDev11, aDev12, aDev13, aDev14, aDev15, aDev16, aDev17, aDev18, aDev19, aDev20, aDev21, aDev22, aDev23];


And then I’m calling it inside Draw as follows: (gStart is the array that contains the coordinates to translate to)

function draw() {



Can you provide a link to the full project?

Thank you so much for responding and for all your help. When I copied the code into the p5js editor it gave me a diagnostic to change the name of the shuffle function and that solved it! :grinning:

1 Like