我有一段代码,我已经编写了一个混音音轨的文本文件,我如何调整我的代码,以便每次运行该程序时,都不会有两个音轨旁边的音轨开头第一封信。例如,艺术家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;
}
注:'阵列[X] = malloc的(strlen的(线));'应'阵列[X] = malloc的(strlen的(线)+ 1);' –
你认识到,它可能不总是有可能这样做(至少不重复一些曲目)?你打算在这种情况下做什么? –
确实存在这种洗牌的充分必要条件是,字母的任何字母都不会超过'ceiling(n/2)'次数(其中'n'是不同轨道的数量)。必要性是显而易见的,充分性可以通过对不同字母的数量进行归纳来证明,其中n = 2是基本情况。 –