如何将Fisher-Yates应用于C程序?

时间:2016-02-19 10:52:15

标签: c algorithm

到目前为止,我已经尝试了很多东西,但还没有能够将Fisher-Yates算法作为一种混洗算法。我无法将其应用到我的代码中。

我按照字母顺序对播放列表进行排序,但现在我需要将其播放。这就是我失去的地方。下面是我的代码和播放列表文本文件。我还附上了代码和文本文件的图像。非常感谢帮助,谢谢。这都是使用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文件

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

0 个答案:

没有答案