我有一段代碼,我已經編寫了一個混音音軌的文本文件,我如何調整我的代碼,以便每次運行該程序時,都不會有兩個音軌旁邊的音軌開頭第一封信。例如,藝術家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是基本情況。 –