diff --git a/du4/program.c b/du4/program.c new file mode 100644 index 0000000..e3f3810 --- /dev/null +++ b/du4/program.c @@ -0,0 +1,74 @@ +#include +#include +#include + +#define MAX_STUDENTS 100 +#define MAX_NAME_LEN 100 +#define MAX_LINE_LEN 150 + +typedef struct{ + char name[MAX_NAME_LEN]; + int votes; +} Student; + +int findStudent(Student students[], int count, const 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(studentB->votes != studentA->votes){ + return studentB->votes - studentA->votes; + } + return strcmp(studentA->name, studentB->name); +} + +int main(){ + Student students[MAX_STUDENTS]; + int student_count = 0; + char line[MAX_LINE_LEN]; + + int read_success = 0; + + while(fgets(line, sizeof(line), stdin)){ + int count; + char name[MAX_NAME_LEN]; + + if(sscanf(line, "%d %[^\n]", &count, name) != 2 || count < 0){ + break; + } + read_success = 1; + + int index = findStudent(students, student_count, name); + if(index != -1){ + students[index].votes += count; + }else{ + if(student_count < MAX_STUDENTS){ + strcpy(students[student_count].name, name); + students[student_count].votes = count; + student_count++; + } + } + } + + if (!read_success) { + printf("Chyba: Nepodarilo sa nacitat ziadne platne zaznamy.\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); + } + + return 0; +}