“program”

This commit is contained in:
Vasylenko 2024-04-17 23:09:04 +02:00
commit 1f8430869e

97
cv10/program.c Normal file
View File

@ -0,0 +1,97 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}