diff --git a/du2/program.c b/du2/program.c new file mode 100644 index 0000000..6d6b664 --- /dev/null +++ b/du2/program.c @@ -0,0 +1,59 @@ +#include +#include +#include + +#define MAX_LINE 1024 +#define MAX_STUDENTS 1024 + +typedef struct { + char name[MAX_LINE]; + long votes; +} Student; + +Student students[MAX_STUDENTS]; +int count = 0; + +static int cmp(const void *a, const void *b) { + const Student *sa = (const Student *)a; + const Student *sb = (const Student *)b; + if (sa->votes != sb->votes) + return (sb->votes > sa->votes) ? 1 : -1; + return strcmp(sa->name, sb->name); +} + +int main(void) { + char line[MAX_LINE]; + + while (fgets(line, sizeof(line), stdin)) { + line[strcspn(line, "\n")] = '\0'; + char *end; + long votes = strtol(line, &end, 10); + if (end == line || votes <= 0 || *end != ' ') + break; + + char *name = end + 1; + if (*name == '\0') + break; + + int i; + for (i = 0; i < count; i++) + if (strcmp(students[i].name, name) == 0) + break; + if (i == count) { + memset(&students[count], 0, sizeof(Student)); + memcpy(students[count].name, name, strlen(name) + 1); + count++; + } + students[i].votes += votes; + } + if (count == 0) { + fprintf(stderr, "Chyba: ziaden platny zaznam.\n"); + return 1; + } + qsort(students, count, sizeof(Student), cmp); + + for (int i = 0; i < count; i++) + printf("%ld %s\n", students[i].votes, students[i].name); + + return 0; +} \ No newline at end of file