samedi 28 janvier 2017

How to shuffle arrays in C?

I'm trying to make a function that will shuffle a playlist but can't figure out how to do it. Been looking at other posts but I can't find anything that helps me solve my problem (in a way that I understand).

This is the function i need help with:

void shuffle(Array *a){
Array temp;

temp.array = (Song *)malloc(sizeof(Song)*a->used);

srand((unsigned int)time(NULL));

if(a->used > 1)
{
    for (int i = 0; i < a->used; i++)
    {
        unsigned int j = rand() % (a->used); //????
        //size_t j = rand() % i;
        temp.array[i] = a->array[j];
        a->array[i] = a->array[j];
        a->array[j] = temp.array[i];
    }
}

freeArray(temp.array);
*a = temp;}

The structs I'm using:

typedef struct song {
char artist[SIZE];
char title[SIZE];
char year[SIZE];} Song;

typedef struct array{
Song *array;
size_t used;
size_t size;} Array;

I want to be able to print out a shuffled list with this function:

(I already have a function that adds each title/year/artist to a->array[i].xxxx)

void printSong(Array *a){
for (size_t i = 0; i < a->used; i++)
{
    printf(
        "\n-----------SONG %d-----------\nSong Title: %sBand/Singer: %sYear: %s",
        i+1,
        a->array[i].title,
        a->array[i].artist,
        a->array[i].year);
}}




Aucun commentaire:

Enregistrer un commentaire