Page 1 of 1

How to shuffle an array?

Posted: Sat Jan 09, 2016 10:07 am
by Ats
Hi,

I'm trying to shuffle the numbers inside an array. But as there is no splice method, I don't find an efficient way to do that without having to call random a lot of times. How would you do that in ZGE?

Thanks

Re: How to shuffle an array?

Posted: Sat Jan 09, 2016 10:20 am
by Rado1
A simple algorithm (O(n)):

Code: Select all

int[20] array;
int i, j, k;

// init array
for(i = 0; i < 20; ++i)
  array[i] = i;

// shuffle (Knuth shuffle)
for(i = 0; i < 20; ++i){
  j = rnd() * i;
  k = array[i];
  array[i] = array[j];
  array[j] = k;
}

// show result
for(i = 0; i < 20; ++i)
  trace(intToStr(i) + ": " + intToStr(array[i]));

Re: How to shuffle an array?

Posted: Sat Jan 09, 2016 10:57 am
by Ats
Thanks fof giving the name of the method ;)
Thanks to that, I found a cool website with methods for everything in a lot of programming languages: http://rosettacode.org/