diff --git a/du4/program.c b/du4/program.c new file mode 100644 index 0000000..92e602e --- /dev/null +++ b/du4/program.c @@ -0,0 +1,75 @@ +#include +#include +#include + +#define MAX_NAME 100 +#define MAX_ENTRIES 100 + +typedef struct { + char *name; + int votes; +} Student; + +Student *students[MAX_ENTRIES]; +int student_count = 0; + +Student *find_or_add(const char *name) { + for (int i = 0; i < student_count; i++) { + if (strcmp(students[i]->name, name) == 0) { + return students[i]; + } + } + if (student_count < MAX_ENTRIES) { + Student *new_student = (Student *)malloc(sizeof(Student)); + new_student->name = strdup(name); + new_student->votes = 0; + students[student_count++] = new_student; + return new_student; + } + return NULL; +} + +int compare(const void *a, const void *b) { + Student *s1 = *(Student **)a; + Student *s2 = *(Student **)b; + return (s2->votes != s1->votes) ? (s2->votes - s1->votes) : strcmp(s1->name, s2->name); +} + +void free_memory() { + for (int i = 0; i < student_count; i++) { + free(students[i]->name); + free(students[i]); + } +} + +int main() { + char line[MAX_NAME + 10]; + int votes; + char name[MAX_NAME]; + int has_data = 0; + + while (fgets(line, sizeof(line), stdin)) { + if (sscanf(line, "%d %99[^"]", &votes, name) != 2 || votes < 0) { + break; + } + Student *student = find_or_add(name); + if (student) student->votes += votes; + has_data = 1; + } + + if (!has_data) { + printf("Chyba: Nebol zadany platny vstup.\n"); + return 1; + } + + qsort(students, student_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); + } + + free_memory(); + return 0; +} +