diff --git a/cv5/program.c b/cv5/program.c new file mode 100644 index 0000000..f380ed2 --- /dev/null +++ b/cv5/program.c @@ -0,0 +1,77 @@ +#include +#include +#include + +#define MAX_NAME_LENGTH 100 + +typedef struct { + char name[MAX_NAME_LENGTH]; + int votes; +} Candidate; + +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 number of 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 %99s", &votes, name) != 2) { + if (feof(stdin)) { + break; // End of input + } else { + printf("Error: Failed to read vote.\n"); + return 1; + } + } + + // 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; +} +