c - 如何避免首字母相同的两个句子在随机播放中彼此相邻?

标签 c algorithm

我编写了一段代码,用于随机播放音乐轨道的文本文件,我该如何调整我的代码,以便每次运行该程序时,不会有两首彼此相邻的轨道以相同的第一个字母。例如,艺术家 Hozier 的两首轨道不应放在一起。

正确:

Hozier - Take Me To Church
Pink - So What
Hozier - Cherry Wine

不正确:

Hozier - Take Me To Church
Hozier - Cherry Wine
Pink - So What

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// Accepts: command line input
// Returns: 0 if no error

int main(int num_args, char *arg_strings[])
{
    int x = 0, i, track_count = 0;
    unsigned long Max_Length = 0;
char line[500], *temp;
FILE *file = fopen("InputFiles/playlist.txt", "r" );
/* The next line checks if the playlist file exists and if it's not there, "Cannot Open File" is printed to the screen */
if (file == NULL){
    printf("Cannot open file\n");

}
/* The following code identifies each line in the text and lines are shuffled accordingly */

while (fgets(line, sizeof(line), file) != NULL)
{
    track_count++;
    if (strlen(line) > Max_Length)
        Max_Length = strlen(line);
}
rewind(file);
char *Array[track_count];
while (fgets(line, sizeof(line), file) != NULL)
{
    Array[x] = malloc(strlen(line));
    if (Array[x] == NULL){
        printf("A memory error occurred.\n");
        return(1);
    }
    strcpy(Array[x], line);
    /* change \n to \0 */
            Array[x][strlen(Array[x])-1] = '\0';
            x++;
        }

    printf("The original playlist is:\n");
    for (x = 0; x < track_count; x++)
    printf("%2d %s\n", x, Array[x]);
/*  The array will now be shuffled: */
srand( (unsigned int) time(NULL));
for (x = track_count - 1; x >= 0; x--){
    i = (int) rand() % track_count;
    temp = Array[x];
    Array[x] = Array[i];
    Array[i] = temp;
}
printf("\nShuffled Array\n");
for (x = 0; x < track_count; x++)
    printf("%2d %s\n", x, Array[x]);

return 0;
}

最佳答案

如果允许重复播放同一首歌曲(例如,当音乐播放器同时打开随机播放和重复播放时),您可以只记住前面的第一个字母,然后从没有相同歌曲的歌曲中随机挑选每一首连续的歌曲第一个字母作为上一首歌曲。

但是,为了不重复地随机播放歌曲,仅考虑最后一个位置是行不通的,例如,如果您的歌曲有第一个字母 C A C B C A C,它们最终可能是 A B A C C C C 最后只剩下 C 歌曲。您可以检测到这种情况(即,不以前一个首字母开头的未洗牌歌曲的数量为零),在这种情况下,在先前排序的列表中找到可以插入每首新歌曲的位置,并从中随机选择。例如,如果您有上面的首字母并且位于 A B A C,那么下一首以 C 开头的歌曲可以插入到 3 个不同的位置(C A B A CA C B A CA B C A C)。

关于c - 如何避免首字母相同的两个句子在随机播放中彼此相邻?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35537803/

相关文章:

c - 如何告诉编译器使用 ARM 的硬件浮点指令

c# - 创建序列的幂集

python - 如何分析DAG时间复杂度?

c++ - 我可以在 C++ 中使用 ** vector < pair <int ,vector < int >>> vec** 之类的声明吗?

c - 查找与线路关联的区域

c - 如何从 C 中的 X11 窗口获取 Vulkan 上下文?

python 3。八叉树实现占用大量内存。如何优化?

algorithm - 反向数组中的选择排序比插入排序更快吗?

c++ - Arduino 端口 Bitschft

c - 内存中一次只需要一份动态库?