diff --git a/du4/program.c b/du4/program.c index 7efe6ac..99f09a2 100644 --- a/du4/program.c +++ b/du4/program.c @@ -1,63 +1,75 @@ #include #include #include +#include -#define MAX_NAME_LENGTH 100 +#define namemax 100 +#define maxstudents 1000 typedef struct { - char name[MAX_NAME_LENGTH]; - int votes; + char name[namemax]; + int golosa; } Student; -int compare_students(const void *a, const void *b) { - const Student *studentA = (const Student *)a; - const Student *studentB = (const Student *)b; - - if (studentA->votes != studentB->votes) { - return studentB->votes - studentA->votes; - } else { - return strcmp(studentA->name, studentB->name); +int find_student(Student students[], int count, char *name) { + for (int i = 0; i < count; i++) { + if (strcmp(students[i].name, name) == 0) { + return i; + } } + return -1; +} + +int compare(const void *a, const void *b) { + Student *studentA = (Student *)a; + Student *studentB = (Student *)b; + + if (studentA->golosa != studentB->golosa) { + return studentB->golosa - studentA->golosa; + } + return strcmp(studentA->name, studentB->name); } int main() { - Student students[100]; - int student_count = 0; - char line[256]; + Student students[maxstudents]; + int count = 0; + char buffer[200]; - while (fgets(line, sizeof(line), stdin)) { - int votes; - char name[MAX_NAME_LENGTH]; + while (fgets(buffer, sizeof(buffer), stdin)) { + buffer[strcspn(buffer, "\n")] = '\0'; - if (sscanf(line, "%d %[^\n]", &votes, name) != 2) { - break; - - - int found = 0; - for (int i = 0; i < student_count; i++) { - if (strcmp(students[i].name, name) == 0) { - students[i].votes += votes; - found = 1; - break; - } + if (strlen(buffer) == 0) { + break; } - - + int golosa; + char name[namemax]; + + if (sscanf(buffer, "%d %99[^\n]", &golosa, name) != 2 || golosa <= 0) { + printf("Chyba: Nepodarilo sa nacitat ziadny zaznam.\n"); + return 0; + } + + int index = find_student(students, count, name); + + if (index != -1) { + students[index].golosa += golosa; + } else { + strcpy(students[count].name, name); + students[count].golosa = golosa; + count++; + } } - if (student_count == 0) { - printf("Chyba: nepodarilo sa nacitat ziadny zaznam.\n"); - return 1; + if (count == 0) { + printf("Chyba: Nepodarilo sa nacitat ziadny zaznam.\n"); + return 0; } - - qsort(students, student_count, sizeof(Student), compare_students); + qsort(students, count, sizeof(Student), compare); - - printf("Vysledky:\n"); - for (int i = 0; i < student_count; i++) { - printf("%d %s\n", students[i].votes, students[i].name); + for (int i = 0; i < count; i++) { + printf("%s %d\n", students[i].name, students[i].golosa); } return 0; diff --git a/du4/program.exe b/du4/program.exe index 6ac905f..3e45f12 100644 Binary files a/du4/program.exe and b/du4/program.exe differ