How to shuffle an array?

All topics about ZGameEditor goes here.

Moderator: Moderators

Post Reply
User avatar
Ats
Posts: 603
Joined: Fri Sep 28, 2012 10:05 am
Contact:

How to shuffle an array?

Post 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
User avatar
Rado1
Posts: 775
Joined: Wed May 05, 2010 12:16 pm

Re: How to shuffle an array?

Post 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]));
User avatar
Ats
Posts: 603
Joined: Fri Sep 28, 2012 10:05 am
Contact:

Re: How to shuffle an array?

Post 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/
Post Reply