random sort

SGDK only sub forum

Moderator: Stef

Post Reply
matteus
Very interested
Posts: 336
Joined: Mon Feb 04, 2008 1:41 pm

random sort

Post by matteus » Mon Sep 12, 2016 5:47 pm

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?

Stef
Very interested
Posts: 3131
Joined: Thu Nov 30, 2006 9:46 pm
Location: France - Sevres
Contact:

Re: random sort

Post by Stef » Mon Sep 12, 2016 7:39 pm

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 :)

Moon-Watcher
Very interested
Posts: 117
Joined: Sun Jan 02, 2011 9:14 pm
Contact:

Re: random sort

Post by Moon-Watcher » Mon Sep 12, 2016 7:51 pm

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

matteus
Very interested
Posts: 336
Joined: Mon Feb 04, 2008 1:41 pm

Re: random sort

Post by matteus » Mon Sep 12, 2016 7:56 pm

Thank you both! :)

Stef
Very interested
Posts: 3131
Joined: Thu Nov 30, 2006 9:46 pm
Location: France - Sevres
Contact:

Re: random sort

Post by Stef » Tue Sep 13, 2016 10:16 am

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

Post Reply