aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 04:42:12 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 04:42:12 +0000
commitf151b796a66adfb1d6b7bf151f2d85fd78cc0a64 (patch)
treeba530b977e6e853d6e1582adbfe1e840d03ffd38
downloadlab-06-master.tar.gz
publishHEADmaster
-rw-r--r--.envrc18
-rw-r--r--.gitignore6
-rw-r--r--README.org152
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild.sh10
-rw-r--r--channels-lock.scm21
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty28
-rw-r--r--doc/gost/gost-7-32-counters.sty37
-rw-r--r--doc/gost/gost-7-32-headings.sty98
-rw-r--r--doc/gost/gost-7-32-lists.sty15
-rw-r--r--doc/gost/gost-7-32-tables.sty29
-rw-r--r--doc/gost/gost-7-32-toc.sty34
-rw-r--r--doc/gost/gost-7-32.cls62
-rw-r--r--doc/ox-init.el32
-rw-r--r--doc/report.org1024
-rw-r--r--doc/setup.org43
-rw-r--r--doc/spbstu-report.cls73
-rw-r--r--manifest.scm52
-rw-r--r--src/dictionary.c234
-rw-r--r--src/dynamic-array.h56
-rw-r--r--src/hash-table.c150
-rw-r--r--src/hash-table.h18
-rw-r--r--src/red-black-tree.c443
-rw-r--r--src/red-black-tree.h17
-rw-r--r--src/utils.h21
26 files changed, 2754 insertions, 0 deletions
diff --git a/.envrc b/.envrc
new file mode 100644
index 0000000..5e9e6bf
--- /dev/null
+++ b/.envrc
@@ -0,0 +1,18 @@
1CHANNELS=./channels-lock.scm
2MANIFEST=./manifest.scm
3LOAD_PATH=./lib
4ROOT=./.guix-shell
5
6TIME_MACHINE_FLAGS+=" --channels=$CHANNELS"
7SHELL_FLAGS+=" --manifest=$MANIFEST"
8SHELL_FLAGS+=" --search-paths"
9SHELL_FLAGS+=" --root=$ROOT"
10SHELL_FLAGS+=" --load-path=$LOAD_PATH"
11
12use_guix_shell() {
13 test -d "$ROOT" && unlink "$ROOT"
14 eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")"
15}
16
17use guix_shell
18export TEXINPUTS=${TEXINPUTS}:./:./gost/
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c3a21e0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
1*.pdf
2*.html
3*.png
4*.dot
5/dictionary
6/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 @@
1#+title: Implementation of a dictionary based on hash tables and red‑black trees
2
3* Task[fn:1]
41. Implement a data structure -- a hash table, which is characterized
5 by the following operations: insertion, deletion, and search.
6 Based on it, implement an application -- a dictionary. As a hash
7 function, you can choose an arbitrary function, for example, taking
8 the first letter of the word. Add The function for completely
9 clearing the dictionary and loading/updating the dictionary from a
10 text file.
112. For the selected text in Russian, build a dictionary based on
12 red‑black trees. Implement functions for adding, deleting, and
13 searching for a word. (use of ready‑made data structures is
14 PROHIBITED!!!). Add a function for completely clearing the
15 dictionary and loading/updating the dictionary from a text file.
16
17The additional implementation also includes the possibility of
18optimizing the dictionary (for example, searching for potential
19cognates in different forms; the simplest criterion is 2/3 of the word
20length). The choice of words to be kept in the dictionary is up to the
21user. It is not allowed to use ready‑made solutions from the STL
22library.
23
24* Documentation
25The exported report can be found at [[https://git.michalec.dev/uni/term-04/graph-theory/lab-06/report.pdf][this link]].
26
27* Showcase
28*Start of the program and the menu:*
29#+begin_example
30HASH-TABLE:......FILE LOADED (159 ENTRIES)
31RED-BLACK-TREE:..FILE LOADED (159 ENTRIES)
32
33SELECT:
34 [00] GENERAL:.........EXIT
35 [01] HASH-TABLE:......PRINT
36 [02] HASH-TABLE:......INSERT
37 [03] HASH-TABLE:......DELETE
38 [04] HASH-TABLE:......SEARCH
39 [05] HASH-TABLE:......CLEAR
40 [06] HASH-TABLE:......LOAD_FROM_FILE
41 [07] RED-BLACK-TREE:..PRINT
42 [08] RED-BLACK-TREE:..INSERT
43 [09] RED-BLACK-TREE:..DELETE
44 [10] RED-BLACK-TREE:..SEARCH
45 [11] RED-BLACK-TREE:..CLEAR
46 [12] RED-BLACK-TREE:..LOAD_FROM_FILE
47>
48#+end_example
49
50*Example output of the PRINT menu items*:
51#+attr_html: :width 400em
52[[https://git.michalec.dev/uni/term-04/graph-theory/lab-06/example-hash-table.png]]
53
54#+attr_html: :width 400em
55[[https://git.michalec.dev/uni/term-04/graph-theory/lab-06/example-red-black-tree.png]]
56
57*Example session:* (menu replaced with # comments)
58 #+begin_src text
59> asdf
60> -1
61> 13
62>
63> 04 # (HASH-TABLE) SEARCH
64WORD: словарь
65ENTRY FOUND
66> 10 # (RED-BLACK-TREE) SEARCH
67WORD: словарь
68ENTRY FOUND
69>
70> 04 # (HASH-TABLE) SEARCH
71WORD: тест
72ENTRY NOT FOUND
73> 10 # (RED-BLACK-TREE) SEARCH
74WORD: тест
75ENTRY NOT FOUND
76> 06 # (HASH-TABLE) LOAD_FROM_FILE
77FILENAME: text
78FILE LOADED (30 ENTRIES)
79> 12 # (RED-BLACK-TREE) LOAD_FROM_FILE
80FILENAME: text
81FILE LOADED (30 ENTRIES)
82> 04 # (HASH-TABLE) SEARCH
83WORD: тест
84ENTRY FOUND
85> 10 # (RED-BLACK-TREE) SEARCH
86WORD: тест
87ENTRY FOUND
88>
89> 02 # (HASH-TABLE) INSERT
90WORD: слово
91ENTRY INSERTED
92> 04 # (HASH-TABLE) SEARCH
93WORD: слово
94ENTRY FOUND
95> 03 # (HASH-TABLE) DELETE
96WORD: слово
97ENTRY DELETED
98> 04 # (HASH-TABLE) SEARCH
99WORD: слово
100ENTRY NOT FOUND
101> 05 # (HASH-TABLE) CLEAR
102HASH TABLE CLEARED
103> 04 # (HASH-TABLE) SEARCH
104WORD: тест
105ENTRY NOT FOUND
106>
107> 08 # (RED-BLACK-TREE) INSERT
108WORD: слово
109ENTRY INSERTED
110> 10 # (RED-BLACK-TREE) SEARCH
111WORD: слово
112ENTRY FOUND
113> 09 # (RED-BLACK-TREE) DELETE
114WORD: слово
115ENTRY DELETED
116> 10 # (RED-BLACK-TREE) SEARCH
117WORD: слово
118ENTRY NOT FOUND
119> 11 # (RED-BLACK-TREE) CLEAR
120HASH TABLE CLEARED
121> 10 # (RED-BLACK-TREE) SEARCH
122WORD: тест
123ENTRY NOT FOUND
124> 00 # (GENERAL) EXIT
125#+end_src
126
127* Unlicense
128#+include: UNLICENSE verse
129
130* Footnotes
131[fn:1] Original text:
132#+HTML: <i>
133#+begin_quote
1341. Реализовать структуру данных -- хеш-таблицу, для которой характерны
135 операции: добавления, удаления и поиска. На ее основе реализовать
136 приложение -- словарь. В качестве хеш-функции, можно выбрать
137 произвольную функцию, например, брать первую букву слова. Добавить
138 функцию полной очистки словаря и загрузки/дополнения словаря из
139 текстового файла.
1402. Для выбранного текста на русском языке построить словарь на основе
141 красно-черных деревьев. Реализовать функции добавления, удаления и
142 поиска слова. (НЕЛЬЗЯ использовать готовые структуры данных!!!).
143 Добавить функцию полной очистки словаря и загрузки/дополнения
144 словаря из текстового файла.
145
146Дополнительная реализация также включает возможность оптимизации
147словаря (например, поиск потенциальных однокоренных слов в разных
148формах; самый простой критерий -- 2/3 длины слова). Выбор слов,
149которые следует оставить в словаре -- за пользователем. Использовать
150готовые решения из библиотеки STL не разрешается.
151#+end_quote
152#+HTML: </i>
diff --git a/UNLICENSE b/UNLICENSE
new file mode 100644
index 0000000..efb9808
--- /dev/null
+++ b/UNLICENSE
@@ -0,0 +1,24 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..2e1600b
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,10 @@
1#!/bin/sh
2
3set +xe
4
5gcc -std=gnu99 -ggdb3 -fanalyzer \
6 -Wall -Wextra -Wpedantic \
7 -Wanalyzer-symbol-too-complex --param=analyzer-max-svalue-depth=20 \
8 -o dictionary src/dictionary.c \
9 src/hash-table.c \
10 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 @@
1(use-modules (guix channels))
2
3(list
4 (channel
5 (name 'guix)
6 (branch "master")
7 (url "https://git.savannah.gnu.org/git/guix.git")
8 (commit "b6dec0108f99d75066bad15aaa124b84bb0261f3")
9 (introduction (make-channel-introduction
10 "d264237d55ca5e2c756cc7a44374a7dbca850505"
11 (openpgp-fingerprint
12 "BBB0 2DDF 2CEA F6A8 0D1D E643 A2A0 6DF2 A33A 54FA"))))
13 (channel
14 (name 'nonguix)
15 (url "https://gitlab.com/nonguix/nonguix")
16 (commit "25bcda2b9107b948a1c858e41aba1b7f95b76228")
17 (introduction
18 (make-channel-introduction
19 "897c1a470da759236cc11798f4e0a5f7d4d59fbc"
20 (openpgp-fingerprint
21 "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 @@
1\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017]
2
3\def\UrlBreaks{\do\/\do-}
4\RequirePackage{url}
5
6\newdimen\bibindent
7\renewenvironment{thebibliography}[1]{
8 \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}%
9 \list{\@biblabel{\@arabic\c@enumiv}}%
10 {\settowidth\labelwidth{\@biblabel{#1}}%
11 \leftmargin\labelwidth
12 \advance\leftmargin\labelsep
13 \@openbib@code
14 \usecounter{enumiv}%
15 \let\p@enumiv\@empty
16 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
17 \sloppy\clubpenalty4000\widowpenalty4000%
18 \sfcode`\.\@m
19}{
20 \setcounter{totalbib}{\c@enumiv}%
21 \def\@noitemerr
22 {\@latex@warning{Empty `thebibliography' environment}}%
23 \endlist
24}
25\renewcommand\@biblabel{}%
26\setlength\bibindent{1.5em}
27
28% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И.
29%\makeatletter
30\renewcommand*{\@biblabel}[1]{\hfill#1.}
31
32
33%
34% Remove References header completely
35% Stolen from original article.cls
36%
37\makeatletter
38\renewenvironment{thebibliography}[1]{%
39% \usection{\refname}%
40% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
41 \list{\@biblabel{\@arabic\c@enumiv}}%
42 {\settowidth\labelwidth{\@biblabel{#1}}%
43 \leftmargin\labelwidth
44 \advance\leftmargin\labelsep
45 \@openbib@code
46 \usecounter{enumiv}%
47 \let\p@enumiv\@empty
48 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
49 \sloppy
50 \clubpenalty4000
51 \@clubpenalty \clubpenalty
52 \widowpenalty4000%
53 \sfcode`\.\@m}
54 {\def\@noitemerr
55 {\@latex@warning{Empty `thebibliography' environment}}%
56 \endlist}
57\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 @@
1\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{caption}
4\RequirePackage{subcaption}
5
6%
7% Table caption aligned to the left with dash as a separator
8%
9\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off}
10
11%
12% Dash as separator in figure caption and centering
13%
14\captionsetup[figure]{labelsep=endash, justification=centering}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, justification=centering}
20
21%
22% Algorithm caption
23%
24\captionsetup[algorithm]{labelsep=endash, justification=centering}
25
26\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}}
27\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}}
28\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 @@
1\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017]
2
3%
4% Values for capital russian letters counter
5%
6\makeatletter
7\newcommand\AlphRus[1]{%
8 \expandafter \@AlphRus \csname c@#1\endcsname
9}
10
11\newcommand\@AlphRus[1]{%
12 \ifcase #1%
13 \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or
14 Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or
15 Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я%
16 \else \@ctrerr
17\fi
18}
19\makeatother
20
21%
22% Values for lowercase russian letters counter
23%
24\makeatletter
25\newcommand\alphRus[1]{%
26 \expandafter \@alphRus \csname c@#1\endcsname
27}
28
29\newcommand\@alphRus[1]{%
30 \ifcase #1%
31 \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or
32 л\or м\or н\or п\or р\or с\or т\or у\or ф\or
33 х\or ц\or ш\or щ\or э\or ю\or я%
34 \else \@ctrerr
35\fi
36}
37\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 @@
1\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{titlesec}
4\RequirePackage{titling}
5\RequirePackage{setspace}
6
7\RequirePackage{gost-7-32-counters}
8
9%
10% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection
11%
12\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{}
13\titlespacing{\section}{0cm}{0cm}{0.5cm}
14
15\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{}
16\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm}
17
18\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent]
19\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm}
20
21%
22% Make special headings, that have their own formatting rules:
23% - centered
24% - all-caps
25% - bold
26%
27% Only three of them must appear in TOC: introduction, conclusion and references
28%
29\newcommand{\introduction}{
30 \addcontentsline{toc}{section}{ВВЕДЕНИЕ}
31 \begin{center}
32 \bfseries\large
33 ВВЕДЕНИЕ
34 \end{center}
35}
36
37\newcommand{\conclusion}{
38 \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ}
39 \begin{center}
40 \bfseries\large
41 ЗАКЛЮЧЕНИЕ
42 \end{center}
43}
44
45\newcommand{\references}{
46 \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}
47 \begin{center}
48 \bfseries\large
49 СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
50 \end{center}
51}
52
53\newcommand{\essay}{
54 \begin{center}
55 \bfseries\large
56 РЕФЕРАТ
57 \end{center}
58}
59
60\newcommand{\definitions}{
61 \begin{center}
62 \bfseries\large
63 ОПРЕДЕЛЕНИЯ
64 \end{center}
65}
66
67\newcommand{\abbreviations}{
68 \begin{center}
69 \bfseries\large
70 ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
71 \end{center}
72}
73
74\newcommand{\defsabbrs}{
75 \begin{center}
76 \bfseries\large
77 ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
78 \end{center}
79}
80
81%
82% Appendices headings. Appendices have autoincrementing number,
83% that is represented with russian letter.
84% This heading must appear in TOC
85%
86\newcounter{appendixcnt}
87\setcounter{appendixcnt}{1}
88
89\renewcommand{\appendix}[1]{
90 \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1}
91 \begin{center}
92 \bfseries\large
93 ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}
94
95 #1
96 \end{center}
97 \stepcounter{appendixcnt}
98}
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 @@
1\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{enumitem}
4\RequirePackage{gost-7-32-counters}
5
6\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1}
7
8\setlist{nosep}
9\setlist[itemize, 1]{label=\textendash}
10\setlist[itemize, 2]{label=\bullet}
11
12\setlist[enumerate, 2]{label=\alphRus*)}
13
14\setlist[1]{wide=\parindent}
15\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 @@
1\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tabularx}
4
5%
6% Center-aligned column with automatic width
7%
8\newcolumntype{Y}{>{\centering\arraybackslash}X}
9
10%
11% Right-aligned column with automatic width
12%
13\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
14
15%
16% Table with designations
17%
18\newenvironment{designations}{
19 \noindent
20 \tabularx{\textwidth}{@{}
21 >{\raggedright \arraybackslash \hsize=0.25\hsize}X
22 >{\centering \arraybackslash \hsize=0.05\hsize}X
23 >{\arraybackslash \hsize=0.70\hsize}X
24 }
25}{
26 \endtabularx
27}
28
29\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 @@
1\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017]
2
3%% \RequirePackage{tocloft}
4\RequirePackage[
5 bookmarks=true,
6 colorlinks=true,
7 unicode=true,
8 urlcolor=black,
9 linkcolor=black,
10 anchorcolor=black,
11 citecolor=black,
12 menucolor=black,
13 filecolor=black
14]{hyperref}
15
16%
17% Set custom font styles
18%
19%% \renewcommand{\cftsecfont}{\normalfont}
20%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
21%% \renewcommand{\cftsecpagefont}{\normalsize}
22%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries}
23%% \renewcommand{\cftaftertoctitle}{\hfill\hfill}
24%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries}
25\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{}
26\titlespacing{\tableofcontents}{0cm}{0cm}{1cm}
27
28%
29% Set indents and line spacing
30%
31%% \setlength{\cftbeforesecskip}{0cm}
32%% \setlength{\cftbeforesubsecskip}{0cm}
33%% \setlength{\cftbeforesubsubsecskip}{0cm}
34%% \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 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017]
3
4%
5% Supported font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12%
13% Set A4 paper format
14%
15\LoadClass[a4paper]{extarticle}
16
17%
18% Use 1.5 line spacing
19%
20\RequirePackage{setspace}
21\spacing{1.5}
22
23%
24% First paragraph indentation
25%
26\RequirePackage{indentfirst}
27\setlength{\parindent}{12.5mm}
28
29%
30% Page margin
31%
32\RequirePackage[
33 left=2.5cm,
34 right=2cm,
35 top=2cm,
36 bottom=2cm,
37 footskip=1cm,
38]{geometry}
39
40%
41% Use TMR-like font
42%
43\RequirePackage{fontspec}
44\RequirePackage{xunicode}
45\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
46\setmainfont{Times New Roman}
47
48%
49% Use russian language
50%
51\RequirePackage[main=russian, english]{babel}
52\babelhyphenation[russian]{}
53
54%
55% gost-7-32 packages
56%
57\RequirePackage{gost-7-32-headings}
58\RequirePackage{gost-7-32-toc}
59\RequirePackage{gost-7-32-lists}
60\RequirePackage{gost-7-32-bibliography}
61\RequirePackage{gost-7-32-captions}
62\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 @@
1;;; ox-init --- Initialization script for async org exprort session
2;;; Commentary:
3;;; Code:
4(org-babel-do-load-languages
5 'org-babel-load-languages
6 '((latex . t)
7 (C . t)))
8
9(require 'ox-extra)
10(ox-extras-activate '(ignore-headlines))
11
12(require 'oc-bibtex)
13
14(setq org-latex-src-block-backend 'minted)
15
16(setq org-latex-bib-compiler "biber")
17
18(setq org-latex-remove-logfiles nil)
19
20(setq org-latex-caption-above '(table src-block special-block))
21
22(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f"
23 "%bib %b"
24 "%latex -shell-escape -interaction nonstopmode -output-directory %o %f"))
25(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
26 ("\\section{%s}" . "\\usection{%s}")
27 ("\\subsection{%s}" . "\\subsection*{%s}")
28 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
29 ("\\paragraph{%s}" . "\\paragraph*{%s}")
30 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
31
32;;; 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 @@
1#+TITLE: Реализация словаря на основе хеш-таблиц и красно-чёрных деревьев
2#+AUTHOR: Михалец Мартин
3#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №6}
4#+LATEX_HEADER: \subject{по дисциплине «Теория графов»}
5#+LATEX_HEADER: \reviewertitle{}\reviewer{Востров Алексей Владимирович}
6#+DATE: 2024
7
8#+SETUPFILE: setup.org
9#+LATEX: \sloppy
10
11* Введение
12:PROPERTIES:
13:UNNUMBERED: t
14:END:
15В данном отчёте представлено описание шестой лабораторной работы по
16дисциплине «Тория графов». Лабораторная работа включает в себя
17реализация словаря на основе хеш-таблицы и красно-чёрного дерева.
18
19Функции, которые применяются к словарю:
201. Печатание словаря в виде графа.
212. Добавление слова в словарь.
223. Удаление слова из словаря.
234. Поиск слова в словаре.
245. Полная очистка словаря.
256. Дополнение словаря из файла.
26
27* Математическое описание
28** Хеш-таблица
29/Хэш-таблица/ --- это структура данных, похожая на ассоциативный массив,
30т.е. хранит пары ключ-значение, где в качестве ключа выступает любой
31объект, для которого можно вычислить его хеш. Интерфейс хеш-таблицы
32предоставляет нам следующие операции:
33- добавление новой пары ключ-значение,
34- поиск значения по ключу,
35- удаление пары ключ-значение по ключу.
36
37На рисунке [[example-hash-table]] приведён пример хеш-таблицы (c 13
38корзинами) словаря с текстом: «Это очередной пример очень простой хеш
39таблицы применяющий функцию хеширования djb2.»
40
41#+name: example-hash-table
42#+caption: Пример хеш-таблицы
43#+attr_latex: :height 16cm
44[[./example-hash-table.pdf]]
45
46*** Хеш-функция
47/Хеш-функция/, или /функция свёртки/ --- функция, преобразующая массив
48входных данных произвольного размера в выходную битовую строку
49определённого (установленного) размера в соответствии с определённым
50алгоритмом. Сила хеш-функции в том, что они один и тот же массив
51всегда превращают в одну и ту же битовую строку, для этого хеш-функция
52должна являться устойчивой. Преобразование, выполняемое хеш-функцией,
53называется хешированием. Исходные (входные) данные называются входным
54массивом, «ключом», «сообщением». Результат преобразования (выходные
55данные) называется «хешем», «хеш-кодом», «хеш-суммой», «сводкой
56сообщения», «свёрткой».
57
58В данной работе применяется устойчивая функция хеширования djb2,
59которая напоминает линейный конгруэнтный метод генерации
60псевдослучайных чисел за счет аккумуляции $X = (a \cdot X) + c$ как
61можно заметить в алгоритме @@latex:\ref{alg:pseudo}@@. Также
62существует альтернативная версия данной хеш-функции, которая вместо
63сложения очередного элемента массива производит побитовое исключающее
64или, что возможно улучает некоторые её качества.
65
66 #+BEGIN_EXPORT latex
67\begin{algorithm}[H]
68 \caption{Вычисление хеш-функции djb2}
69 \label{alg:pseudo}
70 \begin{algorithmic}[1]
71 \setlength{\baselineskip}{5pt}
72 \Procedure {djb2}{$s[0..n]$}
73 \State $h \leftarrow 5381$
74 \For {$i = 0$ to $n$}
75 \State $h \leftarrow 33 \cdot h + s[i]$
76 \EndFor
77 \State \Return $h$
78 \EndProcedure
79 \end{algorithmic}
80\end{algorithm}
81#+END_EXPORT
82
83*** Добавление, удаление и поиск
84/Поиск записи/ --- вычисляется хеш ключа, с помощью функции хеширования,
85чтобы получить индекс корзины. Дальше проходим корзиной пока либо не
86найдём запись с одинаковым ключом, в случае чего возвращаем значение
87записи, или не дойдём до конца, тогда возвращаем информацию об
88отсутствии записи.
89
90/Добавление записи/ --- также как при поиске, но в случае нахождения
91записи с совпадающим ключом переписываем её значение, а в случае её
92отсутствия добавляем её в конец корзины.
93
94/Удаление записи/ --- также как при поиске, но в случае нахождения
95записи с совпадающим ключом удаляем её из корзины, удерживая
96целостность корзины.
97
98*Сложность всех операций составляет:* $\mathcal{O}(1)$, при отсутствии
99коллизии.
100
101*** Разрешение коллизий
102При добавлении нового элемента, хеш-функция может выдать такой
103идентификатор, по которому уже присутствует ключ. В данной реализации
104эта проблема решается методом цепочек. Каждая ячейка корзины содержит
105цепочку пар ключ-значение, соответствующих одному и тому же
106хеш-значению ключа. Коллизии просто приводят к тому, что появляются
107цепочки длиной более одного элемента. Операции поиска или удаления
108элемента требуют просмотра всех элементов соответствующей ему цепочки,
109чтобы найти в ней элемент с заданным ключом. Для добавления элемента
110нужно добавить элемент в конец цепочки. При предположении, что каждый
111элемент может попасть в любую позицию корзины с равной вероятностью и
112независимо от того, куда попал любой другой элемент, среднее время
113работы операции поиска элемента составляет $\mathcal{O}(1+a)$, где $a$
114--- /коэффициент заполнения корзины/.
115
116** Красно-чёрное дерево
117/Красно-чёрное дерево/ --- это самобалансирующееся дерево поиска,
118гарантирующее логарифмический рост высоты дерева в зависимости от
119количества узлов. Бинарное дерево, баланс которого достигается за
120счет поддержания раскраски вершин в два цвета.
121
122Правила окрашивания:
123- корень окрашен в черный цвет;
124- каждый узел покрашен либо в черный, либо в красный цвет;
125- листья покрашены в чёрный цвет;
126- если узел красный, то оба его потомка чёрные.
127
128Для реализации данного вида сбалансированных деревьев, нужно в каждой
129вершине хранить дополнительно 1 бит информации (цвет).
130
131На рисунке [[example-red-black-tree]] приведён пример красно-чёрного
132дерева словаря с текстом: «Это очередной пример очень простого
133красно-чёрного дерева.»
134
135#+name: example-red-black-tree
136#+caption: Пример красно-чёрного дерева
137[[./example-red-black-tree.pdf]]
138
139*** Вставка
1401. Каждый элемент вставляется вместо листа, поэтому для выбора места
141 вставки идём от корня до листа.
1422. Вставляем вместо него новый красный узел без потомков.
1433. Дальше требуется балансировка после вставки.
144
145*Сложность алгоритма:* $\mathcal{O}(\log n)$
146
147*** Балансировка после вставки узла
148При добавлении нового узла происходит проверка соседних
149узлов. Возможны 5 случаев:
150
1511. Если текущий узел --- корень дерева, то добавляемый узел
152 перекрашивается в черный цвет, чтобы соблюдать условия
153 красно-чёрных деревьев.
1542. Если «родитель» текущего узла черный, тогда свойства не нарушаются.
155 Узел можно не перекрашивать.
1563. Если «родитель» и «дядя» красные, то перекрасим «родителя» и «дядю»
157 в чёрный цвет, а «дедушку» --- в красный. При этом число чёрных
158 вершин на любом пути от корня к листьям остаётся прежним. Теперь у
159 текущего красного узла «родитель» чёрного цвета. Нарушение свойств
160 красно-чёрного дерева возможно лишь в одном месте: вершина
161 «дедушка» может иметь красного «родителя». Чтобы этого не
162 произошло рекурсивно выполняется процедура первого случая. В
163 остальных случаях начинает применяться поворот дерева вправо или
164 влево.
1654. Если «дядя» --- чёрная вершина, «родитель» --- красная и текущий
166 узел --- правый потомок, то добавленный узел является левым
167 потомком красной вершины, которая, в свою очередь, является левым
168 потомком своего родителя, правым потомком которой является
169 «дядя». В этом случае достаточно произвести правое вращение и
170 перекрасить две вершины. Процесс перекраски окончится, так как
171 вершина родитель будет после этого чёрной.
1725. Если «дядя» --- чёрная вершина, «родитель» - красная, текущий узел
173 --- левый потомок, то добавленный узел является правым потомком
174 красной вершины, которая, в свою очередь, является левым потомком
175 своего родителя, правым потомком которой является «дядя». В этом
176 случае производится левое вращение, которое сводит это случай к
177 случаю 2, когда добавляемый узел является потомком своего родителя.
178 После вращения глубина, измеренная в чёрных узлах от корня к
179 листьям, остаётся прежней.
180
181*** Удаление
182В процессе удаления вершины могут возникнуть 3 случая в зависимости от
183количества её потомков:
1841. Если у вершины нет потомков, то у её родителя заменяем её на лист.
1852. Если у неё только один потомок, то у её родителя заменяем её на
186 данного потомка.
1873. Если имеются оба потомка, в правой ветке находим минимальную
188 вершину. У такой вершины нет левого потомка. Переставляем эту
189 вершину на место удаляемой.
1904. Дальше требуется балансировка после удаления.
191
192*Сложность алгоритма:* $\mathcal{O}(\log n)$
193
194*** Балансировка после удаления узла
195При удалении красной вершины свойства дерева не нарушаются.
196Балансировка потребуется только при удалении чёрной.
197
1981. Если «брат» этого потомка красный, то делаем вращение вокруг ребра
199 между «отцом» и «братом», тогда «брат» становится родителем «отца».
200 Красим его в чёрный, а «отца» --- в красный цвет.
2012. Если «брат» текущей вершины был чёрным, то требуется рассмотреть
202 еще 3 случая:
203 1. Оба потомка у «брата» чёрные. Красим «брата» в красный цвет и
204 рассматриваем далее «отца» вершины.
205 2. Если у «брата» правый «сын» черный, а левый красный, то
206 перекрашиваем брата и его левого «сына» и делаем вращение.
207 3. Если у брата правый «сын» красный, то перекрашиваем «брата» в
208 цвет отца, его «сын» и «отца» --- в чёрный, делаем вращение и
209 выходим из алгоритма.
210
211*** Поиск
212Поиск в красно-чёрном дереве происходит как и в бинарном дереве.
213Алгоритм начинает от корня дерева, на каждой итерации происходит
214проверка, соответствует ли ключ рассматриваемого узла ключу, который
215мы ищем.
216- Если да, то возвращается узел.
217- Если нет, то происходит сравнение текущего значения ключа и
218 искомого. В зависимости от того больше или меньше переходим в
219 правое или левое поддерево.
220- Алгоритм повторяет вышеперечисленное до тех пор, пока не дойдет до
221 листа, в случае чего возвращается информация об отсутствии такой
222 вершины.
223
224*Сложность алгоритма:* $\mathcal{O}(\log n)$.
225
226* Реализация
227** Хеш-таблица
228Хеш таблица хранится в виде массива указателей на отдельные корзины с
229заголовком их количества (см. листинг [[hash-table-structure]]). Ключ и
230значение простые строки. Полный интерфейс указан в листинге
231[[hash-table-interface]], но ближе будут рассмотрены только основные
232функции хеш-таблиц.
233
234#+name: hash-table-interface
235#+caption: Интерфейс хеш таблицы
236#+begin_src c
237typedef struct hash_table *HASH_TABLE;
238
239HASH_TABLE hash_table_init (size_t bucket_count);
240void hash_table_free (HASH_TABLE);
241void hash_table_clear (HASH_TABLE);
242void hash_table_print (HASH_TABLE, const char *filename);
243void hash_table_insert (HASH_TABLE, const char *key, const char *value);
244bool hash_table_delete (HASH_TABLE, const char *key);
245const char *hash_table_search (HASH_TABLE, const char *key);
246#+end_src
247
248#+name: hash-table-structure
249#+caption: Структура хеш таблицы
250#+begin_src c
251typedef struct entry *ENTRY;
252struct entry {
253 ENTRY next;
254 char *key;
255 char *value;
256};
257
258struct hash_table {
259 size_t bucket_count;
260 ENTRY buckets[];
261};
262#+end_src
263
264Вспомогательная функция хеширования (см. листинг [[hash-table-djb2]])
265вычисляет хеш размера в 64-бит. В её реализации применяется
266оптимизации замены умножения на сдвиг и сложение, хотя оптимизирующий
267компилятор должен этого уметь делать и сам.
268
269#+name: hash-table-djb2
270#+caption: Функция хеширования
271#+begin_src c
272static inline size_t
273hash_function_djb2 (const char *str)
274{
275 size_t hash = 5381;
276 unsigned char c;
277
278 while ((c = *str++))
279 hash = ((hash << 5) + hash) + c; // hash = 33*hash + c
280
281 return hash;
282}
283#+end_src
284
285Все 3 основных операции хеш-таблиц имеют одинаковую структуру
286(см. листинги [[hash-table-insert]]-[[hash-table-search]]), которая позволяет
2872 места различия: запись найдена или не найдена. Поскольку хеш
288таблица владеет всей памятью, которую в себе хранит, то надо аккуратно
289копировать и освобождать нужные записи в нужные моменты.
290
291#+name: hash-table-insert
292#+caption: Функция вставки в хеш-таблицу
293#+begin_src c
294void
295hash_table_insert (HASH_TABLE hash_table, const char *key, const char *value)
296{
297 size_t hash = hash_function_djb2 (key);
298 ENTRY *entry = &hash_table->buckets[hash % hash_table->bucket_count];
299 while (*entry) {
300 if (!strcmp (key, (*entry)->key)) { // found
301 free ((*entry)->value);
302 (*entry)->value = strdup (value);
303 return;
304 } else entry = &(*entry)->next;
305 }
306
307 // not found
308 *entry = malloc (sizeof (**entry));
309 (*entry)->next = NULL;
310 (*entry)->key = strdup (key);
311 (*entry)->value = strdup (value);
312}
313#+end_src
314
315#+name: hash-table-delete
316#+caption: Функция удаления из хеш-таблицы
317#+begin_src c
318bool
319hash_table_delete (HASH_TABLE hash_table, const char *key)
320{
321 size_t hash = hash_function_djb2 (key);
322 ENTRY *entry = &hash_table->buckets[hash % hash_table->bucket_count];
323 while (*entry) {
324 if (!strcmp (key, (*entry)->key)) { // found
325 ENTRY next = (*entry)->next;
326
327 free ((*entry)->key);
328 free ((*entry)->value);
329 free (*entry);
330
331 *entry = next;
332
333 return true;
334 } else entry = &(*entry)->next;
335 } return false; // not found
336}
337#+end_src
338
339#+name: hash-table-search
340#+caption: Функция поиска в хеш-таблицы
341#+begin_src c
342const char *
343hash_table_search (HASH_TABLE hash_table, const char *key)
344{
345 size_t hash = hash_function_djb2 (key);
346 ENTRY entry = hash_table->buckets[hash % hash_table->bucket_count];
347 while (entry) {
348 if (!strcmp (key, entry->key)) // found
349 return entry->value;
350 else entry = entry->next;
351 } return NULL; // not found
352}
353#+end_src
354
355** Красно-чёрное дерево
356Красно-чёрное дерево в виде указателя на его корневой узел
357(см. листинг [[red-black-tree-structure]]). У каждого узла кроме ключа,
358по которому происходит сравнение, также и значение, благодаря чему
359можем данную структура данных является ассоциативной. Поскольку для
360листьев используем чисто ~NULL~ указатель, а не единый экземпляр ~NILL~
361узла, то при проверке на красный цвет надо не забывать сначала
362проверить сам указатель. Полный интерфейс указан в листинге
363[[red-black-tree-interface]], но ближе будут рассмотрены только основные
364функции красно-чёрных деревьев и некоторые вспомогательные функции.
365
366#+name: red-black-tree-interface
367#+caption: Полный интерфейс красно-чёрного дерева
368#+begin_src c
369typedef struct red_black_tree *RED_BLACK_TREE;
370
371RED_BLACK_TREE red_black_tree_init (void);
372void red_black_tree_free (RED_BLACK_TREE);
373void red_black_tree_clear (RED_BLACK_TREE);
374void red_black_tree_print (RED_BLACK_TREE, const char *filename);
375void red_black_tree_insert (RED_BLACK_TREE, const char *key, const char *value);
376bool red_black_tree_delete (RED_BLACK_TREE, const char *key);
377const char *red_black_tree_search (RED_BLACK_TREE, const char *key);
378#+end_src
379
380#+name: red-black-tree-structure
381#+caption: Структура красно-чёрного дерева
382#+begin_src c
383enum color {
384 COLOR_RED,
385 COLOR_BLACK,
386};
387
388typedef struct node *NODE;
389struct node {
390 NODE parent;
391 NODE left;
392 NODE right;
393 enum color color;
394 char *key;
395 char *value;
396};
397
398struct red_black_tree { NODE root; };
399#+end_src
400
401~minimum~ --- функция поиска минимально элемента поддеревья (см. листинг
402[[red-black-tree-minimum]]). Принимает указатель на узел -- корень
403поддеревья, и возвращает указатель на минимальный узел данного
404поддеревья.
405
406#+name: red-black-tree-minimum
407#+caption: Функция поиска минимального узла в поддереве
408#+begin_src c
409static inline NODE
410minimum (NODE node)
411{
412 if (!node)
413 return NULL;
414
415 while (node->left)
416 node = node->left;
417
418 return node;
419}
420#+end_src
421
422~rotate_left~ и ~rotate_right~ --- функции вращения деревья влево и вправо
423относительно одного узла (см. листинги [[red-black-tree-rotate-left]] и
424[[red-black-tree-rotate-right]]). Эти функции принимают указатель на
425структуру красно-чёрного дерева и указатель на узел вращения. Функции
426ничего не возвращают. Эти функции применяются для превращения
427«цепочки» 3 узлов в «треугольник».
428
429#+name: red-black-tree-rotate-left
430#+caption: Вспомогательная функция левого поворота
431#+begin_src c
432static inline void
433rotate_left (RED_BLACK_TREE red_black_tree, NODE node)
434{
435 NODE y = node->right;
436 node->right = y->left;
437 if (y->left)
438 y->left->parent = node;
439 y->parent = node->parent;
440
441 if (!node->parent) {
442 red_black_tree->root = y;
443 } else if (node == node->parent->left) {
444 node->parent->left = y;
445 } else {
446 node->parent->right = y;
447 }
448
449 y->left = node;
450 node->parent = y;
451}
452#+end_src
453
454#+name: red-black-tree-rotate-right
455#+caption: Вспомогательная функция правого поворота
456#+begin_src c
457static inline void
458rotate_right (RED_BLACK_TREE red_black_tree, NODE node)
459{
460 NODE y = node->left;
461 node->left = y->right;
462 if (y->right)
463 y->right->parent = node;
464 y->parent = node->parent;
465
466 if (!node->parent) {
467 red_black_tree->root = y;
468 } else if (node == node->parent->right) {
469 node->parent->right = y;
470 } else {
471 node->parent->left = y;
472 }
473
474 y->right = node;
475 node->parent = y;
476}
477#+end_src
478
479~red_black_tree_insert~ --- функция добавления элемента в дерево
480(см. листинг @@latex:\ref{lst:red-black-tree-insert}@@). Принимает
481строку, ничего не возвращает. Если дерево ещё не содержит элементов,
482то добавленный элемент перекрашивается в чёрный цвет и становится
483корнем дерева. Если элемент с такой строкой уже есть в словаре,
484индекс этого элемента инкрементируется. Если дерево не пустое, то
485находится потенциальный родитель для добавленного элемента, далее,
486исходя из его значения, помещаем принятое значение слева или справа.
487С помощью дополнительных функций поворота и перекраски узлов,
488сохраняются свойства красно-чёрных деревьев.
489
490#+latex: \captionof{listing}{Функция вставки в красно-чёрное дерево\label{lst:red-black-tree-insert}}
491#+begin_src c
492void
493red_black_tree_insert (RED_BLACK_TREE red_black_tree,
494 const char *key, const char *value)
495{
496 // change value if already exists
497 for (NODE head = red_black_tree->root, next; head; head = next) {
498 int difference = strcmp (head->key, key);
499 if (!difference) {
500 free (head->value);
501 head->value = strdup (value);
502 return;
503 }
504 next = difference > 0 ? head->left : head->right;
505 }
506
507 NODE node = calloc (1, sizeof (*node));
508 node->key = strdup (key);
509 node->value = strdup (value);
510
511 // find parent
512 for (NODE head = red_black_tree->root, next; head; head = next) {
513 node->parent = head;
514 next = strcmp (node->key, head->key) < 0 ? head->left
515 : head->right;
516 }
517
518 // no parent
519 if (!node->parent) {
520 node->color = COLOR_BLACK;
521 red_black_tree->root = node;
522 return;
523 }
524
525 // attach
526 if (strcmp (node->key, node->parent->key) < 0) {
527 node->parent->left = node;
528 } else {
529 node->parent->right = node;
530 }
531
532 // no grandparent
533 if (!node->parent->parent)
534 return;
535
536 // fix insert
537 NODE u;
538 while (node->parent->color == COLOR_RED) {
539 if (node->parent == node->parent->parent->right) {
540 u = node->parent->parent->left; // uncle
541 if (u && u->color == COLOR_RED) { // case 3.1
542 u->color = COLOR_BLACK;
543 node->parent->color = COLOR_BLACK;
544 node->parent->parent->color = COLOR_RED;
545 node = node->parent->parent;
546 } else {
547 if (node == node->parent->left) { // case 3.2.2
548 node = node->parent;
549 rotate_right (red_black_tree, node);
550 }
551
552 // case 3.2.1
553 node->parent->color = COLOR_BLACK;
554 node->parent->parent->color = COLOR_RED;
555 rotate_left (red_black_tree, node->parent->parent);
556 }
557 } else {
558 u = node->parent->parent->right; // uncle
559
560 if (u && u->color == COLOR_RED) { // mirror case 3.1
561 u->color = COLOR_BLACK;
562 node->parent->color = COLOR_BLACK;
563 node->parent->parent->color = COLOR_RED;
564 node = node->parent->parent;
565 } else {
566 if (node == node->parent->right) { // mirror case 3.2.2
567 node = node->parent;
568 rotate_left (red_black_tree, node);
569 }
570
571 // mirror case 3.2.1
572 node->parent->color = COLOR_BLACK;
573 node->parent->parent->color = COLOR_RED;
574 rotate_right (red_black_tree, node->parent->parent);
575 }
576 }
577 if (node == red_black_tree->root) {
578 break;
579 }
580 }
581 red_black_tree->root->color = COLOR_BLACK;
582}
583#+end_src
584
585~red_black_tree_delete~ --- функция удаления элемента из дерева
586(см. листинг @@latex:\ref{lst:red-black-tree-delete}@@). Принимает
587строку, возвращает информацию о нахождении записи. Удаление включает
588в себя перестановки узлов, поворот дерева. После удаления сохраняется
589свойство красно-черных деревьев.
590
591#+latex: \captionof{listing}{Функция удаления из красно-чёрного дерева\label{lst:red-black-tree-delete}}
592#+begin_src c
593bool
594red_black_tree_delete (RED_BLACK_TREE red_black_tree, const char *key)
595{
596 NODE node = NULL;
597 NODE target = NULL;
598 NODE child = NULL;
599
600 for (NODE head = red_black_tree->root, next; head; head = next) {
601 if (!strcmp (head->key, key)) {
602 node = head;
603 break;
604 }
605 next = strcmp (head->key, key) <= 0 ? head->right : head->left;
606 }
607
608 if (!node)
609 return false;
610
611 if (!node->left || !node->right) {
612 target = node;
613 } else {
614 target = minimum (node->right);
615
616 SWAP (node->key, target->key);
617 SWAP (node->value, target->value);
618 }
619
620 child = !target->left ? target->right : target->left;
621
622 if (target->color == COLOR_BLACK) {
623 if (child && child->color == COLOR_RED) {
624 // deletion from 3-children cluster (BLACK target node, RED
625 // child node)
626 child->color = COLOR_BLACK;
627 } else if (target == red_black_tree->root) {
628 // deletion from 2-children root cluster (BLACK target node,
629 // BLACK child node)
630 } else { // REBALANCE
631 // deletion from 2-children cluster (BLACK target node, ...)
632 NODE current = target;
633 NODE sibling;
634 do {
635 if (current == current->parent->left) {
636 sibling = current->parent->right;
637 if (sibling && sibling->color == COLOR_RED) {
638 // perform an adjustment (3-children parent cluster has
639 // two representations)
640 sibling->color = COLOR_BLACK;
641 current->parent->color = COLOR_RED;
642 rotate_left (red_black_tree, current->parent);
643 sibling = current->parent->right;
644 }
645
646 // sibling node must be BLACK now
647 if ((!sibling->right || sibling->right->color == COLOR_BLACK) &&
648 (!sibling->left || sibling->left ->color == COLOR_BLACK)) {
649 // 2-children sibling cluster, fuse by recoloring
650 sibling->color = COLOR_RED;
651 if (current->parent->color == COLOR_RED) {
652 current->parent->color = COLOR_BLACK;
653 break;
654 } else {
655 // 2-children parent cluster
656 current = current->parent;
657 }
658 } else {
659 // 3/4-children sibling cluster
660 if (!sibling->right || sibling->right->color == COLOR_BLACK) {
661 // perform an adjustment (3-children sibling cluster has
662 // two representations)
663 sibling->left->color = COLOR_BLACK;
664 sibling->color = COLOR_RED;
665 rotate_right (red_black_tree, sibling);
666 sibling = current->parent->right;
667 }
668
669 // transfer by rotation and recoloring
670 sibling->color = current->parent->color;
671 current->parent->color = COLOR_BLACK;
672 sibling->right->color = COLOR_BLACK;
673 rotate_left (red_black_tree, current->parent);
674 break;
675 }
676 } else {
677 sibling = current->parent->left;
678 if (sibling->color == COLOR_RED) {
679 // perform an adjustment (3-children parent cluster has
680 // two representations)
681 sibling->color = COLOR_BLACK;
682 current->parent->color = COLOR_RED;
683 rotate_right (red_black_tree, current->parent);
684 sibling = current->parent->left;
685 }
686
687 // sibling node must be BLACK now
688 if ((!sibling->right || sibling->right->color == COLOR_BLACK) &&
689 (!sibling->left || sibling->left ->color == COLOR_BLACK)) {
690 // 2-children sibling cluster, fuse by recoloring
691 sibling->color = COLOR_RED;
692 if (current->parent->color == COLOR_RED) {
693 // 3/4-children parent cluster
694 current->parent->color = COLOR_BLACK;
695 break;
696 } else current = current->parent;
697 } else {
698 // 3/4-children sibling cluster
699 if (!sibling->left || sibling->left->color == COLOR_BLACK) {
700 // perform an adjustment (3-children sibling cluster has
701 // two representations)
702 sibling->right->color = COLOR_BLACK;
703 sibling->color = COLOR_RED;
704 rotate_left (red_black_tree, sibling);
705 sibling = current->parent->left;
706 }
707
708 // transfer by rotation and recoloring
709 sibling->color = current->parent->color;
710 current->parent->color = COLOR_BLACK;
711 sibling->left->color = COLOR_BLACK;
712 rotate_right (red_black_tree, current->parent);
713 break;
714 }
715 }
716 } while (current != red_black_tree->root);
717 }
718 } else {
719 // deletion from 4-children cluster (RED target node)
720 // deletion from 3-children cluster (RED target node)
721 }
722
723 if (child)
724 child->parent = target->parent;
725
726 if (target->parent) {
727 if (target == target->parent->left)
728 target->parent->left = child;
729 else if (target == target->parent->right)
730 target->parent->right = child;
731 } else {
732 red_black_tree->root = child;
733 }
734
735 free (target->key);
736 free (target->value);
737 free (target);
738
739 return true;
740}
741#+end_src
742
743~red_black_tree_search~ --- функция поиска элемента в дереве
744(см. листинг [[red-black-tree-search]]). принимает строку -- ключ,
745возвращает строку -- значение.
746
747#+name: red-black-tree-search
748#+caption: Функция поиска в красно-чёрном дереве
749#+begin_src c
750const char *
751red_black_tree_search (RED_BLACK_TREE red_black_tree, const char *key)
752{
753 for (NODE head = red_black_tree->root, next; head; head = next) {
754 int difference = strcmp (head->key, key);
755 if (!difference) return head->value;
756 next = difference > 0 ? head->left : head->right;
757 }
758
759 return NULL;
760}
761#+end_src
762
763** Приложение словарь
764Вся суть приложения в обработке простого меню, она приведена в
765листинге @@latex:\ref{lst:dictionary-menu}@@. Есть несколько операции
766по хеш-таблицы и красно-чёрном дереве, в данном листинге видно их
767применение в качестве словарей.
768
769#+latex: \captionof{listing}{Обработка меню словаря\label{lst:dictionary-menu}}
770#+begin_src c
771switch (selection) {
772 case GENERAL_EXIT: {
773 puts ("EXITING...");
774 hash_table_free (hash_table);
775 red_black_tree_free (red_black_tree);
776 return EXIT_SUCCESS;
777 } break;
778
779 case HASH_TABLE_PRINT: {
780 hash_table_print (hash_table, "hash-table.dot");
781 puts ("hash-table.dot:0:0: HASH TABLE PRINTED");
782 } break;
783
784 case HASH_TABLE_INSERT: {
785 const char *word = input_word ();
786 hash_table_insert (hash_table, word, strdup (""));
787 puts ("ENTRY INSERTED");
788 } break;
789
790 case HASH_TABLE_DELETE: {
791 const char *word = input_word ();
792 if (hash_table_delete (hash_table, word))
793 puts ("ENTRY DELETED");
794 else
795 puts ("ENTRY NOT FOUND");
796 } break;
797
798 case HASH_TABLE_SEARCH: {
799 const char *key = input_word ();
800 const char *value = hash_table_search (hash_table, key);
801 if (value)
802 puts ("ENTRY FOUND");
803 else
804 puts ("ENTRY NOT FOUND");
805 } break;
806
807 case HASH_TABLE_CLEAR: {
808 hash_table_clear (hash_table);
809 puts ("HASH TABLE CLEARED");
810 } break;
811
812 case HASH_TABLE_LOAD_FROM_FILE: {
813 const char *filename = input_filename ();
814 load_from_file (filename, (void *) hash_table_insert, hash_table);
815 } break;
816
817 case RED_BLACK_TREE_PRINT: {
818 red_black_tree_print (red_black_tree, "red-black-tree.dot");
819 puts ("red-black-tree.dot:0:0: RED BLACK TREE PRINTED");
820 } break;
821
822 case RED_BLACK_TREE_INSERT: {
823 const char *word = input_word ();
824 red_black_tree_insert (red_black_tree, word, strdup (""));
825 puts ("ENTRY INSERTED");
826 } break;
827
828 case RED_BLACK_TREE_DELETE: {
829 const char *key = input_word ();
830 if (red_black_tree_delete (red_black_tree, key))
831 puts ("ENTRY DELETED");
832 else
833 puts ("ENTRY NOT FOUND");
834 } break;
835
836 case RED_BLACK_TREE_SEARCH: {
837 const char *key = input_word ();
838 const char *value = red_black_tree_search (red_black_tree, key);
839 if (value)
840 puts ("ENTRY FOUND");
841 else
842 puts ("ENTRY NOT FOUND");
843 } break;
844
845 case RED_BLACK_TREE_CLEAR: {
846 red_black_tree_clear (red_black_tree);
847 puts ("RED BLACK TREE CLEARED");
848 } break;
849
850 case RED_BLACK_TREE_LOAD_FROM_FILE: {
851 const char *filename = input_filename ();
852 load_from_file (filename, (void *) red_black_tree_insert, red_black_tree);
853 } break;
854 default: break;
855}
856#+end_src
857
858* Результаты работы
859В результаты работы также входят сгенерированные коммандой =PRINT= графы
860[[example-hash-table]] и [[example-red-black-tree]].
861
862Начало работы программы и меню:
863#+begin_src text
864HASH-TABLE:......FILE LOADED (159 ENTRIES)
865RED-BLACK-TREE:..FILE LOADED (159 ENTRIES)
866
867SELECT:
868 [00] GENERAL:.........EXIT
869 [01] HASH-TABLE:......PRINT
870 [02] HASH-TABLE:......INSERT
871 [03] HASH-TABLE:......DELETE
872 [04] HASH-TABLE:......SEARCH
873 [05] HASH-TABLE:......CLEAR
874 [06] HASH-TABLE:......LOAD_FROM_FILE
875 [07] RED-BLACK-TREE:..PRINT
876 [08] RED-BLACK-TREE:..INSERT
877 [09] RED-BLACK-TREE:..DELETE
878 [10] RED-BLACK-TREE:..SEARCH
879 [11] RED-BLACK-TREE:..CLEAR
880 [12] RED-BLACK-TREE:..LOAD_FROM_FILE
881>
882 #+end_src
883
884Пример сеанса без меню, но с комментариями после =#=:
885 #+begin_src text
886> asdf
887> -1
888> 13
889>
890> 04 # (HASH-TABLE) SEARCH
891WORD: словарь
892ENTRY FOUND
893> 10 # (RED-BLACK-TREE) SEARCH
894WORD: словарь
895ENTRY FOUND
896>
897> 04 # (HASH-TABLE) SEARCH
898WORD: тест
899ENTRY NOT FOUND
900> 10 # (RED-BLACK-TREE) SEARCH
901WORD: тест
902ENTRY NOT FOUND
903> 06 # (HASH-TABLE) LOAD_FROM_FILE
904FILENAME: text
905FILE LOADED (30 ENTRIES)
906> 12 # (RED-BLACK-TREE) LOAD_FROM_FILE
907FILENAME: text
908FILE LOADED (30 ENTRIES)
909> 04 # (HASH-TABLE) SEARCH
910WORD: тест
911ENTRY FOUND
912> 10 # (RED-BLACK-TREE) SEARCH
913WORD: тест
914ENTRY FOUND
915>
916> 02 # (HASH-TABLE) INSERT
917WORD: слово
918ENTRY INSERTED
919> 04 # (HASH-TABLE) SEARCH
920WORD: слово
921ENTRY FOUND
922> 03 # (HASH-TABLE) DELETE
923WORD: слово
924ENTRY DELETED
925> 04 # (HASH-TABLE) SEARCH
926WORD: слово
927ENTRY NOT FOUND
928> 05 # (HASH-TABLE) CLEAR
929HASH TABLE CLEARED
930> 04 # (HASH-TABLE) SEARCH
931WORD: тест
932ENTRY NOT FOUND
933>
934> 08 # (RED-BLACK-TREE) INSERT
935WORD: слово
936ENTRY INSERTED
937> 10 # (RED-BLACK-TREE) SEARCH
938WORD: слово
939ENTRY FOUND
940> 09 # (RED-BLACK-TREE) DELETE
941WORD: слово
942ENTRY DELETED
943> 10 # (RED-BLACK-TREE) SEARCH
944WORD: слово
945ENTRY NOT FOUND
946> 11 # (RED-BLACK-TREE) CLEAR
947HASH TABLE CLEARED
948> 10 # (RED-BLACK-TREE) SEARCH
949WORD: тест
950ENTRY NOT FOUND
951> 00 # (GENERAL) EXIT
952#+end_src
953
954* Заключение
955:PROPERTIES:
956:UNNUMBERED: t
957:END:
958В результате работы были, на языке программирования Си, реализованы:
959- словарь на основе хэш-таблицы,
960- словарь на основе красно-черного дерева,
961- операции поиска, добавления и удаления записи,
962- а также операции полной очистки и загрузки словаря из файла.
963
964Если сравнить хеш-таблицы с красно-чёрными деревьями чисто по
965сложности их основных алгоритмов, при условии, что хеш-таблица не
966слишком заполнена, то очевидно, что алгоритмы над хеш-таблицами будут
967работать быстрее, но при очень малом заполнении хеш-таблицы будет
968выделено в пустую много памяти. Этот проблем хеш-таблиц можно решить
969способом похожим на балансировку дерева, удерживая хеш-таблицу
970оптимально заполненной, но в данной работе эта проблема не
971затрагивалась. Хеш-таблицы могут в принципе занимать меньше памяти,
972при хранении одинакового количества объектов, за счет того, что их
973объекты требуют только одного дополнительного указателя, когда в то же
974время красно-чёрные деревья требуют три дополнительных указателя и
975один бит для цвета, который в большинстве реализации будет занимать
976размер указателя, за счет выравнивания структур, но его можно хранить,
977например, в одном из обязательных указателей. Красно-чёрные деревья,
978и в общем бинарные дерева поиска, имеют одно выделяющееся преимущество
979над хеш-таблицами --- над объектами хранящимися в них можно эффективно
980пройти в упорядоченном порядке.
981
982*Достоинства программы:*
983- Возможность записи хеш-таблиц и красно-чёрных деревьев в =dot= формате
984 для графической визуализации, что сильно помогло при отладке
985 операции над красно-чёрным деревом.
986- Простая и наглядная реализация, что позволяет её использовать почти
987 в качестве псевдокода.
988
989*Недостатки программы:*
990- Освобождение памяти словарей имеет сложность $\mathcal{O}(n)$,
991 стоило бы рассмотреть применение арены распределителя памяти для
992 понижения сложности до $\mathcal{O}(1)$.
993- Хеш-таблица имеет фиксированное при сборке количество корзин, что
994 может быть проблемно, поскольку хеш-таблицы работают эффективно до
995 80% заполнения.
996- Были использованы наивные реализации обоих структур данных, поэтому
997 они не очень гибкие и эффективные.
998
999*Масштабирование программы:*
1000- Добавление возможности поиска однокоренных слов.
1001- Добавление выбора метода хэш-функции, для хеш-таблицы.
1002
1003* Используемая литература
1004:PROPERTIES:
1005:UNNUMBERED: t
1006:END:
10071. Hash table --- Википедия // URL:
1008 [[https://en.wikipedia.org/wiki/Hash_table]] (Дата обращения:
1009 22.05.2024)
10102. Hash function --- Википедия // URL:
1011 [[https://en.wikipedia.org/wiki/Hash_function]] (Дата обращения:
1012 22.05.2024)
10133. Linear congruential generator --- Википедия // URL:
1014 [[https://en.wikipedia.org/wiki/Linear_congruential_generator]] (Дата обращения:
1015 22.05.2024)
10164. Red–black tree --- Википедия // URL:
1017 [[https://en.wikipedia.org/wiki/Red%E2%80%93black_tree]] (Дата обращения:
1018 22.05.2024)
1019
1020# Local Variables:
1021# org-confirm-babel-evaluate: nil
1022# org-export-async-init-file: "ox-init.el"
1023# org-export-in-background: t
1024# 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 @@
1#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline
2#+OPTIONS: author:t broken-links:nil c:nil creator:nil
3#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t
4#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t
5#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t
6#+SELECT_TAGS: export
7#+EXCLUDE_TAGS: noexport
8#+CREATOR: Emacs 29.1 (Org mode 9.6.9)
9#+BIBLIOGRAPHY: biblio.bib
10#+CITE_EXPORT: biblatex
11#+LATEX_COMPILER: xelatex
12#+LATEX_CLASS: spbstu-report
13# #+LATEX_CLASS_OPTIONS: [draft]
14#+LATEX_HEADER: \usepackage{enumitem}
15#+LATEX_HEADER: \usepackage{array}
16#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type
17# #+LATEX_HEADER: \usepackage{float}
18#+LATEX_HEADER: \usepackage{tikz}
19#+LATEX_HEADER: \usepackage{pgfplots}
20#+LATEX_HEADER: \pgfplotsset{compat=1.18}
21#+LATEX_HEADER: \usepackage{afterpage}
22#+LATEX_HEADER: \usepackage{floatrow}
23#+LATEX_HEADER: \usepackage{minted}
24#+LATEX_HEADER: \floatsetup[listing]{style=Plaintop}
25#+LATEX_HEADER: \floatsetup[algorithm]{style=Plaintop}
26#+LATEX_HEADER: \usemintedstyle{bw}
27#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines}
28#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
29#+LATEX_HEADER: \usepackage[plain]{algorithm}
30#+LATEX_HEADER: \usepackage{algpseudocode}
31#+LATEX_HEADER: \makeatletter
32#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм}
33#+LATEX_HEADER: \makeatother
34#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
35#+LATEX_HEADER: \setmainfont{Times New Roman}
36#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff]
37#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}}
38#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label}
39#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}}
40#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt}
41#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt}
42#+LATEX_HEADER: \hypersetup{hidelinks}
43#+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 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов]
3
4%
5% Support font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12\LoadClass[a4paper]{gost-7-32}
13
14\RequirePackage{csquotes}
15\RequirePackage{amsmath}
16\RequirePackage{adjustbox}
17\RequirePackage{setspace}
18
19\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}}
20
21\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
22\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
23\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
24\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
25\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
26\renewcommand{\maketitle}{
27 \begin{titlepage}
28 \begin{center}
29 \vspace{2cm}
30 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
31
32 \normalsize{Федеральное государственное автономное
33 образовательное учреждение высшего образования
34 \enquote{Санкт-Петербургский политехнический университет Петра Великого}}
35
36 \vspace{0.5cm}
37 \normalsize{Институт компьютерных наук и кибербезопасности}
38
39 \normalsize{Высшая школа технологии искусственного интеллекта}
40
41 \normalsize{Направление 02.03.01 Математика и компьютерные науки}
42
43 \vspace{2cm}
44 \LARGE{ОТЧЁТ}
45
46 \normalsize{\@reportof}
47
48 \large{\@subject}
49
50 \large{\textit{\@title}}
51 \end{center}
52
53 \vspace{3cm}
54 \small{
55 \begin{tabular}{lrrl}
56 \!\!\!Студент, & \hspace{2cm} & & \\
57 \!\!\!группы 5130201/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\
58 \!\!\!Преподаватель, & \hspace{2cm} & \\
59 \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\
60 &&\hspace{5cm}
61 \end{tabular}
62 \begin{flushright}
63 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
64 \end{flushright}
65 }
66
67 \vspace*{\fill}
68 \begin{center}
69 \small{Санкт-Петербург, \@date}
70 \end{center}
71 \end{titlepage}
72 \setcounter{page}{2}
73}
diff --git a/manifest.scm b/manifest.scm
new file mode 100644
index 0000000..beca593
--- /dev/null
+++ b/manifest.scm
@@ -0,0 +1,52 @@
1(use-modules (gnu packages base)
2 (gnu packages commencement)
3 (gnu packages tex)
4 (nongnu packages fonts))
5
6(packages->manifest (list
7 gcc-toolchain
8 font-microsoft-times-new-roman
9 texlive-scheme-small
10 texlive-lh
11 texlive-cm
12 texlive-type1cm
13 texlive-ec
14 texlive-wrapfig
15 texlive-adjustbox
16 texlive-graphics
17 texlive-hyperref
18 texlive-latex-fonts
19 texlive-amsfonts
20 texlive-cyrillic
21 texlive-babel-russian
22 texlive-geometry
23 texlive-enumitem
24 texlive-csquotes
25 texlive-float
26 texlive-floatrow
27 texlive-biblatex
28 texlive-biber
29 texlive-pgfplots
30 texlive-trimspaces
31 texlive-catchfile
32 texlive-hyphen-complete
33 texlive-capt-of
34 texlive-minted
35 texlive-titlesec
36 texlive-titling
37 texlive-scheme-basic
38 texlive-fontspec
39 texlive-beamer
40 texlive-microtype
41 texlive-siunitx
42 texlive-textpos
43 texlive-mathspec
44 texlive-etoolbox
45 texlive-extsizes
46 texlive-cm-super
47 texlive-amsmath
48 texlive-transparent
49 texlive-ucs
50 texlive-ulem
51 texlive-algorithms
52 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 @@
1#include <stdlib.h>
2#include <stdio.h>
3#include <stdint.h>
4#include <string.h>
5#include <wchar.h>
6#include <wctype.h>
7#include <locale.h>
8#include "utils.h"
9#include "hash-table.h"
10#include "red-black-tree.h"
11
12#define MENU_ENTRIES_GENERAL(X, ...) \
13 X(__VA_ARGS__, EXIT, "EXIT")
14
15#define MENU_ENTRIES_HASH_TABLE(X, ...) \
16 X(__VA_ARGS__, PRINT, "PRINT" ) \
17 X(__VA_ARGS__, INSERT, "INSERT" ) \
18 X(__VA_ARGS__, DELETE, "DELETE" ) \
19 X(__VA_ARGS__, SEARCH, "SEARCH" ) \
20 X(__VA_ARGS__, CLEAR, "CLEAR" ) \
21 X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE")
22
23#define MENU_ENTRIES_RED_BLACK_TREE(X, ...) \
24 X(__VA_ARGS__, PRINT, "PRINT" ) \
25 X(__VA_ARGS__, INSERT, "INSERT" ) \
26 X(__VA_ARGS__, DELETE, "DELETE" ) \
27 X(__VA_ARGS__, SEARCH, "SEARCH" ) \
28 X(__VA_ARGS__, CLEAR, "CLEAR" ) \
29 X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE")
30
31#define MENU_ENTRY_ENUM(PREFIX, SYMBOL, ...) PREFIX ## _ ## SYMBOL,
32
33enum menu_entry {
34 MENU_ENTRIES_GENERAL (MENU_ENTRY_ENUM, GENERAL )
35 MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_ENUM, HASH_TABLE )
36 MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_ENUM, RED_BLACK_TREE)
37 MENU_ENTRY_COUNT
38};
39
40#define MENU_ENTRY_LABEL(SYMBOL_PREFIX, LABEL_PREFIX, SYMBOL, LABEL, ...) \
41 [SYMBOL_PREFIX ## _ ## SYMBOL] = LABEL_PREFIX LABEL,
42
43const char *menu_entry_labels[MENU_ENTRY_COUNT] = {
44 MENU_ENTRIES_GENERAL (MENU_ENTRY_LABEL, GENERAL, "GENERAL:.........")
45 MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_LABEL, HASH_TABLE, "HASH-TABLE:......")
46 MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_LABEL, RED_BLACK_TREE, "RED-BLACK-TREE:..")
47};
48
49static inline uint8_t
50log10u8 (uint8_t value)
51{
52 return ((value >= 100u) ? 2 :
53 (value >= 10u) ? 1
54 : 0);
55}
56
57static inline void
58input_line (const char *what, char **line, size_t *line_size)
59{
60 printf ("%s: ", what);
61 size_t length = getline (line, line_size, stdin);
62 (*line)[length - 1] = '\0';
63}
64
65static inline char *input_word ()
66{
67 static char *word = NULL;
68 static size_t word_size = 0;
69
70 input_line ("WORD", &word, &word_size);
71 return word;
72}
73
74static inline char *input_filename ()
75{
76 static char *filename = NULL;
77 static size_t filename_size = 0;
78
79 input_line ("FILENAME", &filename, &filename_size);
80 return filename;
81}
82
83static void
84load_from_file (const char *filename,
85 void (*inserter) (void *context, const char *key, const char *value),
86 void *context)
87{
88 static char *line = NULL;
89 static size_t line_size = 0;
90 static size_t line_length = 0;
91
92 FILE *stream = fopen (filename, "r");
93 if (!stream) {
94 puts ("UNABLE TO OPEN FILE FOR READING");
95 return;
96 }
97
98 size_t entry_count = 0;
99 wchar_t wword[1024];
100 char word[2048];
101 for (;;) {
102 wint_t wc;
103 do wc = fgetwc (stream);
104 while (wc != WEOF && !wcschr (L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", wc));
105 ungetwc (wc, stream);
106
107 if (fwscanf (stream, L"%l[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ]", wword) != 1)
108 break;
109
110 for (wchar_t *head = wword; *head; ++head)
111 *head = towlower (*head);
112
113 wcstombs (word, wword, 2048);
114 inserter (context, strdup (word), strdup (""));
115 entry_count += 1;
116 } fclose (stream);
117
118 printf ("FILE LOADED (%zu ENTRIES)\n", entry_count);
119}
120
121int
122main (void)
123{
124 setlocale (LC_ALL, "");
125
126 // HASH_TABLE hash_table = hash_table_init (193);
127 HASH_TABLE hash_table = hash_table_init (13);
128 RED_BLACK_TREE red_black_tree = red_black_tree_init ();
129
130 load_from_file ("dictionary.txt", (void *) hash_table_insert, hash_table);
131 load_from_file ("dictionary.txt", (void *) red_black_tree_insert, red_black_tree);
132
133 static char *line = NULL;
134 static size_t line_size = 0;
135 for (;;) {
136 enum menu_entry selection = MENU_ENTRY_COUNT;
137 do {
138 printf ("\nSELECT:\n");
139 for (enum menu_entry entry = 0; entry < MENU_ENTRY_COUNT; ++entry) {
140 printf (" [%0*u] %s\n", log10u8 (MENU_ENTRY_COUNT) + 1, entry,
141 menu_entry_labels[entry]);
142 } printf ("> ");
143 getline (&line, &line_size, stdin);
144
145 sscanf (line, "%u", &selection);
146 } while (selection == MENU_ENTRY_COUNT);
147
148 switch (selection) {
149 case GENERAL_EXIT: {
150 puts ("EXITING...");
151 hash_table_free (hash_table);
152 red_black_tree_free (red_black_tree);
153 return EXIT_SUCCESS;
154 } break;
155
156 case HASH_TABLE_PRINT: {
157 hash_table_print (hash_table, "hash-table.dot");
158 puts ("hash-table.dot:0:0: HASH TABLE PRINTED");
159 } break;
160
161 case HASH_TABLE_INSERT: {
162 const char *word = input_word ();
163 hash_table_insert (hash_table, word, strdup (""));
164 puts ("ENTRY INSERTED");
165 } break;
166
167 case HASH_TABLE_DELETE: {
168 const char *word = input_word ();
169 if (hash_table_delete (hash_table, word))
170 puts ("ENTRY DELETED");
171 else
172 puts ("ENTRY NOT FOUND");
173 } break;
174
175 case HASH_TABLE_SEARCH: {
176 const char *key = input_word ();
177 const char *value = hash_table_search (hash_table, key);
178 if (value)
179 puts ("ENTRY FOUND");
180 else
181 puts ("ENTRY NOT FOUND");
182 } break;
183
184 case HASH_TABLE_CLEAR: {
185 hash_table_clear (hash_table);
186 puts ("HASH TABLE CLEARED");
187 } break;
188
189 case HASH_TABLE_LOAD_FROM_FILE: {
190 const char *filename = input_filename ();
191 load_from_file (filename, (void *) hash_table_insert, hash_table);
192 } break;
193
194 case RED_BLACK_TREE_PRINT: {
195 red_black_tree_print (red_black_tree, "red-black-tree.dot");
196 puts ("red-black-tree.dot:0:0: RED BLACK TREE PRINTED");
197 } break;
198
199 case RED_BLACK_TREE_INSERT: {
200 const char *word = input_word ();
201 red_black_tree_insert (red_black_tree, word, strdup (""));
202 puts ("ENTRY INSERTED");
203 } break;
204
205 case RED_BLACK_TREE_DELETE: {
206 const char *key = input_word ();
207 if (red_black_tree_delete (red_black_tree, key))
208 puts ("ENTRY DELETED");
209 else
210 puts ("ENTRY NOT FOUND");
211 } break;
212
213 case RED_BLACK_TREE_SEARCH: {
214 const char *key = input_word ();
215 const char *value = red_black_tree_search (red_black_tree, key);
216 if (value)
217 puts ("ENTRY FOUND");
218 else
219 puts ("ENTRY NOT FOUND");
220 } break;
221
222 case RED_BLACK_TREE_CLEAR: {
223 red_black_tree_clear (red_black_tree);
224 puts ("RED BLACK TREE CLEARED");
225 } break;
226
227 case RED_BLACK_TREE_LOAD_FROM_FILE: {
228 const char *filename = input_filename ();
229 load_from_file (filename, (void *) red_black_tree_insert, red_black_tree);
230 } break;
231 default: break;
232 }
233 }
234}
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 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
49
50#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
51
52#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
53 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
54 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
55
56#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 @@
1#include "hash-table.h"
2#include <string.h>
3#include <stdio.h>
4
5typedef struct entry *ENTRY;
6struct entry {
7 ENTRY next;
8 char *key;
9 char *value;
10};
11
12struct hash_table {
13 size_t bucket_count;
14 ENTRY buckets[];
15};
16
17// NOTE(cmmm): hash * 33 ^ c might be better
18static inline size_t
19hash_function_djb2 (const char *str)
20{
21 size_t hash = 5381;
22 unsigned char c;
23
24 while ((c = *str++))
25 hash = ((hash << 5) + hash) + c; // hash * 33 + c
26
27 return hash;
28}
29
30void
31hash_table_print (HASH_TABLE hash_table, const char *filename)
32{
33 FILE *stream = fopen (filename, "w");
34 fprintf (stream, "digraph hash_table {\n");
35 fprintf (stream, "\trankdir = LR\n");
36 fprintf (stream, "\tnode [shape = record]\n\n");
37 size_t entry_idx = 0;
38 size_t bucket_idx = 0;
39 for (ENTRY *bucket = hash_table->buckets;
40 bucket < hash_table->buckets + hash_table->bucket_count; ++bucket)
41 {
42 fprintf (stream, "\tbucket%zu [label = \"%zu\"]\n", bucket_idx, bucket_idx);
43
44 size_t saved_idx = entry_idx;
45 for (ENTRY entry = *bucket; entry; entry = entry->next)
46 fprintf (stream, "\tentry%zu [label = \"%s\"]\n", entry_idx++, entry->key);
47
48 entry_idx = saved_idx;
49 for (ENTRY entry = *bucket; entry; entry = entry->next) {
50 if (entry == *bucket)
51 fprintf (stream, "\tbucket%zu -> ", bucket_idx);
52 fprintf (stream, "entry%zu", entry_idx++);
53 if (entry->next)
54 fprintf (stream, " -> ");
55 } fprintf (stream, "\n\n");
56
57 bucket_idx += 1;
58 } fprintf (stream, "}\n");
59 fclose (stream);
60}
61
62HASH_TABLE
63hash_table_init (size_t bucket_count)
64{
65 HASH_TABLE hash_table = malloc (sizeof (*hash_table) +
66 bucket_count*sizeof (*hash_table->buckets));
67
68 hash_table->bucket_count = bucket_count;
69 memset (hash_table->buckets, 0,
70 hash_table->bucket_count*sizeof (*hash_table->buckets));
71
72 return hash_table;
73}
74
75void
76hash_table_clear (HASH_TABLE hash_table)
77{
78 if (!hash_table)
79 return;
80
81 for (ENTRY *bucket = hash_table->buckets;
82 bucket < hash_table->buckets + hash_table->bucket_count; ++bucket) {
83 for (ENTRY entry = *bucket, next; entry; entry = next) {
84 next = entry->next;
85 free (entry->key);
86 free (entry->value);
87 free (entry);
88 } *bucket = NULL;
89 }
90}
91
92void
93hash_table_free (HASH_TABLE hash_table)
94{
95 hash_table_clear (hash_table);
96 free (hash_table);
97}
98
99void
100hash_table_insert (HASH_TABLE hash_table, const char *key, const char *value)
101{
102 size_t hash = hash_function_djb2 (key) % hash_table->bucket_count;
103
104 ENTRY *entry = &hash_table->buckets[hash];
105 while (*entry) {
106 if (!strcmp (key, (*entry)->key)) { // found
107 free ((*entry)->value);
108 (*entry)->value = strdup (value);
109 return;
110 } else entry = &(*entry)->next;
111 }
112
113 // not found
114 *entry = malloc (sizeof (**entry));
115 (*entry)->next = NULL;
116 (*entry)->key = strdup (key);
117 (*entry)->value = strdup (value);
118}
119
120bool
121hash_table_delete (HASH_TABLE hash_table, const char *key)
122{
123 size_t hash = hash_function_djb2 (key) % hash_table->bucket_count;
124 ENTRY *entry = &hash_table->buckets[hash];
125 while (*entry) {
126 if (!strcmp (key, (*entry)->key)) { // found
127 ENTRY next = (*entry)->next;
128
129 free ((*entry)->key);
130 free ((*entry)->value);
131 free (*entry);
132
133 *entry = next;
134
135 return true;
136 } else entry = &(*entry)->next;
137 } return false;
138}
139
140const char *
141hash_table_search (HASH_TABLE hash_table, const char *key)
142{
143 size_t hash = hash_function_djb2 (key) % hash_table->bucket_count;
144 ENTRY entry = hash_table->buckets[hash];
145 while (entry) {
146 if (!strcmp (key, entry->key))
147 return entry->value;
148 else entry = entry->next;
149 } return NULL;
150}
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 @@
1#ifndef INCLUDED_HASH_TABLE_H
2#define INCLUDED_HASH_TABLE_H
3
4#include <stdlib.h>
5#include <stdbool.h>
6
7typedef struct hash_table *HASH_TABLE;
8
9HASH_TABLE hash_table_init (size_t bucket_count);
10void hash_table_print (HASH_TABLE, const char *filename);
11void hash_table_clear (HASH_TABLE);
12void hash_table_free (HASH_TABLE);
13
14void hash_table_insert (HASH_TABLE, const char *key, const char *value);
15bool hash_table_delete (HASH_TABLE, const char *key);
16const char *hash_table_search (HASH_TABLE, const char *key);
17
18#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 @@
1#include "red-black-tree.h"
2#include "dynamic-array.h"
3#include <stdlib.h>
4#include <stdint.h>
5#include <stdio.h>
6#include <string.h>
7
8enum color {
9 COLOR_RED,
10 COLOR_BLACK,
11};
12
13typedef struct node *NODE;
14struct node {
15 enum color color;
16 NODE parent;
17 NODE left;
18 NODE right;
19 char *key;
20 char *value;
21};
22
23struct red_black_tree {
24 NODE root;
25};
26
27struct nodes {
28 NODE *items;
29 uint32_t count;
30 uint32_t capacity;
31};
32
33void
34red_black_tree_print (RED_BLACK_TREE red_black_tree, const char *filename)
35{
36 FILE *file = fopen (filename, "w");
37 fprintf (file, "digraph red_black_tree {\n");
38 fprintf (file, "\tnode [style = filled, fillcolor = black, fontcolor = white]\n");
39
40 struct nodes stack1 = {0};
41 struct nodes stack2 = {0};
42 struct nodes *front_stack = &stack1;
43 struct nodes *back_stack = &stack2;
44 if (red_black_tree->root)
45 DYNAMIC_ARRAY_APPEND (*front_stack, red_black_tree->root);
46 size_t null_count = 0;
47 while (front_stack->count) {
48 DYNAMIC_ARRAY_RESET (*back_stack);
49 DYNAMIC_ARRAY_FOREACH(node, *front_stack) {
50 fprintf (file, "\t\"%s\" [fillcolor = %s]\n", (*node)->key, (*node)->color ? "black" : "webmaroon");
51
52 if ((*node)->left) {
53 DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->left);
54 fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->left->key);
55 } else {
56 fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count);
57 fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count);
58 null_count += 1;
59 }
60
61 if ((*node)->right) {
62 DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->right);
63 fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->right->key);
64 } else {
65 fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count);
66 fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count);
67 null_count += 1;
68 }
69 } SWAP (front_stack, back_stack);
70 } fprintf (file, "}\n");
71 fclose (file);
72}
73
74RED_BLACK_TREE
75red_black_tree_init (void)
76{
77 return calloc (1, sizeof (struct red_black_tree));
78}
79
80void
81red_black_tree_clear (RED_BLACK_TREE red_black_tree)
82{
83 if (!red_black_tree || !red_black_tree->root)
84 return;
85
86 struct nodes stack = {0};
87 DYNAMIC_ARRAY_APPEND (stack, red_black_tree->root);
88 while (stack.count) {
89 NODE node = stack.items[stack.count - 1];
90 stack.count -= 1;
91
92 if (node->left)
93 DYNAMIC_ARRAY_APPEND (stack, node->left);
94
95 if (node->right)
96 DYNAMIC_ARRAY_APPEND (stack, node->right);
97
98 free (node->key );
99 free (node->value);
100 free (node );
101 } red_black_tree->root = NULL;
102}
103
104void
105red_black_tree_free (RED_BLACK_TREE red_black_tree)
106{
107 red_black_tree_clear (red_black_tree);
108 free (red_black_tree);
109}
110
111static inline void
112rotate_left (RED_BLACK_TREE red_black_tree, NODE node)
113{
114 NODE y = node->right;
115 if (!y) return;
116 node->right = y->left;
117 if (y->left)
118 y->left->parent = node;
119
120 y->parent = node->parent;
121 if (!node->parent) {
122 red_black_tree->root = y;
123 } else if (node == node->parent->left) {
124 node->parent->left = y;
125 } else {
126 node->parent->right = y;
127 }
128
129 y->left = node;
130 node->parent = y;
131}
132
133static inline void
134rotate_right (RED_BLACK_TREE red_black_tree, NODE node)
135{
136 NODE y = node->left;
137 node->left = y->right;
138 if (y->right) {
139 y->right->parent = node;
140 }
141 y->parent = node->parent;
142 if (!node->parent) {
143 red_black_tree->root = y;
144 } else if (node == node->parent->right) {
145 node->parent->right = y;
146 } else {
147 node->parent->left = y;
148 }
149 y->right = node;
150 node->parent = y;
151}
152
153void
154red_black_tree_insert (RED_BLACK_TREE red_black_tree,
155 const char *key, const char *value)
156{
157 // change value if already exists
158 for (NODE head = red_black_tree->root, next; head; head = next) {
159 int difference = strcmp (head->key, key);
160 if (!difference) {
161 free (head->value);
162 head->value = strdup (value);
163 return;
164 }
165 next = difference > 0 ? head->left : head->right;
166 }
167
168 NODE node = calloc (1, sizeof (*node));
169 node->key = strdup (key);
170 node->value = strdup (value);
171
172 // find parent
173 for (NODE head = red_black_tree->root, next; head; head = next) {
174 node->parent = head;
175 next = strcmp (node->key, head->key) < 0 ? head->left
176 : head->right;
177 }
178
179 // no parent
180 if (!node->parent) {
181 node->color = COLOR_BLACK;
182 red_black_tree->root = node;
183 return;
184 }
185
186 // attach
187 if (strcmp (node->key, node->parent->key) < 0) {
188 node->parent->left = node;
189 } else {
190 node->parent->right = node;
191 }
192
193 // no grandparent
194 if (!node->parent->parent) {
195 return;
196 }
197
198 // fix insert
199 NODE u;
200 while (node->parent->color == COLOR_RED) {
201 if (node->parent == node->parent->parent->right) {
202 u = node->parent->parent->left; // uncle
203 if (u && u->color == COLOR_RED) { // case 3.1
204 u->color = COLOR_BLACK;
205 node->parent->color = COLOR_BLACK;
206 node->parent->parent->color = COLOR_RED;
207 node = node->parent->parent;
208 } else {
209 if (node == node->parent->left) { // case 3.2.2
210 node = node->parent;
211 rotate_right (red_black_tree, node);
212 }
213
214 // case 3.2.1
215 node->parent->color = COLOR_BLACK;
216 node->parent->parent->color = COLOR_RED;
217 rotate_left (red_black_tree, node->parent->parent);
218 }
219 } else {
220 u = node->parent->parent->right; // uncle
221
222 if (u && u->color == COLOR_RED) { // mirror case 3.1
223 u->color = COLOR_BLACK;
224 node->parent->color = COLOR_BLACK;
225 node->parent->parent->color = COLOR_RED;
226 node = node->parent->parent;
227 } else {
228 if (node == node->parent->right) { // mirror case 3.2.2
229 node = node->parent;
230 rotate_left (red_black_tree, node);
231 }
232
233 // mirror case 3.2.1
234 node->parent->color = COLOR_BLACK;
235 node->parent->parent->color = COLOR_RED;
236 rotate_right (red_black_tree, node->parent->parent);
237 }
238 }
239 if (node == red_black_tree->root) {
240 break;
241 }
242 }
243 red_black_tree->root->color = COLOR_BLACK;
244}
245
246
247static inline NODE
248minimum (NODE node)
249{
250 if (!node)
251 return NULL; // patch
252
253 while (node->left)
254 node = node->left;
255
256 return node;
257}
258
259// https://github.com/xieqing/red-black-tree
260bool
261red_black_tree_delete (RED_BLACK_TREE red_black_tree, const char *key)
262{
263 NODE node = NULL;
264 NODE target = NULL;
265 NODE child = NULL;
266
267 for (NODE head = red_black_tree->root, next; head; head = next) {
268 if (!strcmp (head->key, key)) {
269 node = head;
270 break;
271 }
272 next = strcmp (head->key, key) <= 0 ? head->right : head->left;
273 }
274
275 if (!node)
276 return false;
277
278 /* choose node's in-order successor if it has two children */
279 if (!node->left || !node->right) {
280 target = node;
281 } else {
282 target = node->right ? minimum (node->right) : node; /* node->right must not be NIL, thus move down */
283
284 /* data swapped */
285 SWAP (node->key, target->key);
286 SWAP (node->value, target->value);
287 }
288
289 child = !target->left ? target->right : target->left; /* child may be NIL */
290
291 /*
292 * deletion from red-black tree
293 * 4-children cluster (RED target node) becomes 3-children cluster
294 * done
295 * 3-children cluster (RED target node) becomes 2-children cluster
296 * done
297 * 3-children cluster (BLACK target node, RED child node) becomes 2-children cluster
298 * paint child node BLACK, and done
299 *
300 * 2-children root cluster (BLACK target node, BLACK child node) becomes 0-children root cluster
301 * done
302 *
303 * 2-children cluster (BLACK target node, 4-children sibling cluster) becomes 3-children cluster
304 * transfer, and done
305 * 2-children cluster (BLACK target node, 3-children sibling cluster) becomes 2-children cluster
306 * transfer, and done
307 *
308 * 2-children cluster (BLACK target node, 2-children sibling cluster, 3/4-children parent cluster) becomes 3-children cluster
309 * fuse, paint parent node BLACK, and done
310 * 2-children cluster (BLACK target node, 2-children sibling cluster, 2-children parent cluster) becomes 3-children cluster
311 * fuse, and delete parent node from parent cluster
312 */
313 if (target->color == COLOR_BLACK) {
314 if (child && child->color == COLOR_RED) {
315 /* deletion from 3-children cluster (BLACK target node, RED child node) */
316 child->color = COLOR_BLACK;
317 } else if (target == red_black_tree->root) {
318 /* deletion from 2-children root cluster (BLACK target node, BLACK child node) */
319 } else {
320 /* deletion from 2-children cluster (BLACK target node, ...) */
321 // REPAIR
322 NODE current = target;
323 NODE sibling;
324 do {
325 if (current == current->parent->left) {
326 sibling = current->parent->right;
327
328 if (sibling && sibling->color == COLOR_RED) {
329 /* perform an adjustment (3-children parent cluster has two representations) */
330 sibling->color = COLOR_BLACK;
331 current->parent->color = COLOR_RED;
332 rotate_left (red_black_tree, current->parent);
333 sibling = current->parent->right;
334 }
335
336 /* sibling node must be BLACK now */
337 if ((!sibling->right || sibling->right->color == COLOR_BLACK) &&
338 (!sibling->left || sibling->left ->color == COLOR_BLACK)) {
339 /* 2-children sibling cluster, fuse by recoloring */
340 sibling->color = COLOR_RED;
341 if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */
342 current->parent->color = COLOR_BLACK;
343 break; /* goto break */
344 } else { /* 2-children parent cluster */
345 current = current->parent; /* goto loop */
346 }
347 } else {
348 /* 3/4-children sibling cluster */
349
350 /* perform an adjustment (3-children sibling cluster has two representations) */
351 if (!sibling->right || sibling->right->color == COLOR_BLACK) {
352 sibling->left->color = COLOR_BLACK;
353 sibling->color = COLOR_RED;
354 rotate_right (red_black_tree, sibling);
355 sibling = current->parent->right;
356 }
357
358 /* transfer by rotation and recoloring */
359 sibling->color = current->parent->color;
360 current->parent->color = COLOR_BLACK;
361 sibling->right->color = COLOR_BLACK;
362 rotate_left (red_black_tree, current->parent);
363 break; /* goto break */
364 }
365 } else {
366 sibling = current->parent->left;
367
368 if (sibling->color == COLOR_RED) {
369 /* perform an adjustment (3-children parent cluster has two representations) */
370 sibling->color = COLOR_BLACK;
371 current->parent->color = COLOR_RED;
372 rotate_right (red_black_tree, current->parent);
373 sibling = current->parent->left;
374 }
375
376 /* sibling node must be BLACK now */
377
378 if ((!sibling->right || sibling->right->color == COLOR_BLACK) &&
379 (!sibling->left || sibling->left ->color == COLOR_BLACK)) {
380 /* 2-children sibling cluster, fuse by recoloring */
381 sibling->color = COLOR_RED;
382 if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */
383 current->parent->color = COLOR_BLACK;
384 break; /* goto break */
385 } else { /* 2-children parent cluster */
386 current = current->parent; /* goto loop */
387 }
388 } else {
389 /* 3/4-children sibling cluster */
390
391 /* perform an adjustment (3-children sibling cluster has two representations) */
392 if (!sibling->left || sibling->left->color == COLOR_BLACK) {
393 sibling->right->color = COLOR_BLACK;
394 sibling->color = COLOR_RED;
395 rotate_left (red_black_tree, sibling);
396 sibling = current->parent->left;
397 }
398
399 /* transfer by rotation and recoloring */
400 sibling->color = current->parent->color;
401 current->parent->color = COLOR_BLACK;
402 sibling->left->color = COLOR_BLACK;
403 rotate_right (red_black_tree, current->parent);
404 break; /* goto break */
405 }
406 }
407 } while (current != red_black_tree->root);
408 }
409 } else {
410 /* deletion from 4-children cluster (RED target node) */
411 /* deletion from 3-children cluster (RED target node) */
412 }
413
414 if (child)
415 child->parent = target->parent;
416
417 if (target->parent) {
418 if (target == target->parent->left)
419 target->parent->left = child;
420 else if (target == target->parent->right)
421 target->parent->right = child;
422 } else {
423 red_black_tree->root = child;
424 }
425
426 free (target->key);
427 free (target->value);
428 free (target);
429
430 return true;
431}
432
433const char *
434red_black_tree_search (RED_BLACK_TREE red_black_tree, const char *key)
435{
436 for (NODE head = red_black_tree->root, next; head; head = next) {
437 int difference = strcmp (head->key, key);
438 if (!difference) return head->value;
439 next = difference > 0 ? head->left : head->right;
440 }
441
442 return NULL;
443}
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 @@
1#ifndef INCLUDED_RED_BLACK_TREE_H
2#define INCLUDED_RED_BLACK_TREE_H
3
4#include <stdbool.h>
5
6typedef struct red_black_tree *RED_BLACK_TREE;
7
8RED_BLACK_TREE red_black_tree_init (void);
9void red_black_tree_print (RED_BLACK_TREE, const char *filename);
10void red_black_tree_clear (RED_BLACK_TREE);
11void red_black_tree_free (RED_BLACK_TREE);
12
13void red_black_tree_insert (RED_BLACK_TREE, const char *key, const char *value);
14bool red_black_tree_delete (RED_BLACK_TREE, const char *key);
15const char *red_black_tree_search (RED_BLACK_TREE, const char *key);
16
17#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 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <assert.h>
5#include <stdlib.h>
6
7#define MALLOC malloc
8#define REALLOC realloc
9#define FREE free
10#define ASSERT assert
11
12#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
13
14#define SWAP(A, B) \
15 ({ \
16 typeof (A) tmp = (A); \
17 (A) = (B); \
18 (B) = tmp; \
19 })
20
21#endif