pvjc24/cv5/program.c

62 lines
1.6 KiB
C
Raw Normal View History

2024-03-21 21:01:53 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char *name;
int vote_count;
} student_t;
int compare_students(const void *a, const void *b) {
2024-03-21 21:09:05 +00:00
const student_t *student_a = (const student_t *)a;
const student_t *student_b = (const student_t *)b;
2024-03-21 21:01:53 +00:00
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;
2024-03-21 21:05:17 +00:00
int student_count = 0;
2024-03-21 21:01:53 +00:00
char line[1024];
while (fgets(line, sizeof(line), stdin)) {
int vote_count;
2024-03-21 21:17:41 +00:00
char name[1024];
sscanf(line, "%d %[^\n]", &vote_count, name);
2024-03-21 21:01:53 +00:00
2024-03-21 21:05:17 +00:00
if (student_count >= students_capacity) {
students_capacity = (students_capacity + 1) * 2;
2024-03-21 21:01:53 +00:00
student_t *new_students = realloc(students, students_capacity * sizeof(student_t));
if (new_students == NULL) {
2024-03-21 21:17:41 +00:00
fprintf(stderr, "chyba");
2024-03-21 21:01:53 +00:00
return 1;
}
students = new_students;
}
2024-03-21 21:17:41 +00:00
students[student_count].name = strdup(name);
2024-03-21 21:05:17 +00:00
students[student_count].vote_count = vote_count;
student_count++;
2024-03-21 21:01:53 +00:00
}
2024-03-21 21:05:17 +00:00
qsort(students, student_count, sizeof(student_t), compare_students);
2024-03-21 21:01:53 +00:00
2024-03-21 21:14:45 +00:00
printf("Vysledky:\n");
2024-03-21 21:17:41 +00:00
printf("%d %s\n", students[0].vote_count, students[0].name);
for (int i = 1; i < student_count; i++) {
if (strcmp(students[i].name, students[i - 1].name) != 0) {
printf("%d %s\n", students[i].vote_count, students[i].name);
}
2024-03-21 21:05:17 +00:00
free(students[i].name);
2024-03-21 21:01:53 +00:00
}
2024-03-21 21:05:17 +00:00
free(students);
2024-03-21 21:01:53 +00:00
return 0;
2024-03-21 21:14:45 +00:00
}