From f151b796a66adfb1d6b7bf151f2d85fd78cc0a64 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 07:42:12 +0300 Subject: publish --- .envrc | 18 + .gitignore | 6 + README.org | 152 ++++++ UNLICENSE | 24 + build.sh | 10 + channels-lock.scm | 21 + doc/gost/gost-7-32-bibliography.sty | 57 ++ doc/gost/gost-7-32-captions.sty | 28 + doc/gost/gost-7-32-counters.sty | 37 ++ doc/gost/gost-7-32-headings.sty | 98 ++++ doc/gost/gost-7-32-lists.sty | 15 + doc/gost/gost-7-32-tables.sty | 29 + doc/gost/gost-7-32-toc.sty | 34 ++ doc/gost/gost-7-32.cls | 62 +++ doc/ox-init.el | 32 ++ doc/report.org | 1024 +++++++++++++++++++++++++++++++++++ doc/setup.org | 43 ++ doc/spbstu-report.cls | 73 +++ manifest.scm | 52 ++ src/dictionary.c | 234 ++++++++ src/dynamic-array.h | 56 ++ src/hash-table.c | 150 +++++ src/hash-table.h | 18 + src/red-black-tree.c | 443 +++++++++++++++ src/red-black-tree.h | 17 + src/utils.h | 21 + 26 files changed, 2754 insertions(+) create mode 100644 .envrc create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 build.sh create mode 100644 channels-lock.scm create mode 100644 doc/gost/gost-7-32-bibliography.sty create mode 100644 doc/gost/gost-7-32-captions.sty create mode 100644 doc/gost/gost-7-32-counters.sty create mode 100644 doc/gost/gost-7-32-headings.sty create mode 100644 doc/gost/gost-7-32-lists.sty create mode 100644 doc/gost/gost-7-32-tables.sty create mode 100644 doc/gost/gost-7-32-toc.sty create mode 100644 doc/gost/gost-7-32.cls create mode 100644 doc/ox-init.el create mode 100644 doc/report.org create mode 100644 doc/setup.org create mode 100644 doc/spbstu-report.cls create mode 100644 manifest.scm create mode 100644 src/dictionary.c create mode 100644 src/dynamic-array.h create mode 100644 src/hash-table.c create mode 100644 src/hash-table.h create mode 100644 src/red-black-tree.c create mode 100644 src/red-black-tree.h create mode 100644 src/utils.h diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..5e9e6bf --- /dev/null +++ b/.envrc @@ -0,0 +1,18 @@ +CHANNELS=./channels-lock.scm +MANIFEST=./manifest.scm +LOAD_PATH=./lib +ROOT=./.guix-shell + +TIME_MACHINE_FLAGS+=" --channels=$CHANNELS" +SHELL_FLAGS+=" --manifest=$MANIFEST" +SHELL_FLAGS+=" --search-paths" +SHELL_FLAGS+=" --root=$ROOT" +SHELL_FLAGS+=" --load-path=$LOAD_PATH" + +use_guix_shell() { + test -d "$ROOT" && unlink "$ROOT" + eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")" +} + +use guix_shell +export TEXINPUTS=${TEXINPUTS}:./:./gost/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c3a21e0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.pdf +*.html +*.png +*.dot +/dictionary +/dictionary.txt diff --git a/README.org b/README.org new file mode 100644 index 0000000..64b46ec --- /dev/null +++ b/README.org @@ -0,0 +1,152 @@ +#+title: Implementation of a dictionary based on hash tables and red‑black trees + +* Task[fn:1] +1. Implement a data structure -- a hash table, which is characterized + by the following operations: insertion, deletion, and search. + Based on it, implement an application -- a dictionary. As a hash + function, you can choose an arbitrary function, for example, taking + the first letter of the word. Add The function for completely + clearing the dictionary and loading/updating the dictionary from a + text file. +2. For the selected text in Russian, build a dictionary based on + red‑black trees. Implement functions for adding, deleting, and + searching for a word. (use of ready‑made data structures is + PROHIBITED!!!). Add a function for completely clearing the + dictionary and loading/updating the dictionary from a text file. + +The additional implementation also includes the possibility of +optimizing the dictionary (for example, searching for potential +cognates in different forms; the simplest criterion is 2/3 of the word +length). The choice of words to be kept in the dictionary is up to the +user. It is not allowed to use ready‑made solutions from the STL +library. + +* Documentation +The exported report can be found at [[https://git.michalec.dev/uni/term-04/graph-theory/lab-06/report.pdf][this link]]. + +* Showcase +*Start of the program and the menu:* +#+begin_example +HASH-TABLE:......FILE LOADED (159 ENTRIES) +RED-BLACK-TREE:..FILE LOADED (159 ENTRIES) + +SELECT: + [00] GENERAL:.........EXIT + [01] HASH-TABLE:......PRINT + [02] HASH-TABLE:......INSERT + [03] HASH-TABLE:......DELETE + [04] HASH-TABLE:......SEARCH + [05] HASH-TABLE:......CLEAR + [06] HASH-TABLE:......LOAD_FROM_FILE + [07] RED-BLACK-TREE:..PRINT + [08] RED-BLACK-TREE:..INSERT + [09] RED-BLACK-TREE:..DELETE + [10] RED-BLACK-TREE:..SEARCH + [11] RED-BLACK-TREE:..CLEAR + [12] RED-BLACK-TREE:..LOAD_FROM_FILE +> +#+end_example + +*Example output of the PRINT menu items*: +#+attr_html: :width 400em +[[https://git.michalec.dev/uni/term-04/graph-theory/lab-06/example-hash-table.png]] + +#+attr_html: :width 400em +[[https://git.michalec.dev/uni/term-04/graph-theory/lab-06/example-red-black-tree.png]] + +*Example session:* (menu replaced with # comments) + #+begin_src text +> asdf +> -1 +> 13 +> +> 04 # (HASH-TABLE) SEARCH +WORD: словарь +ENTRY FOUND +> 10 # (RED-BLACK-TREE) SEARCH +WORD: словарь +ENTRY FOUND +> +> 04 # (HASH-TABLE) SEARCH +WORD: тест +ENTRY NOT FOUND +> 10 # (RED-BLACK-TREE) SEARCH +WORD: тест +ENTRY NOT FOUND +> 06 # (HASH-TABLE) LOAD_FROM_FILE +FILENAME: text +FILE LOADED (30 ENTRIES) +> 12 # (RED-BLACK-TREE) LOAD_FROM_FILE +FILENAME: text +FILE LOADED (30 ENTRIES) +> 04 # (HASH-TABLE) SEARCH +WORD: тест +ENTRY FOUND +> 10 # (RED-BLACK-TREE) SEARCH +WORD: тест +ENTRY FOUND +> +> 02 # (HASH-TABLE) INSERT +WORD: слово +ENTRY INSERTED +> 04 # (HASH-TABLE) SEARCH +WORD: слово +ENTRY FOUND +> 03 # (HASH-TABLE) DELETE +WORD: слово +ENTRY DELETED +> 04 # (HASH-TABLE) SEARCH +WORD: слово +ENTRY NOT FOUND +> 05 # (HASH-TABLE) CLEAR +HASH TABLE CLEARED +> 04 # (HASH-TABLE) SEARCH +WORD: тест +ENTRY NOT FOUND +> +> 08 # (RED-BLACK-TREE) INSERT +WORD: слово +ENTRY INSERTED +> 10 # (RED-BLACK-TREE) SEARCH +WORD: слово +ENTRY FOUND +> 09 # (RED-BLACK-TREE) DELETE +WORD: слово +ENTRY DELETED +> 10 # (RED-BLACK-TREE) SEARCH +WORD: слово +ENTRY NOT FOUND +> 11 # (RED-BLACK-TREE) CLEAR +HASH TABLE CLEARED +> 10 # (RED-BLACK-TREE) SEARCH +WORD: тест +ENTRY NOT FOUND +> 00 # (GENERAL) EXIT +#+end_src + +* Unlicense +#+include: UNLICENSE verse + +* Footnotes +[fn:1] Original text: +#+HTML: +#+begin_quote +1. Реализовать структуру данных -- хеш-таблицу, для которой характерны + операции: добавления, удаления и поиска. На ее основе реализовать + приложение -- словарь. В качестве хеш-функции, можно выбрать + произвольную функцию, например, брать первую букву слова. Добавить + функцию полной очистки словаря и загрузки/дополнения словаря из + текстового файла. +2. Для выбранного текста на русском языке построить словарь на основе + красно-черных деревьев. Реализовать функции добавления, удаления и + поиска слова. (НЕЛЬЗЯ использовать готовые структуры данных!!!). + Добавить функцию полной очистки словаря и загрузки/дополнения + словаря из текстового файла. + +Дополнительная реализация также включает возможность оптимизации +словаря (например, поиск потенциальных однокоренных слов в разных +формах; самый простой критерий -- 2/3 длины слова). Выбор слов, +которые следует оставить в словаре -- за пользователем. Использовать +готовые решения из библиотеки STL не разрешается. +#+end_quote +#+HTML: diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..2e1600b --- /dev/null +++ b/build.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +set +xe + +gcc -std=gnu99 -ggdb3 -fanalyzer \ + -Wall -Wextra -Wpedantic \ + -Wanalyzer-symbol-too-complex --param=analyzer-max-svalue-depth=20 \ + -o dictionary src/dictionary.c \ + src/hash-table.c \ + src/red-black-tree.c diff --git a/channels-lock.scm b/channels-lock.scm new file mode 100644 index 0000000..1da4533 --- /dev/null +++ b/channels-lock.scm @@ -0,0 +1,21 @@ +(use-modules (guix channels)) + +(list + (channel + (name 'guix) + (branch "master") + (url "https://git.savannah.gnu.org/git/guix.git") + (commit "b6dec0108f99d75066bad15aaa124b84bb0261f3") + (introduction (make-channel-introduction + "d264237d55ca5e2c756cc7a44374a7dbca850505" + (openpgp-fingerprint + "BBB0 2DDF 2CEA F6A8 0D1D E643 A2A0 6DF2 A33A 54FA")))) + (channel + (name 'nonguix) + (url "https://gitlab.com/nonguix/nonguix") + (commit "25bcda2b9107b948a1c858e41aba1b7f95b76228") + (introduction + (make-channel-introduction + "897c1a470da759236cc11798f4e0a5f7d4d59fbc" + (openpgp-fingerprint + "2A39 3FFF 68F4 EF7A 3D29 12AF 6F51 20A0 22FB B2D5"))))) diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty @@ -0,0 +1,57 @@ +\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] + +\def\UrlBreaks{\do\/\do-} +\RequirePackage{url} + +\newdimen\bibindent +\renewenvironment{thebibliography}[1]{ + \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy\clubpenalty4000\widowpenalty4000% + \sfcode`\.\@m +}{ + \setcounter{totalbib}{\c@enumiv}% + \def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist +} +\renewcommand\@biblabel{}% +\setlength\bibindent{1.5em} + +% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. +%\makeatletter +\renewcommand*{\@biblabel}[1]{\hfill#1.} + + +% +% Remove References header completely +% Stolen from original article.cls +% +\makeatletter +\renewenvironment{thebibliography}[1]{% +% \usection{\refname}% +% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy + \clubpenalty4000 + \@clubpenalty \clubpenalty + \widowpenalty4000% + \sfcode`\.\@m} + {\def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist} +\makeatother diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..a8db9fb --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty @@ -0,0 +1,28 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, justification=centering} + +% +% Algorithm caption +% +\captionsetup[algorithm]{labelsep=endash, justification=centering} + +\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}} +\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}} +\addto\captionsrussian{\captionsetup[listing]{name=Листинг}} diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..d694c93 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty @@ -0,0 +1,37 @@ +\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] + +% +% Values for capital russian letters counter +% +\makeatletter +\newcommand\AlphRus[1]{% + \expandafter \@AlphRus \csname c@#1\endcsname +} + +\newcommand\@AlphRus[1]{% + \ifcase #1% + \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or + Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or + Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% + \else \@ctrerr +\fi +} +\makeatother + +% +% Values for lowercase russian letters counter +% +\makeatletter +\newcommand\alphRus[1]{% + \expandafter \@alphRus \csname c@#1\endcsname +} + +\newcommand\@alphRus[1]{% + \ifcase #1% + \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or + л\or м\or н\or п\or р\or с\or т\or у\or ф\or + х\or ц\or ш\or щ\or э\or ю\or я% + \else \@ctrerr +\fi +} +\makeatother diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..d0bb40e --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty @@ -0,0 +1,98 @@ +\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{titlesec} +\RequirePackage{titling} +\RequirePackage{setspace} + +\RequirePackage{gost-7-32-counters} + +% +% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection +% +\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing{\section}{0cm}{0cm}{0.5cm} + +\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} +\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} + +\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] +\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} + +% +% Make special headings, that have their own formatting rules: +% - centered +% - all-caps +% - bold +% +% Only three of them must appear in TOC: introduction, conclusion and references +% +\newcommand{\introduction}{ + \addcontentsline{toc}{section}{ВВЕДЕНИЕ} + \begin{center} + \bfseries\large + ВВЕДЕНИЕ + \end{center} +} + +\newcommand{\conclusion}{ + \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} + \begin{center} + \bfseries\large + ЗАКЛЮЧЕНИЕ + \end{center} +} + +\newcommand{\references}{ + \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} + \begin{center} + \bfseries\large + СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ + \end{center} +} + +\newcommand{\essay}{ + \begin{center} + \bfseries\large + РЕФЕРАТ + \end{center} +} + +\newcommand{\definitions}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ + \end{center} +} + +\newcommand{\abbreviations}{ + \begin{center} + \bfseries\large + ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +\newcommand{\defsabbrs}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +% +% Appendices headings. Appendices have autoincrementing number, +% that is represented with russian letter. +% This heading must appear in TOC +% +\newcounter{appendixcnt} +\setcounter{appendixcnt}{1} + +\renewcommand{\appendix}[1]{ + \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} + \begin{center} + \bfseries\large + ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} + + #1 + \end{center} + \stepcounter{appendixcnt} +} diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..b68d55f --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty @@ -0,0 +1,15 @@ +\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{enumitem} +\RequirePackage{gost-7-32-counters} + +\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} + +\setlist{nosep} +\setlist[itemize, 1]{label=\textendash} +\setlist[itemize, 2]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty new file mode 100644 index 0000000..750ab75 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty @@ -0,0 +1,29 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tabularx} + +% +% Center-aligned column with automatic width +% +\newcolumntype{Y}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{Z}{>{\raggedleft\arraybackslash}X} + +% +% Table with designations +% +\newenvironment{designations}{ + \noindent + \tabularx{\textwidth}{@{} + >{\raggedright \arraybackslash \hsize=0.25\hsize}X + >{\centering \arraybackslash \hsize=0.05\hsize}X + >{\arraybackslash \hsize=0.70\hsize}X + } +}{ + \endtabularx +} + +\newcommand{\designation}[2]{#1 &---& #2. \\} diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..c3b835a --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty @@ -0,0 +1,34 @@ +\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] + +%% \RequirePackage{tocloft} +\RequirePackage[ + bookmarks=true, + colorlinks=true, + unicode=true, + urlcolor=black, + linkcolor=black, + anchorcolor=black, + citecolor=black, + menucolor=black, + filecolor=black +]{hyperref} + +% +% Set custom font styles +% +%% \renewcommand{\cftsecfont}{\normalfont} +%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +%% \renewcommand{\cftsecpagefont}{\normalsize} +%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries} +%% \renewcommand{\cftaftertoctitle}{\hfill\hfill} +%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries} +\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} +\titlespacing{\tableofcontents}{0cm}{0cm}{1cm} + +% +% Set indents and line spacing +% +%% \setlength{\cftbeforesecskip}{0cm} +%% \setlength{\cftbeforesubsecskip}{0cm} +%% \setlength{\cftbeforesubsubsecskip}{0cm} +%% \setlength{\cftbeforeparaskip}{0cm} diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..c13b00e --- /dev/null +++ b/doc/gost/gost-7-32.cls @@ -0,0 +1,62 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] + +% +% Supported font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +% +% Set A4 paper format +% +\LoadClass[a4paper]{extarticle} + +% +% Use 1.5 line spacing +% +\RequirePackage{setspace} +\spacing{1.5} + +% +% First paragraph indentation +% +\RequirePackage{indentfirst} +\setlength{\parindent}{12.5mm} + +% +% Page margin +% +\RequirePackage[ + left=2.5cm, + right=2cm, + top=2cm, + bottom=2cm, + footskip=1cm, +]{geometry} + +% +% Use TMR-like font +% +\RequirePackage{fontspec} +\RequirePackage{xunicode} +\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +\setmainfont{Times New Roman} + +% +% Use russian language +% +\RequirePackage[main=russian, english]{babel} +\babelhyphenation[russian]{} + +% +% gost-7-32 packages +% +\RequirePackage{gost-7-32-headings} +\RequirePackage{gost-7-32-toc} +\RequirePackage{gost-7-32-lists} +\RequirePackage{gost-7-32-bibliography} +\RequirePackage{gost-7-32-captions} +\RequirePackage{gost-7-32-tables} diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..913d021 --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,32 @@ +;;; ox-init --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +(org-babel-do-load-languages + 'org-babel-load-languages + '((latex . t) + (C . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(require 'oc-bibtex) + +(setq org-latex-src-block-backend 'minted) + +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-latex-caption-above '(table src-block special-block)) + +(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" + "%bib %b" + "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) +(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" + ("\\section{%s}" . "\\usection{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;;; ox-init.el ends here diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..6fb0d1a --- /dev/null +++ b/doc/report.org @@ -0,0 +1,1024 @@ +#+TITLE: Реализация словаря на основе хеш-таблиц и красно-чёрных деревьев +#+AUTHOR: Михалец Мартин +#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №6} +#+LATEX_HEADER: \subject{по дисциплине «Теория графов»} +#+LATEX_HEADER: \reviewertitle{}\reviewer{Востров Алексей Владимирович} +#+DATE: 2024 + +#+SETUPFILE: setup.org +#+LATEX: \sloppy + +* Введение +:PROPERTIES: +:UNNUMBERED: t +:END: +В данном отчёте представлено описание шестой лабораторной работы по +дисциплине «Тория графов». Лабораторная работа включает в себя +реализация словаря на основе хеш-таблицы и красно-чёрного дерева. + +Функции, которые применяются к словарю: +1. Печатание словаря в виде графа. +2. Добавление слова в словарь. +3. Удаление слова из словаря. +4. Поиск слова в словаре. +5. Полная очистка словаря. +6. Дополнение словаря из файла. + +* Математическое описание +** Хеш-таблица +/Хэш-таблица/ --- это структура данных, похожая на ассоциативный массив, +т.е. хранит пары ключ-значение, где в качестве ключа выступает любой +объект, для которого можно вычислить его хеш. Интерфейс хеш-таблицы +предоставляет нам следующие операции: +- добавление новой пары ключ-значение, +- поиск значения по ключу, +- удаление пары ключ-значение по ключу. + +На рисунке [[example-hash-table]] приведён пример хеш-таблицы (c 13 +корзинами) словаря с текстом: «Это очередной пример очень простой хеш +таблицы применяющий функцию хеширования djb2.» + +#+name: example-hash-table +#+caption: Пример хеш-таблицы +#+attr_latex: :height 16cm +[[./example-hash-table.pdf]] + +*** Хеш-функция +/Хеш-функция/, или /функция свёртки/ --- функция, преобразующая массив +входных данных произвольного размера в выходную битовую строку +определённого (установленного) размера в соответствии с определённым +алгоритмом. Сила хеш-функции в том, что они один и тот же массив +всегда превращают в одну и ту же битовую строку, для этого хеш-функция +должна являться устойчивой. Преобразование, выполняемое хеш-функцией, +называется хешированием. Исходные (входные) данные называются входным +массивом, «ключом», «сообщением». Результат преобразования (выходные +данные) называется «хешем», «хеш-кодом», «хеш-суммой», «сводкой +сообщения», «свёрткой». + +В данной работе применяется устойчивая функция хеширования djb2, +которая напоминает линейный конгруэнтный метод генерации +псевдослучайных чисел за счет аккумуляции $X = (a \cdot X) + c$ как +можно заметить в алгоритме @@latex:\ref{alg:pseudo}@@. Также +существует альтернативная версия данной хеш-функции, которая вместо +сложения очередного элемента массива производит побитовое исключающее +или, что возможно улучает некоторые её качества. + + #+BEGIN_EXPORT latex +\begin{algorithm}[H] + \caption{Вычисление хеш-функции djb2} + \label{alg:pseudo} + \begin{algorithmic}[1] + \setlength{\baselineskip}{5pt} + \Procedure {djb2}{$s[0..n]$} + \State $h \leftarrow 5381$ + \For {$i = 0$ to $n$} + \State $h \leftarrow 33 \cdot h + s[i]$ + \EndFor + \State \Return $h$ + \EndProcedure + \end{algorithmic} +\end{algorithm} +#+END_EXPORT + +*** Добавление, удаление и поиск +/Поиск записи/ --- вычисляется хеш ключа, с помощью функции хеширования, +чтобы получить индекс корзины. Дальше проходим корзиной пока либо не +найдём запись с одинаковым ключом, в случае чего возвращаем значение +записи, или не дойдём до конца, тогда возвращаем информацию об +отсутствии записи. + +/Добавление записи/ --- также как при поиске, но в случае нахождения +записи с совпадающим ключом переписываем её значение, а в случае её +отсутствия добавляем её в конец корзины. + +/Удаление записи/ --- также как при поиске, но в случае нахождения +записи с совпадающим ключом удаляем её из корзины, удерживая +целостность корзины. + +*Сложность всех операций составляет:* $\mathcal{O}(1)$, при отсутствии +коллизии. + +*** Разрешение коллизий +При добавлении нового элемента, хеш-функция может выдать такой +идентификатор, по которому уже присутствует ключ. В данной реализации +эта проблема решается методом цепочек. Каждая ячейка корзины содержит +цепочку пар ключ-значение, соответствующих одному и тому же +хеш-значению ключа. Коллизии просто приводят к тому, что появляются +цепочки длиной более одного элемента. Операции поиска или удаления +элемента требуют просмотра всех элементов соответствующей ему цепочки, +чтобы найти в ней элемент с заданным ключом. Для добавления элемента +нужно добавить элемент в конец цепочки. При предположении, что каждый +элемент может попасть в любую позицию корзины с равной вероятностью и +независимо от того, куда попал любой другой элемент, среднее время +работы операции поиска элемента составляет $\mathcal{O}(1+a)$, где $a$ +--- /коэффициент заполнения корзины/. + +** Красно-чёрное дерево +/Красно-чёрное дерево/ --- это самобалансирующееся дерево поиска, +гарантирующее логарифмический рост высоты дерева в зависимости от +количества узлов. Бинарное дерево, баланс которого достигается за +счет поддержания раскраски вершин в два цвета. + +Правила окрашивания: +- корень окрашен в черный цвет; +- каждый узел покрашен либо в черный, либо в красный цвет; +- листья покрашены в чёрный цвет; +- если узел красный, то оба его потомка чёрные. + +Для реализации данного вида сбалансированных деревьев, нужно в каждой +вершине хранить дополнительно 1 бит информации (цвет). + +На рисунке [[example-red-black-tree]] приведён пример красно-чёрного +дерева словаря с текстом: «Это очередной пример очень простого +красно-чёрного дерева.» + +#+name: example-red-black-tree +#+caption: Пример красно-чёрного дерева +[[./example-red-black-tree.pdf]] + +*** Вставка +1. Каждый элемент вставляется вместо листа, поэтому для выбора места + вставки идём от корня до листа. +2. Вставляем вместо него новый красный узел без потомков. +3. Дальше требуется балансировка после вставки. + +*Сложность алгоритма:* $\mathcal{O}(\log n)$ + +*** Балансировка после вставки узла +При добавлении нового узла происходит проверка соседних +узлов. Возможны 5 случаев: + +1. Если текущий узел --- корень дерева, то добавляемый узел + перекрашивается в черный цвет, чтобы соблюдать условия + красно-чёрных деревьев. +2. Если «родитель» текущего узла черный, тогда свойства не нарушаются. + Узел можно не перекрашивать. +3. Если «родитель» и «дядя» красные, то перекрасим «родителя» и «дядю» + в чёрный цвет, а «дедушку» --- в красный. При этом число чёрных + вершин на любом пути от корня к листьям остаётся прежним. Теперь у + текущего красного узла «родитель» чёрного цвета. Нарушение свойств + красно-чёрного дерева возможно лишь в одном месте: вершина + «дедушка» может иметь красного «родителя». Чтобы этого не + произошло рекурсивно выполняется процедура первого случая. В + остальных случаях начинает применяться поворот дерева вправо или + влево. +4. Если «дядя» --- чёрная вершина, «родитель» --- красная и текущий + узел --- правый потомок, то добавленный узел является левым + потомком красной вершины, которая, в свою очередь, является левым + потомком своего родителя, правым потомком которой является + «дядя». В этом случае достаточно произвести правое вращение и + перекрасить две вершины. Процесс перекраски окончится, так как + вершина родитель будет после этого чёрной. +5. Если «дядя» --- чёрная вершина, «родитель» - красная, текущий узел + --- левый потомок, то добавленный узел является правым потомком + красной вершины, которая, в свою очередь, является левым потомком + своего родителя, правым потомком которой является «дядя». В этом + случае производится левое вращение, которое сводит это случай к + случаю 2, когда добавляемый узел является потомком своего родителя. + После вращения глубина, измеренная в чёрных узлах от корня к + листьям, остаётся прежней. + +*** Удаление +В процессе удаления вершины могут возникнуть 3 случая в зависимости от +количества её потомков: +1. Если у вершины нет потомков, то у её родителя заменяем её на лист. +2. Если у неё только один потомок, то у её родителя заменяем её на + данного потомка. +3. Если имеются оба потомка, в правой ветке находим минимальную + вершину. У такой вершины нет левого потомка. Переставляем эту + вершину на место удаляемой. +4. Дальше требуется балансировка после удаления. + +*Сложность алгоритма:* $\mathcal{O}(\log n)$ + +*** Балансировка после удаления узла +При удалении красной вершины свойства дерева не нарушаются. +Балансировка потребуется только при удалении чёрной. + +1. Если «брат» этого потомка красный, то делаем вращение вокруг ребра + между «отцом» и «братом», тогда «брат» становится родителем «отца». + Красим его в чёрный, а «отца» --- в красный цвет. +2. Если «брат» текущей вершины был чёрным, то требуется рассмотреть + еще 3 случая: + 1. Оба потомка у «брата» чёрные. Красим «брата» в красный цвет и + рассматриваем далее «отца» вершины. + 2. Если у «брата» правый «сын» черный, а левый красный, то + перекрашиваем брата и его левого «сына» и делаем вращение. + 3. Если у брата правый «сын» красный, то перекрашиваем «брата» в + цвет отца, его «сын» и «отца» --- в чёрный, делаем вращение и + выходим из алгоритма. + +*** Поиск +Поиск в красно-чёрном дереве происходит как и в бинарном дереве. +Алгоритм начинает от корня дерева, на каждой итерации происходит +проверка, соответствует ли ключ рассматриваемого узла ключу, который +мы ищем. +- Если да, то возвращается узел. +- Если нет, то происходит сравнение текущего значения ключа и + искомого. В зависимости от того больше или меньше переходим в + правое или левое поддерево. +- Алгоритм повторяет вышеперечисленное до тех пор, пока не дойдет до + листа, в случае чего возвращается информация об отсутствии такой + вершины. + +*Сложность алгоритма:* $\mathcal{O}(\log n)$. + +* Реализация +** Хеш-таблица +Хеш таблица хранится в виде массива указателей на отдельные корзины с +заголовком их количества (см. листинг [[hash-table-structure]]). Ключ и +значение простые строки. Полный интерфейс указан в листинге +[[hash-table-interface]], но ближе будут рассмотрены только основные +функции хеш-таблиц. + +#+name: hash-table-interface +#+caption: Интерфейс хеш таблицы +#+begin_src c +typedef struct hash_table *HASH_TABLE; + +HASH_TABLE hash_table_init (size_t bucket_count); +void hash_table_free (HASH_TABLE); +void hash_table_clear (HASH_TABLE); +void hash_table_print (HASH_TABLE, const char *filename); +void hash_table_insert (HASH_TABLE, const char *key, const char *value); +bool hash_table_delete (HASH_TABLE, const char *key); +const char *hash_table_search (HASH_TABLE, const char *key); +#+end_src + +#+name: hash-table-structure +#+caption: Структура хеш таблицы +#+begin_src c +typedef struct entry *ENTRY; +struct entry { + ENTRY next; + char *key; + char *value; +}; + +struct hash_table { + size_t bucket_count; + ENTRY buckets[]; +}; +#+end_src + +Вспомогательная функция хеширования (см. листинг [[hash-table-djb2]]) +вычисляет хеш размера в 64-бит. В её реализации применяется +оптимизации замены умножения на сдвиг и сложение, хотя оптимизирующий +компилятор должен этого уметь делать и сам. + +#+name: hash-table-djb2 +#+caption: Функция хеширования +#+begin_src c +static inline size_t +hash_function_djb2 (const char *str) +{ + size_t hash = 5381; + unsigned char c; + + while ((c = *str++)) + hash = ((hash << 5) + hash) + c; // hash = 33*hash + c + + return hash; +} +#+end_src + +Все 3 основных операции хеш-таблиц имеют одинаковую структуру +(см. листинги [[hash-table-insert]]-[[hash-table-search]]), которая позволяет +2 места различия: запись найдена или не найдена. Поскольку хеш +таблица владеет всей памятью, которую в себе хранит, то надо аккуратно +копировать и освобождать нужные записи в нужные моменты. + +#+name: hash-table-insert +#+caption: Функция вставки в хеш-таблицу +#+begin_src c +void +hash_table_insert (HASH_TABLE hash_table, const char *key, const char *value) +{ + size_t hash = hash_function_djb2 (key); + ENTRY *entry = &hash_table->buckets[hash % hash_table->bucket_count]; + while (*entry) { + if (!strcmp (key, (*entry)->key)) { // found + free ((*entry)->value); + (*entry)->value = strdup (value); + return; + } else entry = &(*entry)->next; + } + + // not found + *entry = malloc (sizeof (**entry)); + (*entry)->next = NULL; + (*entry)->key = strdup (key); + (*entry)->value = strdup (value); +} +#+end_src + +#+name: hash-table-delete +#+caption: Функция удаления из хеш-таблицы +#+begin_src c +bool +hash_table_delete (HASH_TABLE hash_table, const char *key) +{ + size_t hash = hash_function_djb2 (key); + ENTRY *entry = &hash_table->buckets[hash % hash_table->bucket_count]; + while (*entry) { + if (!strcmp (key, (*entry)->key)) { // found + ENTRY next = (*entry)->next; + + free ((*entry)->key); + free ((*entry)->value); + free (*entry); + + *entry = next; + + return true; + } else entry = &(*entry)->next; + } return false; // not found +} +#+end_src + +#+name: hash-table-search +#+caption: Функция поиска в хеш-таблицы +#+begin_src c +const char * +hash_table_search (HASH_TABLE hash_table, const char *key) +{ + size_t hash = hash_function_djb2 (key); + ENTRY entry = hash_table->buckets[hash % hash_table->bucket_count]; + while (entry) { + if (!strcmp (key, entry->key)) // found + return entry->value; + else entry = entry->next; + } return NULL; // not found +} +#+end_src + +** Красно-чёрное дерево +Красно-чёрное дерево в виде указателя на его корневой узел +(см. листинг [[red-black-tree-structure]]). У каждого узла кроме ключа, +по которому происходит сравнение, также и значение, благодаря чему +можем данную структура данных является ассоциативной. Поскольку для +листьев используем чисто ~NULL~ указатель, а не единый экземпляр ~NILL~ +узла, то при проверке на красный цвет надо не забывать сначала +проверить сам указатель. Полный интерфейс указан в листинге +[[red-black-tree-interface]], но ближе будут рассмотрены только основные +функции красно-чёрных деревьев и некоторые вспомогательные функции. + +#+name: red-black-tree-interface +#+caption: Полный интерфейс красно-чёрного дерева +#+begin_src c +typedef struct red_black_tree *RED_BLACK_TREE; + +RED_BLACK_TREE red_black_tree_init (void); +void red_black_tree_free (RED_BLACK_TREE); +void red_black_tree_clear (RED_BLACK_TREE); +void red_black_tree_print (RED_BLACK_TREE, const char *filename); +void red_black_tree_insert (RED_BLACK_TREE, const char *key, const char *value); +bool red_black_tree_delete (RED_BLACK_TREE, const char *key); +const char *red_black_tree_search (RED_BLACK_TREE, const char *key); +#+end_src + +#+name: red-black-tree-structure +#+caption: Структура красно-чёрного дерева +#+begin_src c +enum color { + COLOR_RED, + COLOR_BLACK, +}; + +typedef struct node *NODE; +struct node { + NODE parent; + NODE left; + NODE right; + enum color color; + char *key; + char *value; +}; + +struct red_black_tree { NODE root; }; +#+end_src + +~minimum~ --- функция поиска минимально элемента поддеревья (см. листинг +[[red-black-tree-minimum]]). Принимает указатель на узел -- корень +поддеревья, и возвращает указатель на минимальный узел данного +поддеревья. + +#+name: red-black-tree-minimum +#+caption: Функция поиска минимального узла в поддереве +#+begin_src c +static inline NODE +minimum (NODE node) +{ + if (!node) + return NULL; + + while (node->left) + node = node->left; + + return node; +} +#+end_src + +~rotate_left~ и ~rotate_right~ --- функции вращения деревья влево и вправо +относительно одного узла (см. листинги [[red-black-tree-rotate-left]] и +[[red-black-tree-rotate-right]]). Эти функции принимают указатель на +структуру красно-чёрного дерева и указатель на узел вращения. Функции +ничего не возвращают. Эти функции применяются для превращения +«цепочки» 3 узлов в «треугольник». + +#+name: red-black-tree-rotate-left +#+caption: Вспомогательная функция левого поворота +#+begin_src c +static inline void +rotate_left (RED_BLACK_TREE red_black_tree, NODE node) +{ + NODE y = node->right; + node->right = y->left; + if (y->left) + y->left->parent = node; + y->parent = node->parent; + + if (!node->parent) { + red_black_tree->root = y; + } else if (node == node->parent->left) { + node->parent->left = y; + } else { + node->parent->right = y; + } + + y->left = node; + node->parent = y; +} +#+end_src + +#+name: red-black-tree-rotate-right +#+caption: Вспомогательная функция правого поворота +#+begin_src c +static inline void +rotate_right (RED_BLACK_TREE red_black_tree, NODE node) +{ + NODE y = node->left; + node->left = y->right; + if (y->right) + y->right->parent = node; + y->parent = node->parent; + + if (!node->parent) { + red_black_tree->root = y; + } else if (node == node->parent->right) { + node->parent->right = y; + } else { + node->parent->left = y; + } + + y->right = node; + node->parent = y; +} +#+end_src + +~red_black_tree_insert~ --- функция добавления элемента в дерево +(см. листинг @@latex:\ref{lst:red-black-tree-insert}@@). Принимает +строку, ничего не возвращает. Если дерево ещё не содержит элементов, +то добавленный элемент перекрашивается в чёрный цвет и становится +корнем дерева. Если элемент с такой строкой уже есть в словаре, +индекс этого элемента инкрементируется. Если дерево не пустое, то +находится потенциальный родитель для добавленного элемента, далее, +исходя из его значения, помещаем принятое значение слева или справа. +С помощью дополнительных функций поворота и перекраски узлов, +сохраняются свойства красно-чёрных деревьев. + +#+latex: \captionof{listing}{Функция вставки в красно-чёрное дерево\label{lst:red-black-tree-insert}} +#+begin_src c +void +red_black_tree_insert (RED_BLACK_TREE red_black_tree, + const char *key, const char *value) +{ + // change value if already exists + for (NODE head = red_black_tree->root, next; head; head = next) { + int difference = strcmp (head->key, key); + if (!difference) { + free (head->value); + head->value = strdup (value); + return; + } + next = difference > 0 ? head->left : head->right; + } + + NODE node = calloc (1, sizeof (*node)); + node->key = strdup (key); + node->value = strdup (value); + + // find parent + for (NODE head = red_black_tree->root, next; head; head = next) { + node->parent = head; + next = strcmp (node->key, head->key) < 0 ? head->left + : head->right; + } + + // no parent + if (!node->parent) { + node->color = COLOR_BLACK; + red_black_tree->root = node; + return; + } + + // attach + if (strcmp (node->key, node->parent->key) < 0) { + node->parent->left = node; + } else { + node->parent->right = node; + } + + // no grandparent + if (!node->parent->parent) + return; + + // fix insert + NODE u; + while (node->parent->color == COLOR_RED) { + if (node->parent == node->parent->parent->right) { + u = node->parent->parent->left; // uncle + if (u && u->color == COLOR_RED) { // case 3.1 + u->color = COLOR_BLACK; + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + node = node->parent->parent; + } else { + if (node == node->parent->left) { // case 3.2.2 + node = node->parent; + rotate_right (red_black_tree, node); + } + + // case 3.2.1 + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + rotate_left (red_black_tree, node->parent->parent); + } + } else { + u = node->parent->parent->right; // uncle + + if (u && u->color == COLOR_RED) { // mirror case 3.1 + u->color = COLOR_BLACK; + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + node = node->parent->parent; + } else { + if (node == node->parent->right) { // mirror case 3.2.2 + node = node->parent; + rotate_left (red_black_tree, node); + } + + // mirror case 3.2.1 + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + rotate_right (red_black_tree, node->parent->parent); + } + } + if (node == red_black_tree->root) { + break; + } + } + red_black_tree->root->color = COLOR_BLACK; +} +#+end_src + +~red_black_tree_delete~ --- функция удаления элемента из дерева +(см. листинг @@latex:\ref{lst:red-black-tree-delete}@@). Принимает +строку, возвращает информацию о нахождении записи. Удаление включает +в себя перестановки узлов, поворот дерева. После удаления сохраняется +свойство красно-черных деревьев. + +#+latex: \captionof{listing}{Функция удаления из красно-чёрного дерева\label{lst:red-black-tree-delete}} +#+begin_src c +bool +red_black_tree_delete (RED_BLACK_TREE red_black_tree, const char *key) +{ + NODE node = NULL; + NODE target = NULL; + NODE child = NULL; + + for (NODE head = red_black_tree->root, next; head; head = next) { + if (!strcmp (head->key, key)) { + node = head; + break; + } + next = strcmp (head->key, key) <= 0 ? head->right : head->left; + } + + if (!node) + return false; + + if (!node->left || !node->right) { + target = node; + } else { + target = minimum (node->right); + + SWAP (node->key, target->key); + SWAP (node->value, target->value); + } + + child = !target->left ? target->right : target->left; + + if (target->color == COLOR_BLACK) { + if (child && child->color == COLOR_RED) { + // deletion from 3-children cluster (BLACK target node, RED + // child node) + child->color = COLOR_BLACK; + } else if (target == red_black_tree->root) { + // deletion from 2-children root cluster (BLACK target node, + // BLACK child node) + } else { // REBALANCE + // deletion from 2-children cluster (BLACK target node, ...) + NODE current = target; + NODE sibling; + do { + if (current == current->parent->left) { + sibling = current->parent->right; + if (sibling && sibling->color == COLOR_RED) { + // perform an adjustment (3-children parent cluster has + // two representations) + sibling->color = COLOR_BLACK; + current->parent->color = COLOR_RED; + rotate_left (red_black_tree, current->parent); + sibling = current->parent->right; + } + + // sibling node must be BLACK now + if ((!sibling->right || sibling->right->color == COLOR_BLACK) && + (!sibling->left || sibling->left ->color == COLOR_BLACK)) { + // 2-children sibling cluster, fuse by recoloring + sibling->color = COLOR_RED; + if (current->parent->color == COLOR_RED) { + current->parent->color = COLOR_BLACK; + break; + } else { + // 2-children parent cluster + current = current->parent; + } + } else { + // 3/4-children sibling cluster + if (!sibling->right || sibling->right->color == COLOR_BLACK) { + // perform an adjustment (3-children sibling cluster has + // two representations) + sibling->left->color = COLOR_BLACK; + sibling->color = COLOR_RED; + rotate_right (red_black_tree, sibling); + sibling = current->parent->right; + } + + // transfer by rotation and recoloring + sibling->color = current->parent->color; + current->parent->color = COLOR_BLACK; + sibling->right->color = COLOR_BLACK; + rotate_left (red_black_tree, current->parent); + break; + } + } else { + sibling = current->parent->left; + if (sibling->color == COLOR_RED) { + // perform an adjustment (3-children parent cluster has + // two representations) + sibling->color = COLOR_BLACK; + current->parent->color = COLOR_RED; + rotate_right (red_black_tree, current->parent); + sibling = current->parent->left; + } + + // sibling node must be BLACK now + if ((!sibling->right || sibling->right->color == COLOR_BLACK) && + (!sibling->left || sibling->left ->color == COLOR_BLACK)) { + // 2-children sibling cluster, fuse by recoloring + sibling->color = COLOR_RED; + if (current->parent->color == COLOR_RED) { + // 3/4-children parent cluster + current->parent->color = COLOR_BLACK; + break; + } else current = current->parent; + } else { + // 3/4-children sibling cluster + if (!sibling->left || sibling->left->color == COLOR_BLACK) { + // perform an adjustment (3-children sibling cluster has + // two representations) + sibling->right->color = COLOR_BLACK; + sibling->color = COLOR_RED; + rotate_left (red_black_tree, sibling); + sibling = current->parent->left; + } + + // transfer by rotation and recoloring + sibling->color = current->parent->color; + current->parent->color = COLOR_BLACK; + sibling->left->color = COLOR_BLACK; + rotate_right (red_black_tree, current->parent); + break; + } + } + } while (current != red_black_tree->root); + } + } else { + // deletion from 4-children cluster (RED target node) + // deletion from 3-children cluster (RED target node) + } + + if (child) + child->parent = target->parent; + + if (target->parent) { + if (target == target->parent->left) + target->parent->left = child; + else if (target == target->parent->right) + target->parent->right = child; + } else { + red_black_tree->root = child; + } + + free (target->key); + free (target->value); + free (target); + + return true; +} +#+end_src + +~red_black_tree_search~ --- функция поиска элемента в дереве +(см. листинг [[red-black-tree-search]]). принимает строку -- ключ, +возвращает строку -- значение. + +#+name: red-black-tree-search +#+caption: Функция поиска в красно-чёрном дереве +#+begin_src c +const char * +red_black_tree_search (RED_BLACK_TREE red_black_tree, const char *key) +{ + for (NODE head = red_black_tree->root, next; head; head = next) { + int difference = strcmp (head->key, key); + if (!difference) return head->value; + next = difference > 0 ? head->left : head->right; + } + + return NULL; +} +#+end_src + +** Приложение словарь +Вся суть приложения в обработке простого меню, она приведена в +листинге @@latex:\ref{lst:dictionary-menu}@@. Есть несколько операции +по хеш-таблицы и красно-чёрном дереве, в данном листинге видно их +применение в качестве словарей. + +#+latex: \captionof{listing}{Обработка меню словаря\label{lst:dictionary-menu}} +#+begin_src c +switch (selection) { + case GENERAL_EXIT: { + puts ("EXITING..."); + hash_table_free (hash_table); + red_black_tree_free (red_black_tree); + return EXIT_SUCCESS; + } break; + + case HASH_TABLE_PRINT: { + hash_table_print (hash_table, "hash-table.dot"); + puts ("hash-table.dot:0:0: HASH TABLE PRINTED"); + } break; + + case HASH_TABLE_INSERT: { + const char *word = input_word (); + hash_table_insert (hash_table, word, strdup ("")); + puts ("ENTRY INSERTED"); + } break; + + case HASH_TABLE_DELETE: { + const char *word = input_word (); + if (hash_table_delete (hash_table, word)) + puts ("ENTRY DELETED"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case HASH_TABLE_SEARCH: { + const char *key = input_word (); + const char *value = hash_table_search (hash_table, key); + if (value) + puts ("ENTRY FOUND"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case HASH_TABLE_CLEAR: { + hash_table_clear (hash_table); + puts ("HASH TABLE CLEARED"); + } break; + + case HASH_TABLE_LOAD_FROM_FILE: { + const char *filename = input_filename (); + load_from_file (filename, (void *) hash_table_insert, hash_table); + } break; + + case RED_BLACK_TREE_PRINT: { + red_black_tree_print (red_black_tree, "red-black-tree.dot"); + puts ("red-black-tree.dot:0:0: RED BLACK TREE PRINTED"); + } break; + + case RED_BLACK_TREE_INSERT: { + const char *word = input_word (); + red_black_tree_insert (red_black_tree, word, strdup ("")); + puts ("ENTRY INSERTED"); + } break; + + case RED_BLACK_TREE_DELETE: { + const char *key = input_word (); + if (red_black_tree_delete (red_black_tree, key)) + puts ("ENTRY DELETED"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case RED_BLACK_TREE_SEARCH: { + const char *key = input_word (); + const char *value = red_black_tree_search (red_black_tree, key); + if (value) + puts ("ENTRY FOUND"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case RED_BLACK_TREE_CLEAR: { + red_black_tree_clear (red_black_tree); + puts ("RED BLACK TREE CLEARED"); + } break; + + case RED_BLACK_TREE_LOAD_FROM_FILE: { + const char *filename = input_filename (); + load_from_file (filename, (void *) red_black_tree_insert, red_black_tree); + } break; + default: break; +} +#+end_src + +* Результаты работы +В результаты работы также входят сгенерированные коммандой =PRINT= графы +[[example-hash-table]] и [[example-red-black-tree]]. + +Начало работы программы и меню: +#+begin_src text +HASH-TABLE:......FILE LOADED (159 ENTRIES) +RED-BLACK-TREE:..FILE LOADED (159 ENTRIES) + +SELECT: + [00] GENERAL:.........EXIT + [01] HASH-TABLE:......PRINT + [02] HASH-TABLE:......INSERT + [03] HASH-TABLE:......DELETE + [04] HASH-TABLE:......SEARCH + [05] HASH-TABLE:......CLEAR + [06] HASH-TABLE:......LOAD_FROM_FILE + [07] RED-BLACK-TREE:..PRINT + [08] RED-BLACK-TREE:..INSERT + [09] RED-BLACK-TREE:..DELETE + [10] RED-BLACK-TREE:..SEARCH + [11] RED-BLACK-TREE:..CLEAR + [12] RED-BLACK-TREE:..LOAD_FROM_FILE +> + #+end_src + +Пример сеанса без меню, но с комментариями после =#=: + #+begin_src text +> asdf +> -1 +> 13 +> +> 04 # (HASH-TABLE) SEARCH +WORD: словарь +ENTRY FOUND +> 10 # (RED-BLACK-TREE) SEARCH +WORD: словарь +ENTRY FOUND +> +> 04 # (HASH-TABLE) SEARCH +WORD: тест +ENTRY NOT FOUND +> 10 # (RED-BLACK-TREE) SEARCH +WORD: тест +ENTRY NOT FOUND +> 06 # (HASH-TABLE) LOAD_FROM_FILE +FILENAME: text +FILE LOADED (30 ENTRIES) +> 12 # (RED-BLACK-TREE) LOAD_FROM_FILE +FILENAME: text +FILE LOADED (30 ENTRIES) +> 04 # (HASH-TABLE) SEARCH +WORD: тест +ENTRY FOUND +> 10 # (RED-BLACK-TREE) SEARCH +WORD: тест +ENTRY FOUND +> +> 02 # (HASH-TABLE) INSERT +WORD: слово +ENTRY INSERTED +> 04 # (HASH-TABLE) SEARCH +WORD: слово +ENTRY FOUND +> 03 # (HASH-TABLE) DELETE +WORD: слово +ENTRY DELETED +> 04 # (HASH-TABLE) SEARCH +WORD: слово +ENTRY NOT FOUND +> 05 # (HASH-TABLE) CLEAR +HASH TABLE CLEARED +> 04 # (HASH-TABLE) SEARCH +WORD: тест +ENTRY NOT FOUND +> +> 08 # (RED-BLACK-TREE) INSERT +WORD: слово +ENTRY INSERTED +> 10 # (RED-BLACK-TREE) SEARCH +WORD: слово +ENTRY FOUND +> 09 # (RED-BLACK-TREE) DELETE +WORD: слово +ENTRY DELETED +> 10 # (RED-BLACK-TREE) SEARCH +WORD: слово +ENTRY NOT FOUND +> 11 # (RED-BLACK-TREE) CLEAR +HASH TABLE CLEARED +> 10 # (RED-BLACK-TREE) SEARCH +WORD: тест +ENTRY NOT FOUND +> 00 # (GENERAL) EXIT +#+end_src + +* Заключение +:PROPERTIES: +:UNNUMBERED: t +:END: +В результате работы были, на языке программирования Си, реализованы: +- словарь на основе хэш-таблицы, +- словарь на основе красно-черного дерева, +- операции поиска, добавления и удаления записи, +- а также операции полной очистки и загрузки словаря из файла. + +Если сравнить хеш-таблицы с красно-чёрными деревьями чисто по +сложности их основных алгоритмов, при условии, что хеш-таблица не +слишком заполнена, то очевидно, что алгоритмы над хеш-таблицами будут +работать быстрее, но при очень малом заполнении хеш-таблицы будет +выделено в пустую много памяти. Этот проблем хеш-таблиц можно решить +способом похожим на балансировку дерева, удерживая хеш-таблицу +оптимально заполненной, но в данной работе эта проблема не +затрагивалась. Хеш-таблицы могут в принципе занимать меньше памяти, +при хранении одинакового количества объектов, за счет того, что их +объекты требуют только одного дополнительного указателя, когда в то же +время красно-чёрные деревья требуют три дополнительных указателя и +один бит для цвета, который в большинстве реализации будет занимать +размер указателя, за счет выравнивания структур, но его можно хранить, +например, в одном из обязательных указателей. Красно-чёрные деревья, +и в общем бинарные дерева поиска, имеют одно выделяющееся преимущество +над хеш-таблицами --- над объектами хранящимися в них можно эффективно +пройти в упорядоченном порядке. + +*Достоинства программы:* +- Возможность записи хеш-таблиц и красно-чёрных деревьев в =dot= формате + для графической визуализации, что сильно помогло при отладке + операции над красно-чёрным деревом. +- Простая и наглядная реализация, что позволяет её использовать почти + в качестве псевдокода. + +*Недостатки программы:* +- Освобождение памяти словарей имеет сложность $\mathcal{O}(n)$, + стоило бы рассмотреть применение арены распределителя памяти для + понижения сложности до $\mathcal{O}(1)$. +- Хеш-таблица имеет фиксированное при сборке количество корзин, что + может быть проблемно, поскольку хеш-таблицы работают эффективно до + 80% заполнения. +- Были использованы наивные реализации обоих структур данных, поэтому + они не очень гибкие и эффективные. + +*Масштабирование программы:* +- Добавление возможности поиска однокоренных слов. +- Добавление выбора метода хэш-функции, для хеш-таблицы. + +* Используемая литература +:PROPERTIES: +:UNNUMBERED: t +:END: +1. Hash table --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Hash_table]] (Дата обращения: + 22.05.2024) +2. Hash function --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Hash_function]] (Дата обращения: + 22.05.2024) +3. Linear congruential generator --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Linear_congruential_generator]] (Дата обращения: + 22.05.2024) +4. Red–black tree --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Red%E2%80%93black_tree]] (Дата обращения: + 22.05.2024) + +# Local Variables: +# org-confirm-babel-evaluate: nil +# org-export-async-init-file: "ox-init.el" +# org-export-in-background: t +# End: diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..6895f6f --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,43 @@ +#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline +#+OPTIONS: author:t broken-links:nil c:nil creator:nil +#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t +#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t +#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t +#+SELECT_TAGS: export +#+EXCLUDE_TAGS: noexport +#+CREATOR: Emacs 29.1 (Org mode 9.6.9) +#+BIBLIOGRAPHY: biblio.bib +#+CITE_EXPORT: biblatex +#+LATEX_COMPILER: xelatex +#+LATEX_CLASS: spbstu-report +# #+LATEX_CLASS_OPTIONS: [draft] +#+LATEX_HEADER: \usepackage{enumitem} +#+LATEX_HEADER: \usepackage{array} +#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type +# #+LATEX_HEADER: \usepackage{float} +#+LATEX_HEADER: \usepackage{tikz} +#+LATEX_HEADER: \usepackage{pgfplots} +#+LATEX_HEADER: \pgfplotsset{compat=1.18} +#+LATEX_HEADER: \usepackage{afterpage} +#+LATEX_HEADER: \usepackage{floatrow} +#+LATEX_HEADER: \usepackage{minted} +#+LATEX_HEADER: \floatsetup[listing]{style=Plaintop} +#+LATEX_HEADER: \floatsetup[algorithm]{style=Plaintop} +#+LATEX_HEADER: \usemintedstyle{bw} +#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines} +#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} +#+LATEX_HEADER: \usepackage[plain]{algorithm} +#+LATEX_HEADER: \usepackage{algpseudocode} +#+LATEX_HEADER: \makeatletter +#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм} +#+LATEX_HEADER: \makeatother +#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+LATEX_HEADER: \setmainfont{Times New Roman} +#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff] +#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}} +#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label} +#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}} +#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt} +#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt} +#+LATEX_HEADER: \hypersetup{hidelinks} +#+LATEX_HEADER: \newcommand{\overbar}[1]{\mkern 1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu} diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..422edf2 --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,73 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] + +% +% Support font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +\LoadClass[a4paper]{gost-7-32} + +\RequirePackage{csquotes} +\RequirePackage{amsmath} +\RequirePackage{adjustbox} +\RequirePackage{setspace} + +\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} +\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} +\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} +\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{Федеральное государственное автономное + образовательное учреждение высшего образования + \enquote{Санкт-Петербургский политехнический университет Петра Великого}} + + \vspace{0.5cm} + \normalsize{Институт компьютерных наук и кибербезопасности} + + \normalsize{Высшая школа технологии искусственного интеллекта} + + \normalsize{Направление 02.03.01 Математика и компьютерные науки} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130201/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ + \!\!\!Преподаватель, & \hspace{2cm} & \\ + \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ + &&\hspace{5cm} + \end{tabular} + \begin{flushright} + \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. + \end{flushright} + } + + \vspace*{\fill} + \begin{center} + \small{Санкт-Петербург, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/manifest.scm b/manifest.scm new file mode 100644 index 0000000..beca593 --- /dev/null +++ b/manifest.scm @@ -0,0 +1,52 @@ +(use-modules (gnu packages base) + (gnu packages commencement) + (gnu packages tex) + (nongnu packages fonts)) + +(packages->manifest (list + gcc-toolchain + font-microsoft-times-new-roman + texlive-scheme-small + texlive-lh + texlive-cm + texlive-type1cm + texlive-ec + texlive-wrapfig + texlive-adjustbox + texlive-graphics + texlive-hyperref + texlive-latex-fonts + texlive-amsfonts + texlive-cyrillic + texlive-babel-russian + texlive-geometry + texlive-enumitem + texlive-csquotes + texlive-float + texlive-floatrow + texlive-biblatex + texlive-biber + texlive-pgfplots + texlive-trimspaces + texlive-catchfile + texlive-hyphen-complete + texlive-capt-of + texlive-minted + texlive-titlesec + texlive-titling + texlive-scheme-basic + texlive-fontspec + texlive-beamer + texlive-microtype + texlive-siunitx + texlive-textpos + texlive-mathspec + texlive-etoolbox + texlive-extsizes + texlive-cm-super + texlive-amsmath + texlive-transparent + texlive-ucs + texlive-ulem + texlive-algorithms + texlive-algorithmicx)) diff --git a/src/dictionary.c b/src/dictionary.c new file mode 100644 index 0000000..291c200 --- /dev/null +++ b/src/dictionary.c @@ -0,0 +1,234 @@ +#include +#include +#include +#include +#include +#include +#include +#include "utils.h" +#include "hash-table.h" +#include "red-black-tree.h" + +#define MENU_ENTRIES_GENERAL(X, ...) \ + X(__VA_ARGS__, EXIT, "EXIT") + +#define MENU_ENTRIES_HASH_TABLE(X, ...) \ + X(__VA_ARGS__, PRINT, "PRINT" ) \ + X(__VA_ARGS__, INSERT, "INSERT" ) \ + X(__VA_ARGS__, DELETE, "DELETE" ) \ + X(__VA_ARGS__, SEARCH, "SEARCH" ) \ + X(__VA_ARGS__, CLEAR, "CLEAR" ) \ + X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE") + +#define MENU_ENTRIES_RED_BLACK_TREE(X, ...) \ + X(__VA_ARGS__, PRINT, "PRINT" ) \ + X(__VA_ARGS__, INSERT, "INSERT" ) \ + X(__VA_ARGS__, DELETE, "DELETE" ) \ + X(__VA_ARGS__, SEARCH, "SEARCH" ) \ + X(__VA_ARGS__, CLEAR, "CLEAR" ) \ + X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE") + +#define MENU_ENTRY_ENUM(PREFIX, SYMBOL, ...) PREFIX ## _ ## SYMBOL, + +enum menu_entry { + MENU_ENTRIES_GENERAL (MENU_ENTRY_ENUM, GENERAL ) + MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_ENUM, HASH_TABLE ) + MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_ENUM, RED_BLACK_TREE) + MENU_ENTRY_COUNT +}; + +#define MENU_ENTRY_LABEL(SYMBOL_PREFIX, LABEL_PREFIX, SYMBOL, LABEL, ...) \ + [SYMBOL_PREFIX ## _ ## SYMBOL] = LABEL_PREFIX LABEL, + +const char *menu_entry_labels[MENU_ENTRY_COUNT] = { + MENU_ENTRIES_GENERAL (MENU_ENTRY_LABEL, GENERAL, "GENERAL:.........") + MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_LABEL, HASH_TABLE, "HASH-TABLE:......") + MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_LABEL, RED_BLACK_TREE, "RED-BLACK-TREE:..") +}; + +static inline uint8_t +log10u8 (uint8_t value) +{ + return ((value >= 100u) ? 2 : + (value >= 10u) ? 1 + : 0); +} + +static inline void +input_line (const char *what, char **line, size_t *line_size) +{ + printf ("%s: ", what); + size_t length = getline (line, line_size, stdin); + (*line)[length - 1] = '\0'; +} + +static inline char *input_word () +{ + static char *word = NULL; + static size_t word_size = 0; + + input_line ("WORD", &word, &word_size); + return word; +} + +static inline char *input_filename () +{ + static char *filename = NULL; + static size_t filename_size = 0; + + input_line ("FILENAME", &filename, &filename_size); + return filename; +} + +static void +load_from_file (const char *filename, + void (*inserter) (void *context, const char *key, const char *value), + void *context) +{ + static char *line = NULL; + static size_t line_size = 0; + static size_t line_length = 0; + + FILE *stream = fopen (filename, "r"); + if (!stream) { + puts ("UNABLE TO OPEN FILE FOR READING"); + return; + } + + size_t entry_count = 0; + wchar_t wword[1024]; + char word[2048]; + for (;;) { + wint_t wc; + do wc = fgetwc (stream); + while (wc != WEOF && !wcschr (L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", wc)); + ungetwc (wc, stream); + + if (fwscanf (stream, L"%l[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ]", wword) != 1) + break; + + for (wchar_t *head = wword; *head; ++head) + *head = towlower (*head); + + wcstombs (word, wword, 2048); + inserter (context, strdup (word), strdup ("")); + entry_count += 1; + } fclose (stream); + + printf ("FILE LOADED (%zu ENTRIES)\n", entry_count); +} + +int +main (void) +{ + setlocale (LC_ALL, ""); + + // HASH_TABLE hash_table = hash_table_init (193); + HASH_TABLE hash_table = hash_table_init (13); + RED_BLACK_TREE red_black_tree = red_black_tree_init (); + + load_from_file ("dictionary.txt", (void *) hash_table_insert, hash_table); + load_from_file ("dictionary.txt", (void *) red_black_tree_insert, red_black_tree); + + static char *line = NULL; + static size_t line_size = 0; + for (;;) { + enum menu_entry selection = MENU_ENTRY_COUNT; + do { + printf ("\nSELECT:\n"); + for (enum menu_entry entry = 0; entry < MENU_ENTRY_COUNT; ++entry) { + printf (" [%0*u] %s\n", log10u8 (MENU_ENTRY_COUNT) + 1, entry, + menu_entry_labels[entry]); + } printf ("> "); + getline (&line, &line_size, stdin); + + sscanf (line, "%u", &selection); + } while (selection == MENU_ENTRY_COUNT); + + switch (selection) { + case GENERAL_EXIT: { + puts ("EXITING..."); + hash_table_free (hash_table); + red_black_tree_free (red_black_tree); + return EXIT_SUCCESS; + } break; + + case HASH_TABLE_PRINT: { + hash_table_print (hash_table, "hash-table.dot"); + puts ("hash-table.dot:0:0: HASH TABLE PRINTED"); + } break; + + case HASH_TABLE_INSERT: { + const char *word = input_word (); + hash_table_insert (hash_table, word, strdup ("")); + puts ("ENTRY INSERTED"); + } break; + + case HASH_TABLE_DELETE: { + const char *word = input_word (); + if (hash_table_delete (hash_table, word)) + puts ("ENTRY DELETED"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case HASH_TABLE_SEARCH: { + const char *key = input_word (); + const char *value = hash_table_search (hash_table, key); + if (value) + puts ("ENTRY FOUND"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case HASH_TABLE_CLEAR: { + hash_table_clear (hash_table); + puts ("HASH TABLE CLEARED"); + } break; + + case HASH_TABLE_LOAD_FROM_FILE: { + const char *filename = input_filename (); + load_from_file (filename, (void *) hash_table_insert, hash_table); + } break; + + case RED_BLACK_TREE_PRINT: { + red_black_tree_print (red_black_tree, "red-black-tree.dot"); + puts ("red-black-tree.dot:0:0: RED BLACK TREE PRINTED"); + } break; + + case RED_BLACK_TREE_INSERT: { + const char *word = input_word (); + red_black_tree_insert (red_black_tree, word, strdup ("")); + puts ("ENTRY INSERTED"); + } break; + + case RED_BLACK_TREE_DELETE: { + const char *key = input_word (); + if (red_black_tree_delete (red_black_tree, key)) + puts ("ENTRY DELETED"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case RED_BLACK_TREE_SEARCH: { + const char *key = input_word (); + const char *value = red_black_tree_search (red_black_tree, key); + if (value) + puts ("ENTRY FOUND"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case RED_BLACK_TREE_CLEAR: { + red_black_tree_clear (red_black_tree); + puts ("RED BLACK TREE CLEARED"); + } break; + + case RED_BLACK_TREE_LOAD_FROM_FILE: { + const char *filename = input_filename (); + load_from_file (filename, (void *) red_black_tree_insert, red_black_tree); + } break; + default: break; + } + } +} diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..212e9f4 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,56 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/src/hash-table.c b/src/hash-table.c new file mode 100644 index 0000000..7b6c983 --- /dev/null +++ b/src/hash-table.c @@ -0,0 +1,150 @@ +#include "hash-table.h" +#include +#include + +typedef struct entry *ENTRY; +struct entry { + ENTRY next; + char *key; + char *value; +}; + +struct hash_table { + size_t bucket_count; + ENTRY buckets[]; +}; + +// NOTE(cmmm): hash * 33 ^ c might be better +static inline size_t +hash_function_djb2 (const char *str) +{ + size_t hash = 5381; + unsigned char c; + + while ((c = *str++)) + hash = ((hash << 5) + hash) + c; // hash * 33 + c + + return hash; +} + +void +hash_table_print (HASH_TABLE hash_table, const char *filename) +{ + FILE *stream = fopen (filename, "w"); + fprintf (stream, "digraph hash_table {\n"); + fprintf (stream, "\trankdir = LR\n"); + fprintf (stream, "\tnode [shape = record]\n\n"); + size_t entry_idx = 0; + size_t bucket_idx = 0; + for (ENTRY *bucket = hash_table->buckets; + bucket < hash_table->buckets + hash_table->bucket_count; ++bucket) + { + fprintf (stream, "\tbucket%zu [label = \"%zu\"]\n", bucket_idx, bucket_idx); + + size_t saved_idx = entry_idx; + for (ENTRY entry = *bucket; entry; entry = entry->next) + fprintf (stream, "\tentry%zu [label = \"%s\"]\n", entry_idx++, entry->key); + + entry_idx = saved_idx; + for (ENTRY entry = *bucket; entry; entry = entry->next) { + if (entry == *bucket) + fprintf (stream, "\tbucket%zu -> ", bucket_idx); + fprintf (stream, "entry%zu", entry_idx++); + if (entry->next) + fprintf (stream, " -> "); + } fprintf (stream, "\n\n"); + + bucket_idx += 1; + } fprintf (stream, "}\n"); + fclose (stream); +} + +HASH_TABLE +hash_table_init (size_t bucket_count) +{ + HASH_TABLE hash_table = malloc (sizeof (*hash_table) + + bucket_count*sizeof (*hash_table->buckets)); + + hash_table->bucket_count = bucket_count; + memset (hash_table->buckets, 0, + hash_table->bucket_count*sizeof (*hash_table->buckets)); + + return hash_table; +} + +void +hash_table_clear (HASH_TABLE hash_table) +{ + if (!hash_table) + return; + + for (ENTRY *bucket = hash_table->buckets; + bucket < hash_table->buckets + hash_table->bucket_count; ++bucket) { + for (ENTRY entry = *bucket, next; entry; entry = next) { + next = entry->next; + free (entry->key); + free (entry->value); + free (entry); + } *bucket = NULL; + } +} + +void +hash_table_free (HASH_TABLE hash_table) +{ + hash_table_clear (hash_table); + free (hash_table); +} + +void +hash_table_insert (HASH_TABLE hash_table, const char *key, const char *value) +{ + size_t hash = hash_function_djb2 (key) % hash_table->bucket_count; + + ENTRY *entry = &hash_table->buckets[hash]; + while (*entry) { + if (!strcmp (key, (*entry)->key)) { // found + free ((*entry)->value); + (*entry)->value = strdup (value); + return; + } else entry = &(*entry)->next; + } + + // not found + *entry = malloc (sizeof (**entry)); + (*entry)->next = NULL; + (*entry)->key = strdup (key); + (*entry)->value = strdup (value); +} + +bool +hash_table_delete (HASH_TABLE hash_table, const char *key) +{ + size_t hash = hash_function_djb2 (key) % hash_table->bucket_count; + ENTRY *entry = &hash_table->buckets[hash]; + while (*entry) { + if (!strcmp (key, (*entry)->key)) { // found + ENTRY next = (*entry)->next; + + free ((*entry)->key); + free ((*entry)->value); + free (*entry); + + *entry = next; + + return true; + } else entry = &(*entry)->next; + } return false; +} + +const char * +hash_table_search (HASH_TABLE hash_table, const char *key) +{ + size_t hash = hash_function_djb2 (key) % hash_table->bucket_count; + ENTRY entry = hash_table->buckets[hash]; + while (entry) { + if (!strcmp (key, entry->key)) + return entry->value; + else entry = entry->next; + } return NULL; +} diff --git a/src/hash-table.h b/src/hash-table.h new file mode 100644 index 0000000..b8f14bc --- /dev/null +++ b/src/hash-table.h @@ -0,0 +1,18 @@ +#ifndef INCLUDED_HASH_TABLE_H +#define INCLUDED_HASH_TABLE_H + +#include +#include + +typedef struct hash_table *HASH_TABLE; + +HASH_TABLE hash_table_init (size_t bucket_count); +void hash_table_print (HASH_TABLE, const char *filename); +void hash_table_clear (HASH_TABLE); +void hash_table_free (HASH_TABLE); + +void hash_table_insert (HASH_TABLE, const char *key, const char *value); +bool hash_table_delete (HASH_TABLE, const char *key); +const char *hash_table_search (HASH_TABLE, const char *key); + +#endif diff --git a/src/red-black-tree.c b/src/red-black-tree.c new file mode 100644 index 0000000..62be0d8 --- /dev/null +++ b/src/red-black-tree.c @@ -0,0 +1,443 @@ +#include "red-black-tree.h" +#include "dynamic-array.h" +#include +#include +#include +#include + +enum color { + COLOR_RED, + COLOR_BLACK, +}; + +typedef struct node *NODE; +struct node { + enum color color; + NODE parent; + NODE left; + NODE right; + char *key; + char *value; +}; + +struct red_black_tree { + NODE root; +}; + +struct nodes { + NODE *items; + uint32_t count; + uint32_t capacity; +}; + +void +red_black_tree_print (RED_BLACK_TREE red_black_tree, const char *filename) +{ + FILE *file = fopen (filename, "w"); + fprintf (file, "digraph red_black_tree {\n"); + fprintf (file, "\tnode [style = filled, fillcolor = black, fontcolor = white]\n"); + + struct nodes stack1 = {0}; + struct nodes stack2 = {0}; + struct nodes *front_stack = &stack1; + struct nodes *back_stack = &stack2; + if (red_black_tree->root) + DYNAMIC_ARRAY_APPEND (*front_stack, red_black_tree->root); + size_t null_count = 0; + while (front_stack->count) { + DYNAMIC_ARRAY_RESET (*back_stack); + DYNAMIC_ARRAY_FOREACH(node, *front_stack) { + fprintf (file, "\t\"%s\" [fillcolor = %s]\n", (*node)->key, (*node)->color ? "black" : "webmaroon"); + + if ((*node)->left) { + DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->left); + fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->left->key); + } else { + fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count); + fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count); + null_count += 1; + } + + if ((*node)->right) { + DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->right); + fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->right->key); + } else { + fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count); + fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count); + null_count += 1; + } + } SWAP (front_stack, back_stack); + } fprintf (file, "}\n"); + fclose (file); +} + +RED_BLACK_TREE +red_black_tree_init (void) +{ + return calloc (1, sizeof (struct red_black_tree)); +} + +void +red_black_tree_clear (RED_BLACK_TREE red_black_tree) +{ + if (!red_black_tree || !red_black_tree->root) + return; + + struct nodes stack = {0}; + DYNAMIC_ARRAY_APPEND (stack, red_black_tree->root); + while (stack.count) { + NODE node = stack.items[stack.count - 1]; + stack.count -= 1; + + if (node->left) + DYNAMIC_ARRAY_APPEND (stack, node->left); + + if (node->right) + DYNAMIC_ARRAY_APPEND (stack, node->right); + + free (node->key ); + free (node->value); + free (node ); + } red_black_tree->root = NULL; +} + +void +red_black_tree_free (RED_BLACK_TREE red_black_tree) +{ + red_black_tree_clear (red_black_tree); + free (red_black_tree); +} + +static inline void +rotate_left (RED_BLACK_TREE red_black_tree, NODE node) +{ + NODE y = node->right; + if (!y) return; + node->right = y->left; + if (y->left) + y->left->parent = node; + + y->parent = node->parent; + if (!node->parent) { + red_black_tree->root = y; + } else if (node == node->parent->left) { + node->parent->left = y; + } else { + node->parent->right = y; + } + + y->left = node; + node->parent = y; +} + +static inline void +rotate_right (RED_BLACK_TREE red_black_tree, NODE node) +{ + NODE y = node->left; + node->left = y->right; + if (y->right) { + y->right->parent = node; + } + y->parent = node->parent; + if (!node->parent) { + red_black_tree->root = y; + } else if (node == node->parent->right) { + node->parent->right = y; + } else { + node->parent->left = y; + } + y->right = node; + node->parent = y; +} + +void +red_black_tree_insert (RED_BLACK_TREE red_black_tree, + const char *key, const char *value) +{ + // change value if already exists + for (NODE head = red_black_tree->root, next; head; head = next) { + int difference = strcmp (head->key, key); + if (!difference) { + free (head->value); + head->value = strdup (value); + return; + } + next = difference > 0 ? head->left : head->right; + } + + NODE node = calloc (1, sizeof (*node)); + node->key = strdup (key); + node->value = strdup (value); + + // find parent + for (NODE head = red_black_tree->root, next; head; head = next) { + node->parent = head; + next = strcmp (node->key, head->key) < 0 ? head->left + : head->right; + } + + // no parent + if (!node->parent) { + node->color = COLOR_BLACK; + red_black_tree->root = node; + return; + } + + // attach + if (strcmp (node->key, node->parent->key) < 0) { + node->parent->left = node; + } else { + node->parent->right = node; + } + + // no grandparent + if (!node->parent->parent) { + return; + } + + // fix insert + NODE u; + while (node->parent->color == COLOR_RED) { + if (node->parent == node->parent->parent->right) { + u = node->parent->parent->left; // uncle + if (u && u->color == COLOR_RED) { // case 3.1 + u->color = COLOR_BLACK; + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + node = node->parent->parent; + } else { + if (node == node->parent->left) { // case 3.2.2 + node = node->parent; + rotate_right (red_black_tree, node); + } + + // case 3.2.1 + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + rotate_left (red_black_tree, node->parent->parent); + } + } else { + u = node->parent->parent->right; // uncle + + if (u && u->color == COLOR_RED) { // mirror case 3.1 + u->color = COLOR_BLACK; + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + node = node->parent->parent; + } else { + if (node == node->parent->right) { // mirror case 3.2.2 + node = node->parent; + rotate_left (red_black_tree, node); + } + + // mirror case 3.2.1 + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + rotate_right (red_black_tree, node->parent->parent); + } + } + if (node == red_black_tree->root) { + break; + } + } + red_black_tree->root->color = COLOR_BLACK; +} + + +static inline NODE +minimum (NODE node) +{ + if (!node) + return NULL; // patch + + while (node->left) + node = node->left; + + return node; +} + +// https://github.com/xieqing/red-black-tree +bool +red_black_tree_delete (RED_BLACK_TREE red_black_tree, const char *key) +{ + NODE node = NULL; + NODE target = NULL; + NODE child = NULL; + + for (NODE head = red_black_tree->root, next; head; head = next) { + if (!strcmp (head->key, key)) { + node = head; + break; + } + next = strcmp (head->key, key) <= 0 ? head->right : head->left; + } + + if (!node) + return false; + + /* choose node's in-order successor if it has two children */ + if (!node->left || !node->right) { + target = node; + } else { + target = node->right ? minimum (node->right) : node; /* node->right must not be NIL, thus move down */ + + /* data swapped */ + SWAP (node->key, target->key); + SWAP (node->value, target->value); + } + + child = !target->left ? target->right : target->left; /* child may be NIL */ + + /* + * deletion from red-black tree + * 4-children cluster (RED target node) becomes 3-children cluster + * done + * 3-children cluster (RED target node) becomes 2-children cluster + * done + * 3-children cluster (BLACK target node, RED child node) becomes 2-children cluster + * paint child node BLACK, and done + * + * 2-children root cluster (BLACK target node, BLACK child node) becomes 0-children root cluster + * done + * + * 2-children cluster (BLACK target node, 4-children sibling cluster) becomes 3-children cluster + * transfer, and done + * 2-children cluster (BLACK target node, 3-children sibling cluster) becomes 2-children cluster + * transfer, and done + * + * 2-children cluster (BLACK target node, 2-children sibling cluster, 3/4-children parent cluster) becomes 3-children cluster + * fuse, paint parent node BLACK, and done + * 2-children cluster (BLACK target node, 2-children sibling cluster, 2-children parent cluster) becomes 3-children cluster + * fuse, and delete parent node from parent cluster + */ + if (target->color == COLOR_BLACK) { + if (child && child->color == COLOR_RED) { + /* deletion from 3-children cluster (BLACK target node, RED child node) */ + child->color = COLOR_BLACK; + } else if (target == red_black_tree->root) { + /* deletion from 2-children root cluster (BLACK target node, BLACK child node) */ + } else { + /* deletion from 2-children cluster (BLACK target node, ...) */ + // REPAIR + NODE current = target; + NODE sibling; + do { + if (current == current->parent->left) { + sibling = current->parent->right; + + if (sibling && sibling->color == COLOR_RED) { + /* perform an adjustment (3-children parent cluster has two representations) */ + sibling->color = COLOR_BLACK; + current->parent->color = COLOR_RED; + rotate_left (red_black_tree, current->parent); + sibling = current->parent->right; + } + + /* sibling node must be BLACK now */ + if ((!sibling->right || sibling->right->color == COLOR_BLACK) && + (!sibling->left || sibling->left ->color == COLOR_BLACK)) { + /* 2-children sibling cluster, fuse by recoloring */ + sibling->color = COLOR_RED; + if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */ + current->parent->color = COLOR_BLACK; + break; /* goto break */ + } else { /* 2-children parent cluster */ + current = current->parent; /* goto loop */ + } + } else { + /* 3/4-children sibling cluster */ + + /* perform an adjustment (3-children sibling cluster has two representations) */ + if (!sibling->right || sibling->right->color == COLOR_BLACK) { + sibling->left->color = COLOR_BLACK; + sibling->color = COLOR_RED; + rotate_right (red_black_tree, sibling); + sibling = current->parent->right; + } + + /* transfer by rotation and recoloring */ + sibling->color = current->parent->color; + current->parent->color = COLOR_BLACK; + sibling->right->color = COLOR_BLACK; + rotate_left (red_black_tree, current->parent); + break; /* goto break */ + } + } else { + sibling = current->parent->left; + + if (sibling->color == COLOR_RED) { + /* perform an adjustment (3-children parent cluster has two representations) */ + sibling->color = COLOR_BLACK; + current->parent->color = COLOR_RED; + rotate_right (red_black_tree, current->parent); + sibling = current->parent->left; + } + + /* sibling node must be BLACK now */ + + if ((!sibling->right || sibling->right->color == COLOR_BLACK) && + (!sibling->left || sibling->left ->color == COLOR_BLACK)) { + /* 2-children sibling cluster, fuse by recoloring */ + sibling->color = COLOR_RED; + if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */ + current->parent->color = COLOR_BLACK; + break; /* goto break */ + } else { /* 2-children parent cluster */ + current = current->parent; /* goto loop */ + } + } else { + /* 3/4-children sibling cluster */ + + /* perform an adjustment (3-children sibling cluster has two representations) */ + if (!sibling->left || sibling->left->color == COLOR_BLACK) { + sibling->right->color = COLOR_BLACK; + sibling->color = COLOR_RED; + rotate_left (red_black_tree, sibling); + sibling = current->parent->left; + } + + /* transfer by rotation and recoloring */ + sibling->color = current->parent->color; + current->parent->color = COLOR_BLACK; + sibling->left->color = COLOR_BLACK; + rotate_right (red_black_tree, current->parent); + break; /* goto break */ + } + } + } while (current != red_black_tree->root); + } + } else { + /* deletion from 4-children cluster (RED target node) */ + /* deletion from 3-children cluster (RED target node) */ + } + + if (child) + child->parent = target->parent; + + if (target->parent) { + if (target == target->parent->left) + target->parent->left = child; + else if (target == target->parent->right) + target->parent->right = child; + } else { + red_black_tree->root = child; + } + + free (target->key); + free (target->value); + free (target); + + return true; +} + +const char * +red_black_tree_search (RED_BLACK_TREE red_black_tree, const char *key) +{ + for (NODE head = red_black_tree->root, next; head; head = next) { + int difference = strcmp (head->key, key); + if (!difference) return head->value; + next = difference > 0 ? head->left : head->right; + } + + return NULL; +} diff --git a/src/red-black-tree.h b/src/red-black-tree.h new file mode 100644 index 0000000..a18984e --- /dev/null +++ b/src/red-black-tree.h @@ -0,0 +1,17 @@ +#ifndef INCLUDED_RED_BLACK_TREE_H +#define INCLUDED_RED_BLACK_TREE_H + +#include + +typedef struct red_black_tree *RED_BLACK_TREE; + +RED_BLACK_TREE red_black_tree_init (void); +void red_black_tree_print (RED_BLACK_TREE, const char *filename); +void red_black_tree_clear (RED_BLACK_TREE); +void red_black_tree_free (RED_BLACK_TREE); + +void red_black_tree_insert (RED_BLACK_TREE, const char *key, const char *value); +bool red_black_tree_delete (RED_BLACK_TREE, const char *key); +const char *red_black_tree_search (RED_BLACK_TREE, const char *key); + +#endif diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..d4d451f --- /dev/null +++ b/src/utils.h @@ -0,0 +1,21 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) + +#define SWAP(A, B) \ + ({ \ + typeof (A) tmp = (A); \ + (A) = (B); \ + (B) = tmp; \ + }) + +#endif -- cgit v1.3.1