pvjc24/cv5/program.c

80 lines
2.1 KiB
C
Raw Normal View History

2024-03-13 09:55:11 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-03-20 14:57:31 +00:00
#define SIZE 100
2024-03-20 14:08:46 +00:00
2024-03-20 14:57:31 +00:00
struct student {
char name[SIZE];
int votes;
};
2024-03-13 09:55:11 +00:00
2024-03-20 15:22:08 +00:00
// 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);
}
2024-03-20 14:57:31 +00:00
}
2024-03-20 15:22:08 +00:00
// Funkcia na hladanie studenta v databaze
2024-03-20 14:57:31 +00:00
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) {
2024-03-20 15:22:08 +00:00
return i; // Student najdeny
2024-03-20 13:52:38 +00:00
}
2024-03-13 09:55:11 +00:00
}
2024-03-20 15:22:08 +00:00
return -1; // Student nenajdeny
2024-03-20 14:57:31 +00:00
}
2024-03-20 13:52:38 +00:00
2024-03-20 15:22:08 +00:00
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;
2024-03-13 09:55:11 +00:00
}