pvjc24/cv5/program.c
2024-03-20 16:22:08 +01:00

80 lines
2.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct student {
char name[SIZE];
int votes;
};
// Funkcia pre porovnanie dvoch študentov
int compare(const void *p1, const void *p2) {
const struct student *s1 = (const struct student *)p1;
const struct student *s2 = (const struct student *)p2;
// Porovnanie počtu hlasov
if (s1->votes != s2->votes) {
return s2->votes - s1->votes; // Zoradenie zostupne podla poctu hlasov
} else {
// Ak maju rovnaky pocet hlasov, zoradime lexikograficky podla mena
return strcmp(s1->name, s2->name);
}
}
// Funkcia na hladanie studenta v databaze
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; // Student najdeny
}
}
return -1; // Student nenajdeny
}
int main() {
struct student database[SIZE];
memset(database, 0, SIZE * sizeof(struct student));
int size = 0;
char line[SIZE];
while (fgets(line, SIZE, stdin) != NULL) {
int votes;
char name[SIZE];
// Nacitanie hlasov a mena
if (sscanf(line, "%d %[^\n]", &votes, name) != 2) {
fprintf(stderr, "Chyba pri citani riadku: %s", line);
return 1;
}
// Hladanie studenta v databaze
int idx = find_student(database, size, name);
if (idx == -1) {
// Student nie je v databaze, pridame ho
if (size >= SIZE) {
fprintf(stderr, "Prekroceny limit databazy\n");
return 1;
}
strcpy(database[size].name, name);
database[size].votes = votes;
size++;
} else {
// Student je v databaze, pripocitame hlasy
database[idx].votes += votes;
}
}
// Zoradenie databazy
qsort(database, size, sizeof(struct student), compare);
// Vypis databazy
for (int i = 0; i < size; i++) {
printf("%d %s\n", database[i].votes, database[i].name);
}
return 0;
}