From 56cd8dff34f446da969a207743f98e9b6d28569d Mon Sep 17 00:00:00 2001 From: Weber Date: Thu, 21 Mar 2024 21:01:53 +0000 Subject: [PATCH] skuska --- cv5/program.c | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/cv5/program.c b/cv5/program.c index e69de29..8e10af4 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -0,0 +1,58 @@ +#include +#include +#include + +typedef struct student { + char *name; + int vote_count; +} student_t; + +int compare_students(const void *a, const void *b) { + const student_t *student_a = a; + const student_t *student_b = b; + + if (student_a->vote_count > student_b->vote_count) { + return -1; + } else if (student_a->vote_count < student_b->vote_count) { + return 1; + } + + return strcmp(student_a->name, student_b->name); +} + +int main() { + student_t *students = NULL; + int students_capacity = 0; + + char line[1024]; + while (fgets(line, sizeof(line), stdin)) { + int vote_count; + char *name; + sscanf(line, "%d %ms", &vote_count, &name); + + if (students_capacity <= vote_count) { + students_capacity *= 2; + student_t *new_students = realloc(students, students_capacity * sizeof(student_t)); + if (new_students == NULL) { + fprintf(stderr, "Error: Memory reallocation failed\n"); + return 1; + } + students = new_students; + } + + students[vote_count].name = name; + students[vote_count].vote_count++; + } + + qsort(students, students_capacity, sizeof(student_t), compare_students); + + printf("Results:\n"); + for (int i = 0; i < students_capacity; i++) { + if (students[i].vote_count > 0) { + printf("%d %s\n", students[i].vote_count, students[i].name); + students[i].name = NULL; + } + } + + return 0; +} \ No newline at end of file