From bca75f071153ddcaa5ceee0722e2152bacfedc78 Mon Sep 17 00:00:00 2001 From: Comrade Martin Miroslavovich Michalec Date: Sat, 25 Nov 2023 19:24:10 +0300 Subject: publish --- src/main.c | 307 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/multiset.c | 277 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/multiset.h | 36 +++++++ src/utils.c | 47 +++++++++ src/utils.h | 29 ++++++ 5 files changed, 696 insertions(+) create mode 100644 src/main.c create mode 100644 src/multiset.c create mode 100644 src/multiset.h create mode 100644 src/utils.c create mode 100644 src/utils.h (limited to 'src') diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..4a0d36f --- /dev/null +++ b/src/main.c @@ -0,0 +1,307 @@ +/* + * Лабораторная работа №1 + * + * Реализовать программу генерации бинарного кода Грея для заполнения + * универсума (заданной пользователем разрядности). На основе универсума + * формируются два мультимножества двумя способами заполнения: вручную и + * автоматически (выбирает пользователь). Мощность множеств также задает + * пользователь. В результате на экран выводятся результаты всех действий + * над множествами. Кроме того, требуется реализовать защиту от + * некорректного пользовательского ввода. + * + * trie (radix 32 -> 32 indirections + a lot of memory for pointers + a lot of memory + "fast" insert/delete) + * array + binary search (log(32)/log(2) -> max 32 jumps + low amount of memory + "slow" insert/delete) + * + */ + +#include +#include +#include +#include +#include + +#include "utils.h" +#include "multiset.h" + +#define MULTISET_ELEMENT_MAX_COUNT 99 + +uint +bin_to_gray (uint num) +{ + return num ^ (num >> 1); +} + +uint +gray_to_bin (uint num) +{ + num ^= num >> 16; + num ^= num >> 8; + num ^= num >> 4; + num ^= num >> 2; + num ^= num >> 1; + return num; +} + +void +generate_universum (MULTISET u) +{ + for (uint i = 0; i < u->power; ++i) { + u->elements[i].value = i; + u->elements[i].count = (rand () % MULTISET_ELEMENT_MAX_COUNT) + 1; + } +} + +void +generate_random_multiset (MULTISET ms, MULTISET u) +{ + assert (ms); + assert (u); + + uint pd = u->power/ms->power; + for (uint i = 0; i < ms->power; ++i) { + ms->elements[i] = u->elements[i*pd + (rand () % pd)]; + ms->elements[i].count = (rand () % ms->elements[i].count) + 1; + } +} + +void +print_multiset (MULTISET ms, MULTISET u) +{ + assert (u); + + if (!ms || ms->power == 0) { + printf ("Пустое множество!\n"); + return; + } + + for (uint i = 0; i < ms->power; ++i) { + printf ("[%0*d] = %0*b x %*d\n", + log10ui (ms->power) + 1, i, + CTZ (u->power), bin_to_gray (ms->elements[i].value), + log10ui (multiset_element_max_count (u)) + 1, ms->elements[i].count); + } +} + +uint +request_universum_bitdepth_from_user () +{ + uint bitdepth = 0; + + for (;;) { + while (!input ("Задайте разрядность универсума U", "^[[:digit:]]+$", "%u", &bitdepth)) + printf ("Ввод не соответствует регулярному выражению!\n"); + if (bitdepth <= 24) + break; + puts ("Разрядность должна быть <= 24"); + } + + return bitdepth; +} + +uint +request_multiset_power_from_user (const char *name, MULTISET u) +{ + if (!u) return 0; + + uint power = 0; + + for (;;) { + while (!input ("Зададайте мощность мультимножества %s", "^[[:digit:]]+$", "%u", name, &power)) + printf ("Ввод не соответствует регулярному выражению!\n"); + if (0 < power && power <= u->power) + return power; + printf ("Мощность мультимножества должна принадлежать (0; %d]!\n", u->power); + } +} + +MULTISET +request_universum_from_user (void) +{ + MULTISET u; + + for (;;) { + uint bitdepth = request_universum_bitdepth_from_user (); + if (bitdepth == 0) return NULL; + u = init_multiset (1 << bitdepth); + if (u) break; + else puts ("Недостаточно памяти для универсумма данной разрядности!"); + } + + generate_universum (u); + return u; +} + +struct multiset_element +request_multiset_element_from_user (MULTISET ms, MULTISET u, int i) +{ + struct multiset_element mse; + + for (;;) { + input: + char *bstr; + while (!input ("Задайте код Грея %d элемента мультимножества", "^[01]+$", "%ms", + i + 1, &bstr)) + printf ("Ввод не соответствует регулярному выражению!\n"); + mse.value = gray_to_bin (strtoul (bstr, NULL, 2)); + free (bstr); + + if (mse.value > (uint) 1 << u->power) { + printf ("Код Грея должен принадлежать [%0*d; %0*d]!\n", + log10ui (ms->power) + 1, 0, + log10ui (ms->power) + 1, bin_to_gray (ms->power)); + continue; + } + for (int j = 0; j < i; ++j) { + if (ms->elements[j].value == mse.value) { + printf ("Элемент под данным кодом Грея уже в мультимножестве!\n"); + goto input; + } + } + + break; + } + + for (;;) { + while (!input ("Задайте кратность %0*b", "^[[:digit:]]+$", "%d", + CTZ (u->power), bin_to_gray (mse.value), &mse.count)) + printf ("Ввод не соответствует регулярному выражению!\n"); + if (0 < mse.count && mse.count <= u->elements[mse.value].count) + break; + printf ("Введённая кратность должна входить в 1..%d!\n", u->elements[mse.value].count); + } + + return mse; +} + +MULTISET +request_multiset_from_user (const char *name, MULTISET u) +{ + MULTISET ms; + + for (;;) { + uint power = request_multiset_power_from_user (name, u); + ms = init_multiset (power); + if (!ms) return NULL; + // if (!ms) { + // printf ("Недостаточно памяти для мультимножества данной мощности!\n"); + // continue; + // } + + for (;;) { + int a; + while (!input ("Заполнить мультимножество автоматически (1) или вручную (2)", "^[12]$", "%d", &a)) + printf ("Ввод не соответствует регулярному выражению!\n"); + switch (a) { + case 1: + generate_random_multiset (ms, u); + return ms; + case 2: + for (uint i = 0; i < ms->power; ++i) + ms->elements[i] = request_multiset_element_from_user (ms, u, i); + qsort (ms->elements, ms->power, sizeof (struct multiset_element), compare_multiset_elements); + return ms; + default: + printf ("Неверный выбор!\n"); + } + } + } +} + +int +main (void) +{ + srand (time (NULL)); + + MULTISET u = request_universum_from_user (); + print_multiset (u, u); + PAGEBREAK (); + + MULTISET a = request_multiset_from_user ("A", u); + print_multiset (a, u); + PAGEBREAK (); + + MULTISET b = request_multiset_from_user ("B", u); + print_multiset (b, u); + PAGEBREAK (); + + MULTISET c; + + puts ("Объединение A и B:"); + c = multiset_union (a, b); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Пересечение A и B:"); + c = multiset_intersection (a, b); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Дополнение A:"); + c = multiset_complement (a, u); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Дополнение B:"); + c = multiset_complement (b, u); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Разность A\\B:"); + c = multiset_difference (a, b); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Разность B\\A:"); + c = multiset_difference (b, a); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Арифметическое сложение A и B:"); + c = multiset_arithmetic_sum (a, b, u); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Арифметическая разность A - B:"); + c = multiset_arithmetic_difference (a, b); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Арифметическая разность B - A:"); + c = multiset_arithmetic_difference (b, a); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Арифметическое произведение A и B:"); + c = multiset_arithmetic_multiplication (a, b, u); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Арифметическое деление A на B:"); + c = multiset_arithmetic_division (a, b, u); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Арифметическое деление B на A:"); + c = multiset_arithmetic_division (b, a, u); + print_multiset (c, u); + PAGEBREAK (); + free (c); + + puts ("Симетрическая разность A и B:"); + c = multiset_symmetrical_difference (a, b); + print_multiset (c, u); + free (c); + + return EXIT_SUCCESS; +} diff --git a/src/multiset.c b/src/multiset.c new file mode 100644 index 0000000..ca1ea8d --- /dev/null +++ b/src/multiset.c @@ -0,0 +1,277 @@ +#include "multiset.h" +#include + +MULTISET +init_multiset (uint power) +{ + if (!power) return NULL; + + MULTISET ms = malloc (sizeof (struct multiset) + + sizeof (struct multiset_element)*power); + if (!ms) return NULL; + + ms->power = power; + memset (ms->elements, 0, power*sizeof (struct multiset_element)); + + return ms; +} + +int +compare_multiset_elements (const void *lhs, const void *rhs) +{ + if (!lhs && !rhs) return 0; + if (!lhs) return -1; + if (!rhs) return +1; + + uint lhs_value = *((const uint *) lhs); + uint rhs_value = ((const struct multiset_element *) rhs)->value; + + return lhs_value - rhs_value; +} + +uint +multiset_get (MULTISET ms, uint value) +{ + if (!ms) return 0; + + struct multiset_element *mse = bsearch (&value, ms->elements, ms->power, + sizeof (struct multiset_element), + compare_multiset_elements); + return mse ? mse->count : 0; +} + +MULTISET +multiset_set (MULTISET ms, uint value, uint count) +{ + if (!ms) + ms = init_multiset (1); + assert (ms); + + int first = 0; + int last = ms->power - 1; + int middle = (first + last)/2; + while (first <= last) { + if (ms->elements[middle].value < value) + first = middle + 1; + else if (ms->elements[middle].value == value) { + if (count) { + ms->elements[middle].count = count; + } else { + ms->power -= 1; + memmove (&ms->elements[middle], &ms->elements[middle + 1], + sizeof (struct multiset_element)*(ms->power - middle)); + // ms = realloc (ms, (sizeof (struct multiset) + + // sizeof (struct multiset_element)*(ms->power))); + } + break; + } + else last = middle - 1; + + middle = (first + last)/2; + } + if (first > last && count) { + ms = realloc (ms, (sizeof (struct multiset) + + sizeof (struct multiset_element)*(ms->power + 1))); + assert (ms); + memmove (&ms->elements[first + 1], &ms->elements[first], + sizeof (struct multiset_element)*(ms->power - first)); + ms->power += 1; + ms->elements[first].value = value; + ms->elements[first].count = count; + } + return ms; +} + +uint +multiset_element_max_count (MULTISET ms) +{ + if (!ms) return 0; + + uint max_count = 0; + + for (uint i = 0; i < ms->power; ++i) { + uint count_i = ms->elements[i].count; + if (count_i > max_count) + max_count = count_i; + } + + return max_count; +} + +MULTISET +multiset_copy (MULTISET ms) +{ + if (!ms) return NULL; + + size_t size = (sizeof (struct multiset) + + sizeof (struct multiset_element)*ms->power); + MULTISET ms_copy = malloc (size); + assert (ms_copy); + memcpy (ms_copy, ms, size); + return ms_copy; +} + +MULTISET +multiset_union (MULTISET lhs, MULTISET rhs) +{ + if (!lhs && !rhs) return NULL; + if (!lhs) return multiset_copy (rhs); + if (!rhs) return multiset_copy (lhs); + + MULTISET res = multiset_copy (lhs); + + for (uint i = 0; i < rhs->power; ++i) { + struct multiset_element rhse = rhs->elements[i]; + uint rese_count = multiset_get (res, rhse.value); + res = multiset_set (res, rhse.value, MAX (rese_count, rhse.count)); + } + + return res; +} + +MULTISET +multiset_intersection (MULTISET lhs, MULTISET rhs) +{ + if (!lhs || !rhs) return NULL; + + MULTISET res = init_multiset (0); + + for (uint i = 0; i < lhs->power; ++i) { + struct multiset_element lhse = lhs->elements[i]; + uint rhs_count = multiset_get (rhs, lhse.value); + uint count = MIN (lhse.count, rhs_count); + if (count > 0) + res = multiset_set (res, lhse.value, count); + } + + return res; +} + +MULTISET +multiset_complement (MULTISET ms, MULTISET u) +{ + if (!ms) return multiset_copy (u); + + MULTISET res = init_multiset (0); + + for (uint i = 0; i < u->power; ++i) { + struct multiset_element ue = u->elements[i]; + uint mse_count = multiset_get (ms, ue.value); + if (ue.count - mse_count) + res = multiset_set (res, ue.value, ue.count - mse_count); + } + + return res; +} + +MULTISET +multiset_difference (MULTISET lhs, MULTISET rhs) +{ + if (!lhs) return NULL; + if (!rhs) return multiset_copy (lhs); + + MULTISET res = init_multiset (0); + + for (uint i = 0; i < lhs->power; ++i) { + struct multiset_element lhse = lhs->elements[i]; + uint rhs_count = multiset_get (rhs, lhse.value); + if (lhse.count > rhs_count) + res = multiset_set (res, lhse.value, lhse.count - rhs_count); + } + + return res; +} + +MULTISET +multiset_arithmetic_sum (MULTISET lhs, MULTISET rhs, MULTISET u) +{ + if (!lhs && !rhs) return NULL; + if (!lhs) return multiset_copy (rhs); + if (!rhs) return multiset_copy (lhs); + + MULTISET res = multiset_copy (lhs); + + for (uint i = 0; i < rhs->power; ++i) { + struct multiset_element rhse = rhs->elements[i]; + uint rese_count = multiset_get (res, rhse.value); + uint ue_count = multiset_get (u, rhse.value); + res = multiset_set (res, rhse.value, MIN (rese_count + rhse.count, ue_count)); + } + + return res; +} + +MULTISET +multiset_arithmetic_difference (MULTISET lhs, MULTISET rhs) +{ + return multiset_difference (lhs, rhs); +} + +MULTISET +multiset_arithmetic_multiplication (MULTISET lhs, MULTISET rhs, MULTISET u) +{ + if (!lhs || !rhs) return NULL; + + MULTISET res = init_multiset (0); + + for (uint i = 0; i < lhs->power; ++i) { + struct multiset_element lhse = lhs->elements[i]; + uint rhs_count = multiset_get (rhs, lhse.value); + uint ue_count = multiset_get (u, lhse.value); + if (lhse.count && rhs_count) + res = multiset_set (res, lhse.value, MIN (lhse.count * rhs_count, ue_count)); + } + + return res; +} + +MULTISET +multiset_arithmetic_division (MULTISET lhs, MULTISET rhs, MULTISET u) +{ + if (!lhs) return NULL; + if (!rhs) return multiset_copy (lhs); + + MULTISET res = init_multiset (0); + + for (uint i = 0; i < lhs->power; ++i) { + struct multiset_element lhse = lhs->elements[i]; + uint rhs_count = multiset_get (rhs, lhse.value); + uint ue_count = multiset_get (u, lhse.value); + if (!lhse.count) + continue; + if (rhs_count && lhse.count / rhs_count) + res = multiset_set (res, lhse.value, lhse.count / rhs_count); + else + res = multiset_set (res, lhse.value, ue_count); + } + + return res; +} + +MULTISET +multiset_symmetrical_difference (MULTISET lhs, MULTISET rhs) +{ + if (!lhs || !rhs) return NULL; + + MULTISET res = init_multiset (0); + + for (uint i = 0; i < lhs->power; ++i) { + struct multiset_element lhse = lhs->elements[i]; + uint rhs_count = multiset_get (rhs, lhse.value); + if (!rhs_count) + res = multiset_set (res, lhse.value, lhse.count); + else if (rhs_count != lhse.count) + res = multiset_set (res, lhse.value, (lhse.count > rhs_count + ? lhse.count - rhs_count + : rhs_count - lhse.count)); + } + + for (uint i = 0; i < rhs->power; ++i) { + struct multiset_element rhse = rhs->elements[i]; + uint lhs_count = multiset_get (lhs, rhse.value); + if (!lhs_count) + res = multiset_set (res, rhse.value, rhse.count); + } + + return res; +} diff --git a/src/multiset.h b/src/multiset.h new file mode 100644 index 0000000..6e1a8c9 --- /dev/null +++ b/src/multiset.h @@ -0,0 +1,36 @@ +#ifndef MULTISET_H +#define MULTISET_H + +#include +#include +#include "utils.h" + +struct multiset_element +{ + uint value; + uint count; +}; + +typedef struct multiset +{ + uint power; + struct multiset_element elements[0]; +} *MULTISET; + +MULTISET init_multiset (uint power); +int compare_multiset_elements (const void *lhs, const void *rhs); +uint multiset_get (MULTISET ms, uint value); +MULTISET multiset_set (MULTISET ms, uint value, uint count); +uint multiset_element_max_count (MULTISET ms); +MULTISET multiset_copy (MULTISET ms); +MULTISET multiset_union (MULTISET lhs, MULTISET rhs); +MULTISET multiset_intersection (MULTISET lhs, MULTISET rhs); +MULTISET multiset_complement (MULTISET ms, MULTISET u); +MULTISET multiset_difference (MULTISET lhs, MULTISET rhs); +MULTISET multiset_arithmetic_sum (MULTISET lhs, MULTISET rhs, MULTISET u); +MULTISET multiset_arithmetic_difference (MULTISET lhs, MULTISET rhs); +MULTISET multiset_arithmetic_multiplication (MULTISET lhs, MULTISET rhs, MULTISET u); +MULTISET multiset_arithmetic_division (MULTISET lhs, MULTISET rhs, MULTISET u); +MULTISET multiset_symmetrical_difference (MULTISET lhs, MULTISET rhs); + +#endif diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..2218754 --- /dev/null +++ b/src/utils.c @@ -0,0 +1,47 @@ +#include "utils.h" +#include +#include +#include +#include +#include + +int +input (const char *message, const char *regex, const char *template, ...) +{ + char *line = NULL; + size_t line_size = 0; + regex_t compiled; + int matches = 0; + va_list ap; + + va_start (ap, template); + vprintf (message, ap); + printf (" (\"%s\"): ", regex); + getline (&line, &line_size, stdin); + line[strlen (line) - 1] = '\0'; + + regcomp (&compiled, regex, REG_EXTENDED | REG_NOSUB); + if (regexec (&compiled, line, 0, NULL, 0)) + goto defer; + + matches = vsscanf (line, template, ap); + va_end (ap); + + defer: + free (line); + return matches; +} + +uint +log10ui (uint ui) +{ + return ((ui >= 1000000000u) ? 9 : + (ui >= 100000000u) ? 8 : + (ui >= 10000000u) ? 7 : + (ui >= 1000000u) ? 6 : + (ui >= 100000u) ? 5 : + (ui >= 10000u) ? 4 : + (ui >= 1000u) ? 3 : + (ui >= 100u) ? 2 : + (ui >= 10u) ? 1 : 0u); +} diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..99765db --- /dev/null +++ b/src/utils.h @@ -0,0 +1,29 @@ +#ifndef UTILS_H +#define UTILS_H + +#define MAX(a, b) ({ \ + __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a > _b ? _a : _b; \ + }) + +#define MIN(a, b) ({ \ + __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a < _b ? _a : _b; \ + }) + +#define CTZ(X) __builtin_ctz (X) + +#define PAGEBREAK() puts ("\n ") +#define NEWLINE() putchar ('\n'); + +typedef unsigned int uint; + +int +input (const char *message, const char *regex, const char *template, ...); + +uint +log10ui (uint ui); + +#endif -- cgit v1.3.1