I have tried a lot of things so far but havent been able to get the Fisher-Yates algorithm working as a shuffle algorithm. I'm having trouble applying it to my code.
I got the playlist to sort in alphabetical order but now I need to get it to shuffle. This is where I'm lost. Below is my code and the playlist text file. I have also attached images of the code and text file. Help would be greatly appreciated thank you. This is all done using eclipse. code
code.png
CODE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void)
{
int s, i;
const char *SHUFFLE_PLAYLISTS_FILE_PATH = "./InputFiles/playlist.txt"; // location of playlist file
char SongArr[100][100], temp[100]; // stores song data (limited to nine rows)
int songNum = 0;
FILE *fp = fopen(SHUFFLE_PLAYLISTS_FILE_PATH, "r+" ); /* open for reading */
// This will take each row in the file and store it in SongArr.
if (fp == NULL )
{ /* check does playlist file exist etc */
perror ("Error opening playlist file");
songNum = -1; /* use this as a file not found code */
}
else
{
// fgets returns NULL when it gets to the end of the file
while ( fgets( SongArr[songNum], sizeof(SongArr[songNum]), fp ) != NULL )
{
songNum++;
}
fclose (fp);
}
for(s = 0; s <= songNum; s++)
{
for (i = s+1; i <= songNum; i++)
{
if(strcmp(SongArr[s], SongArr[i])>0)
{
strcpy(temp, SongArr[s]);
strcpy(SongArr[s], SongArr[i]);
strcpy(SongArr[i], temp);
}
}
}
//Prints the result of sorted songs
printf("Order of Sorted Strings: \n");
for(s = 0; s <= songNum; s++)
{
printf("%s\n", SongArr[s]);
}
void shuffle(int *SongArr, int n)
{
srand(time(NULL));
int temp;
for(s = n - 1; s > 0; s--)
{
i = rand() % (i +1);
temp = SongArr[i];
SongArr[i] = SongArr[s];
SongArr[s] = temp;
}
}
return 0;
}
playlist.txt file
Taylor Swift - Everything Has Changed
Mumford and Sons - Little Lion Man
Hozier - Sedated
Mumford and Sons - Babel
Taylor Swift - I Knew You Were Trouble
Taylor Swift - We Are Never Ever Getting Back Together
Hozier - Jackie and Wilson
Hozier - Take Me To Church
Hozier - Angel of Small Death & The Codeine Scene