From 1f8430869ed9cde84efa763761a7fad4ac860c39 Mon Sep 17 00:00:00 2001 From: Vasylenko Date: Wed, 17 Apr 2024 23:09:04 +0200 Subject: [PATCH] =?UTF-8?q?=E2=80=9Cprogram=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cv10/program.c | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 cv10/program.c diff --git a/cv10/program.c b/cv10/program.c new file mode 100644 index 0000000..a9d0295 --- /dev/null +++ b/cv10/program.c @@ -0,0 +1,97 @@ +#include +#include +#include + +int compare_strings(const void *a, const void *b) { + const char *str1 = *(const char **)a; + const char *str2 = *(const char **)b; + return strcmp(str1, str2); +} + +int main() { + int max_students, read; + char buffer[101]; + char **names = NULL; + size_t count = 0; + size_t capacity = 0; + + + if (scanf("%d", &max_students) != 1 || max_students <= 0) { + puts("Nespravny vstup"); + return 1; + } + + + while (fgets(buffer, sizeof(buffer), stdin)) { + + buffer[strcspn(buffer, "\n")] = 0; + if (strlen(buffer) == 0) break; + + + if (count == capacity) { + capacity = capacity == 0 ? 16 : capacity * 2; + char **new_names = realloc(names, capacity * sizeof(char *)); + if (!new_names) { + puts("Memory allocation failed"); + free(names); + return 1; + } + names = new_names; + } + + + names[count] = strdup(buffer); + if (!names[count]) { + puts("Memory allocation failed"); + while (count > 0) free(names[--count]); + free(names); + return 1; + } + count++; + } + + if (count == 0) { + puts("Ziadne prihlasky"); + free(names); + return 1; + } + + + qsort(names, count, sizeof(char *), compare_strings); + + + size_t unique_count = 0; + for (size_t i = 0; i < count; i++) { + if (unique_count == 0 || strcmp(names[unique_count - 1], names[i]) != 0) { + names[unique_count++] = names[i]; + } else { + free(names[i]); + } + } + + + puts("Prijati studenti:"); + size_t limit = max_students < unique_count ? max_students : unique_count; + for (size_t i = 0; i < limit; i++) { + puts(names[i]); + } + + + if (limit < unique_count) { + puts("Neprijati studenti:"); + for (size_t i = limit; i < unique_count; i++) { + puts(names[i]); + free(names[i]); + } + } + + + for (size_t i = 0; i < limit; i++) { + free(names[i]); + } + + + free(names); + return 0; +} +