Page 1 of 1

random sort

Posted: Mon Sep 12, 2016 5:47 pm
by matteus
I've an array of numbers 1 to 20 and i'd like to randomly sort them :) What's the best sort to use with the SGDK?

Re: random sort

Posted: Mon Sep 12, 2016 7:39 pm
by Stef
There is no "random sort" feature in SGDK but you can use that kind of algo:

Code: Select all

array[20] = {0, 1, 2, ..., 19}
remaining = 20
outInd = 0
while (remaining > 0)
{
  int index = random() % remaining;
  value = array[index];
  yourArray[outInd++] = value;
  remaining--;
  array[index] = array[remaining];
}
not really straightforward but at least it works :)

Re: random sort

Posted: Mon Sep 12, 2016 7:51 pm
by Moon-Watcher
ShuffleVector_u8(...) https://github.com/moon-watcher/BugHunt ... chos.c#L78

Code: Select all

static void ShuffleVector_u8(u8 *array, u32 n)
{
    u32 i;

    for (i = 0; i < n ; i++)        /* RECORREMOS UNO A UNO EL VECTOR... */
    {
        u32 j = random() % n;       /* ... Y LO INTERCAMBIAMOS CON OTRO ÍNDICE AL AZAR */
        SWAP( array[i], array[j] );
    }
}
By Jack Nolddor

Re: random sort

Posted: Mon Sep 12, 2016 7:56 pm
by matteus
Thank you both! :)

Re: random sort

Posted: Tue Sep 13, 2016 10:16 am
by Stef
Haha the algo from Moon is much more simple, i suggest you to use it ;) Crazy that i even didn't think about just shuffling the array :p