pvjc24/cv5/program.c
2024-03-13 11:10:55 +01:00

89 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
// Structure to hold candidate information
typedef struct {
char name[MAX_NAME_LENGTH];
int votes;
} Candidate;
// Comparator function for qsort
int compare_candidates(const void *a, const void *b) {
const Candidate *candidate_a = (const Candidate *)a;
const Candidate *candidate_b = (const Candidate *)b;
// Sort by total votes in descending order
if (candidate_a->votes != candidate_b->votes) {
return candidate_b->votes - candidate_a->votes;
} else {
// If votes are tied, sort lexicographically by name
return strcmp(candidate_a->name, candidate_b->name);
}
}
int main() {
Candidate candidates[100]; // Assuming no more than 100 candidates
int num_candidates = 0;
// Read votes from standard input
while (1) {
int votes;
char name[MAX_NAME_LENGTH];
// Try to read votes and name
if (scanf("%d ", &votes) != 1) {
if (feof(stdin)) {
break; // End of input
} else {
printf("Error: Failed to read vote.\n");
return 1;
}
}
// Read candidate name
if (fgets(name, MAX_NAME_LENGTH, stdin) == NULL) {
printf("Error: Failed to read candidate name.\n");
return 1;
}
// Remove trailing newline character
name[strcspn(name, "\n")] = '\0';
// Check if the candidate already exists
int found = 0;
for (int i = 0; i < num_candidates; i++) {
if (strcmp(candidates[i].name, name) == 0) {
candidates[i].votes += votes;
found = 1;
break;
}
}
// If the candidate is not found, add a new candidate
if (!found) {
if (num_candidates >= 100) {
printf("Error: Too many candidates.\n");
return 1;
}
strcpy(candidates[num_candidates].name, name);
candidates[num_candidates].votes = votes;
num_candidates++;
}
}
// Sort the candidates
qsort(candidates, num_candidates, sizeof(Candidate), compare_candidates);
// Print the outcome
printf("Outcome:\n");
for (int i = 0; i < num_candidates; i++) {
printf("%d %s\n", candidates[i].votes, candidates[i].name);
}
return 0;
}