diff --git a/cv5/program.c b/cv5/program.c index e69de29..4055ee5 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -0,0 +1,91 @@ +#include +#include +#include + +#define SIZE 100 + +struct student { + char name[SIZE]; + int votes; +}; + +int find_student(struct student *students, int size, const char *name); +int compare(const void *p1, const void *p2); + +struct student databaza[SIZE]; +int size = 0; + +char line[SIZE]; + +int main() { + memset(databaza, 0, SIZE * sizeof(struct student)); + + while (1) { + memset(line, 0, SIZE); + char *r = fgets(line, SIZE, stdin); + + if (r == NULL) { + break; + } + + int value = strtol(line, NULL, 10); + if (value == 0) { + printf("Zly format vstupu\n"); + return 0; + } + + char name[SIZE]; + memset(name, 0, SIZE); + char *zaciatok_mena = strchr(line, ' ') + 1; + int velkost_mena = strlen(zaciatok_mena) - 1; + + if (velkost_mena > 0) { + memcpy(name, zaciatok_mena, velkost_mena); + name[velkost_mena] = '\0'; + } else { + printf("Nepodarilo sa nacitat meno\n"); + return 0; + } + + int find_student(struct student *students, int size, const char *name) { + for (int i = 0; i < size; ++i) { + if (strcmp(students[i].name, name) == 0) { + return i; + } + } + return -1; + } + + int id = find_student(databaza, size, name); + if (id < 0) { + strcpy(databaza[size].name, name); + databaza[size].votes = value; + size += 1; + } else { + databaza[id].votes += value; + } + } + + qsort(databaza, size, sizeof(struct student), compare); + + printf("Vysledky:\n"); + + for (int i = 0; i < size; ++i) { + printf("%d %s\n", databaza[i].votes, databaza[i].name); + } + + return 0; +} + +int compare(const void *p1, const void *p2) { + struct student *s1 = (struct student *)p1; + struct student *s2 = (struct student *)p2; + + if (s1->votes < s2->votes) { + return 1; + } else if (s1->votes > s2->votes) { + return -1; + } + + return strcmp(s1->name, s2->name); +}