From 7ac9c048bb7c00d614230997df520b9319f0a030 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 09:37:40 +0300 Subject: publish --- .gitignore | 6 + README.org | 15 ++ UNLICENSE | 24 ++ build.sh | 5 + doc/biblio.bib | 7 + doc/gost/gost-7-32-bibliography.sty | 57 +++++ doc/gost/gost-7-32-captions.sty | 30 +++ doc/gost/gost-7-32-counters.sty | 44 ++++ doc/gost/gost-7-32-headings.sty | 106 +++++++++ doc/gost/gost-7-32-lists.sty | 17 ++ doc/gost/gost-7-32-tables.sty | 31 +++ doc/gost/gost-7-32-toc.sty | 34 +++ doc/gost/gost-7-32.cls | 62 +++++ doc/ox-init.el | 132 +++++++++++ doc/report.org | 438 +++++++++++++++++++++++++++++++++++ doc/setup.org | 34 +++ doc/spbstu-report.cls | 77 ++++++ src/bake.c | 22 ++ src/built.h | 66 ++++++ src/common.h | 27 +++ src/data.h | 124 ++++++++++ src/dynamic-array.h | 66 ++++++ src/simple-ant-colony-optimization.c | 379 ++++++++++++++++++++++++++++++ src/task2.c | 8 + src/task2.h | 18 ++ src/utils.h | 54 +++++ 26 files changed, 1883 insertions(+) create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 build.sh create mode 100644 doc/biblio.bib 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 src/bake.c create mode 100644 src/built.h create mode 100644 src/common.h create mode 100644 src/data.h create mode 100644 src/dynamic-array.h create mode 100644 src/simple-ant-colony-optimization.c create mode 100644 src/task2.c create mode 100644 src/task2.h create mode 100644 src/utils.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c475d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.html +*.pdf +*.tex +*.dot +*.png +/simple-ant-colony-optimization diff --git a/README.org b/README.org new file mode 100644 index 0000000..54694ca --- /dev/null +++ b/README.org @@ -0,0 +1,15 @@ +#+title: Ant colony optimization +#+subtitle: for the traveling salesman problem +#+date: 2025H2 + +* Documentation +:PROPERTIES: +:CUSTOM_ID: documentation +:END: +The exported report can be found at [[https://git.michalec.dev/files/uni/term-07/gen-alg/lab-06/report.pdf][this link]]. + +* Unlicense +:PROPERTIES: +:CUSTOM_ID: unlicense +:END: +#+include: UNLICENSE verse 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..5f71bd2 --- /dev/null +++ b/build.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +set -xe + +gcc -Wall -Wextra -ggdb3 -std=gnu99 -O3 -march=native -lm src/simple-ant-colony-optimization.c -o simple-ant-colony-optimization diff --git a/doc/biblio.bib b/doc/biblio.bib new file mode 100644 index 0000000..51443f5 --- /dev/null +++ b/doc/biblio.bib @@ -0,0 +1,7 @@ +@book{METODA, + title = {Методические указания по выполнению лабораторных работ к курсу «Генетические алгоритмы»}, + address = {Санкт-Петербург}, + publisher = {СПБПУ}, + pages = {119}, + language = {russian} +} 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..79a4620 --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty @@ -0,0 +1,30 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} +\RequirePackage{capt-of} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, skip=0.5em, justification=centering, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, skip=0.5em, singlelinecheck=off, position=above} + +\addto\captionsrussian{\renewcommand{\figurename}{Рис.}} +\addto\captionsrussian{\captionsetup[listing]{name=Рис.}} +\makeatletter +\AtBeginDocument{% + \let\c@figure\c@listing + \let\thefigure\thelisting + \let\ftype@listing\ftype@figure +} +\makeatother diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..ee95480 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty @@ -0,0 +1,44 @@ +\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 + +% Increment figure counter when using lstlisting +% \let\oldlstlisting\lstlisting +% \renewcommand{\lstlisting}[1][]{% +% \refstepcounter{figure} +% \oldlstlisting[#1] +% } diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..033f4a8 --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty @@ -0,0 +1,106 @@ +\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]{\centering\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing*{\section}{0cm}{0cm}{0.5cm} +\newcommand{\sectionbreak}{\clearpage} + +\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} + +\makeatletter +\let\oldsection\section +\newcommand{\@sectionnostar}[1]{\phantomsection\oldsection*{#1}\addcontentsline{toc}{section}{#1}} +\newcommand{\@sectionstar}[1]{\oldsection{#1}} +\renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}} +\makeatother + +% +% 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..6f41980 --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty @@ -0,0 +1,17 @@ +\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[itemize, 3]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} +\setlist[3]{wide=2\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..c3954c3 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty @@ -0,0 +1,31 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{booktabs} +\RequirePackage{xltabular} +\renewcommand\tabularxcolumn[1]{m{#1}} % for vertical centering text + +% +% Center-aligned column with automatic width +% +\newcolumntype{C}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{R}{>{\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..328079d --- /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, + hidelinks +]{hyperref} + +% +% Set custom font styles +% +\renewcommand{\cftsecfont}{\normalfont} +\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +\renewcommand{\cftsecpagefont}{\normalsize} +\renewcommand{\cftaftertoctitle}{\hfill\hfill} +\renewcommand{\cfttoctitlefont}{\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..efbe9d8 --- /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} +\singlespacing % or \setstretch{1} + +% +% 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..47ef892 --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,132 @@ +;;; ox-init.el --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +;; (org-babel-do-load-languages +;; 'org-babel-load-languages +;; '((latex . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(setq org-latex-src-block-backend 'minted) + +(require 'oc-bibtex) +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-export-default-language "ru") + +(setq org-latex-default-packages-alist nil) + +(setq org-latex-tables-booktabs t) + +(setq org-latex-caption-above '(table)) + +(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}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;; TODO(cmmm): add \addlinespace between rows which don't have 'rule +;; TODO(cmmm): wrap head columns in something like: +;; \multicolumn{1}{c}{\bold head1} +(defun cmmm-org-latex-table-row (table-row contents info) + "Transcode a TABLE-ROW element from Org to LaTeX. +CONTENTS is the contents of the row. INFO is a plist used as +a communication channel." + (let* ((attr (org-export-read-attribute :attr_latex + (org-element-parent table-row))) + (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs) + (plist-get info :latex-tables-booktabs))) + (longtablep + (member (or (plist-get attr :environment) + (plist-get info :latex-default-table-environment)) + ;; adding xltabular is the only change + '("longtable" "longtabu" "xltabular")))) + (if (eq (org-element-property :type table-row) 'rule) + (cond + ((not booktabsp) "\\hline") + ((not (org-export-get-previous-element table-row info)) "\\toprule") + ((not (org-export-get-next-element table-row info)) "\\bottomrule") + ((and longtablep + (org-export-table-row-ends-header-p + (org-export-get-previous-element table-row info) info)) + "") + (t "\\midrule")) + ;; Memorize table header in case it is multiline. We need this + ;; information to define contents before "\\endhead" in longtable environments. + (when (org-export-table-row-in-header-p table-row info) + (let ((table-head-cache (plist-get info :org-latex-table-head-cache))) + (unless (hash-table-p table-head-cache) + (setq table-head-cache (make-hash-table :test #'eq)) + (plist-put info :org-latex-table-head-cache table-head-cache)) + (if-let* ((head-contents (gethash (org-element-parent table-row) table-head-cache))) + (puthash (org-element-parent table-row) (concat head-contents "\\\\\n" contents) + table-head-cache) + (puthash (org-element-parent table-row) contents table-head-cache)))) + ;; Return LaTeX string as the transcoder. + (concat + ;; When BOOKTABS are activated enforce top-rule even when no + ;; hline was specifically marked. + (and booktabsp (not (org-export-get-previous-element table-row info)) + "\\toprule\n") + contents "\\\\\n" + (cond + ;; Special case for long tables. Define header and footers. + ((and longtablep (org-export-table-row-ends-header-p table-row info)) + (let ((columns (cdr (org-export-table-dimensions + (org-element-lineage table-row 'table) info)))) + (format "%s +\\endfirsthead +\\multicolumn{%d}{l}{%s} \\\\ +%s +%s \\\\\n +%s +\\endhead +%s\\multicolumn{%d}{r}{%s} \\\\ +\\endfoot +\\endlastfoot" + (if booktabsp "\\midrule" "\\hline") + columns + (org-latex--translate "Continued from previous page" info) + (cond + ((not (org-export-table-row-starts-header-p table-row info)) + "") + (booktabsp "\\toprule\n") + (t "\\hline\n")) + (gethash (org-element-parent table-row) (plist-get info :org-latex-table-head-cache)) + (if booktabsp "\\midrule" "\\hline") + (if booktabsp "\\midrule" "\\hline") + columns + (org-latex--translate "Continued on next page" info)))) + ;; When BOOKTABS are activated enforce bottom rule even when + ;; no hline was specifically marked. + ((and booktabsp (not (org-export-get-next-element table-row info))) + "\\bottomrule")))))) +(advice-add 'org-latex-table-row :override 'cmmm-org-latex-table-row) + +(defun cmmm-org-export-translate (s encoding info) + "Translate string S according to language specification. + +ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1' +and `:utf-8'. INFO is a plist used as a communication channel. + +Translation depends on `:language' property. Return the +translated string. If no translation is found, try to fall back +to `:default' encoding. If it fails, return S." + (let* ((lang (plist-get info :language)) + (translations (cdr (assoc lang + (cdr (assoc s org-export-dictionary)))))) + (or (plist-get translations encoding) + (plist-get translations :default) + (plist-get translations :utf-8) + s))) +(advice-add 'org-export-translate :override 'cmmm-org-export-translate) + +;;; ox-init.el ends here diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..60985b5 --- /dev/null +++ b/doc/report.org @@ -0,0 +1,438 @@ +#+title: Оптимизация путей на графах с помощью муравьиных алгоритмов +#+subtitle: Вариант 14 +#+author: Михалец М. +#+date: 2025 +#+latex_header: \reportof{О ВЫПОЛНЕНИИ ПРАКТИЧЕСКОЙ РАБОТЫ №6} +#+latex_header: \subject{по дисциплине «Генетические алгоритмы»} +#+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} +#+latex_header: \institute{Институт компьютерных наук и кибербезопасности} +#+latex_header: \school{Высшая школа технологии искусственного интеллекта} +#+latex_header: \direction{02.03.01 Математика и компьютерные науки} +#+latex_header: \reviewertitle{}\reviewer{Большаков А.А.} +#+latex_header: \city{Санкт-Петербург} + +#+setupfile: setup.org +#+latex: \sloppy + +* ВВЕДЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +Муравьиные алгоритмы представляют собой класс метаэвристических +методов оптимизации, основанных на моделировании поведения колоний +муравьев в природе. Эти алгоритмы были разработаны для решения +сложных комбинаторных задач оптимизации, в частности задач поиска +путей на графах. + +Основная идея муравьиных алгоритмов заключается в использовании +коллективного поведения искусственных агентов (муравьев), которые +взаимодействуют через отложение феромонов. Каждый муравей строит +потенциальное решение задачи, а концентрация феромона на ребрах графа +отражает «качество» этих решений. Чем выше концентрация феромона на +определенном ребре, тем более привлекательным оно становится для +последующих муравьев. + +#+latex: \bigbreak\noindent +*Цель работы:* изучить принципы работы муравьиных алгоритмов, +реализовать их для решения поставленной задачи и провести анализ +полученных результатов. + +* Постановка задачи +#+latex: \noindent +В данной работе были поставлены следующие задачи: +1. Реализовать с использованием муравьиного алгоритма решение задачи + коммивояжера (TSP). +2. Представить графически найденное решение и график сходимости + алгоритма. + +#+latex: \bigbreak\noindent +*Индивидуальное задание вариант 14:* + +#+latex: \bigbreak\noindent +*Дано:* Эвклидовы координаты 52 городов в Берлине (см. [[#A]]). Оптимальный +тур представлен на Рис. [[optimal-tour]], его длина равна 7498.270020. + +#+name: optimal-tour +#+caption: Оптиматльный тур для заданного набора данных +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{./res/optimal-tour} +#+end_figure + +#+latex: \bigbreak\noindent +*Требуется:* +1. Реализовать с использованием муравьиных алгоритмов решение задачи + коммивояжера +2. Представить графически найденное решение +3. Сравнить найденное решение с представленным в условии задачи + оптимальным решением и результатами, полученными в лабораторной + работе №3. + +* Теоретические сведения +** Задача коммивояжера +Задача коммивояжера (Traveling Salesman Problem, TSP) является одной +из самых известных и изучаемых проблем комбинаторной оптимизации. Её +классическая формулировка заключается в следующем: коммивояжеру +необходимо посетить ровно по одному разу каждый из заданного множества +городов и вернуться в исходный пункт. Расстояния между всеми парами +городов известны. Цель состоит в том, чтобы найти такой порядок +обхода городов (замкнутый маршрут или гамильтонов цикл), при котором +общее пройденное расстояние является минимально возможным, а +единственным ограничением является требование посетить каждый город +ровно один раз перед возвращением. + +Математически задача может быть представлена на взвешенном графе \( G += (V, E), где V = \{1, 2, ..., n\} \) --- множество вершин (городов), +а \( E \) --- множество рёбер (путей между городами). Каждому ребру \( +(i, j) \) приписан неотрицательный вес \( d_{ij} \) , представляющий +расстояние или стоимость перемещения из города \( i \) в город \( j +\). Задача сводится к нахождению минимального по весу гамильтонова +цикла в этом графе. Пусть бинарная переменная \( x_{ij} \) принимает +значение \( 1 \), если ребро \( (i, j) \) включено в маршрут, и \( 0 +\) в противном случае. Тогда целевая функция, которую необходимо +минимизировать, записывается как: \[ \sum_{i=1}^n\sum_{j \ne i, j=1}^n +d_{ij}x_{ij}. \] + +Для того чтобы решение образовывало единственный замкнутый цикл, а не +набор несвязных подциклов, на переменные \( x_{ij} \) накладываются +следующие ограничения. Во-первых, гарантируется, что коммивояжер +въезжает в каждый город ровно один раз и выезжает из него ровно один +раз: \[ \sum_{i = 1, i \ne j}^n x_{ij} = 1\quad \forall +j\quad\text{и}\quad \sum_{j=1, j \ne 1}^n x_{ij} = 1\quad \forall +i. \] + +Во-вторых, вводятся так называемые «субтурные» или «подцикловые» +ограничения, которые исключают формирование циклов, не включающих все +города: \[ \sum_{i \in S}\sum_{j \notin S} x_{ij} \ge 1\quad \forall S +\subset V, S \neq \emptyset. \] + +** Муравьиные алгоритмы +Муравьиные алгоритмы (МА) основаны на использовании популяции +потенциальных решений и разработаны для решения задач комбинаторной +оптимизации, прежде всего, поиска различных путей на графах. +Кооперация между особями (искусственными муравьями) здесь реализуется +на основе моделирования. При этом каждый агент, называемый +искусственным муравьем, ищет решение поставленной +задачи. Искусственные муравьи последовательно строят решение задачи, +передвигаясь по графу, откладывают феромон и при выборе дальнейшего +участка пути учитывают концентрацию этого фермента. Чем больше +концентрация феромона в последующем участке, тем больше вероятность +его выбора. + +** Простой муравьиный алгоритм +Рассмотрим задачу поиска кратчайшего пути между двумя узлами графа \( +G = (V, E) \), где \( V \) --- множество узлов (вершин), а \( E \) --- +матрица, которая представляет связи между узлами. Пусть \( n_G = |V| +\) --- число узлов в графе. Обозначим \( L^k \) --- длину пути в +графе, пройденного \(k\)-м муравьем, которая равна числу пройденных +дуг (ребер) от первой до последней вершины пути. С каждой дугой, +соединяющей вершины \( (i,j) \) ассоциируем концентрацию феромона \( +\tau_{ij} \). + +** Инициализация +С формальной точки зрения, исходная концентрация феромона на всех +дугах графа должна быть нулевой. Однако на практике для инициализации +процесса каждой дуге присваивается небольшое начальное значение \( +\tau_{ij}(0) \), генерируемое случайным образом. + +** Построение решений +Процесс выбора муравьём следующей дуги пути организуется следующим +образом. Множество муравьев \( k = 1, \ldots, n_k \) размещается в +стартовой вершине. На каждой итерации муравьиного алгоритма каждый +муравей последовательно строит маршрут до конечной вершины. В каждой +текущей вершине муравей осуществляет выбор следующей дуги пути. Если +\(k\)-й муравей находится в вершине \(i\), то выбор следующей вершины +\( j \in N_i^k \) осуществляется на основе вероятностей перехода: \[ +p_{ij}^k(t) = \begin{cases} +\dfrac{[\tau_{ij}(t)]^{\alpha}}{\sum\limits_{l \in N_i^{k}} +[\tau_{il}(t)]^{\alpha}}, & \text{если } j \in N_i^{k} \\ 0, & +\text{если } j \notin N_i^{k}\end{cases}, \] где \( N_i^k \) --- +множество допустимых вершин, соединенных с вершиной \(i\), для +\(k\)-го муравья. Если для некоторой вершины \(i\) и муравья \(k\) +множество \( N_i^k = \emptyset \), то в \( N_i^k \) включается +предыдущая вершина. Это может приводить к образованию петель в +маршруте, которые устраняются после достижения конечной вершины пути. +\(\alpha\) --- положительная константа, определяющая степень влияния +концентрации феромона. Более высокие значения \(\alpha\) усиливают +влияние феромона, что особенно значимо на начальных этапах алгоритма +при случайных начальных значениях концентрации и может привести к +преждевременной сходимости к субоптимальным решениям. + +** Обновление феромона +После построения всех решений выполняется обновление феромонной матрицы: + +*Испарение феромона:* + +\[ \tau_{ij}(t) \leftarrow (1 − \rho) \cdot \tau_{ij}(t), \] + +где \( \rho \in [0, 1] \) --- коэффициент испарения. + +*Отложение феромона:* + +\[ \tau_{ij}(t + 1) = \tau_{ij}(t) + +\sum_{k=1}^{n_k}\Delta\tau_{ij}^k(t) \] + +Количество откладываемого феромона обратно пропорционально длине пути: + +\[ \Delta \tau_{ij}^k(t) = \frac{1}{L^k(t)}, \] + +где \( L^k(t) \) --- длина пути, построенного муравьем \(k\). + +*** Добавление эвристики +Параметр \( \beta \) определяет влияние эвристической информации на +вероятность выбора следующей вершины. В модифицированной формуле +вероятности перехода учитывается не только концентрация феромона, но и +эвристическая оценка целесообразности перехода: + +\[ p_{ij}^k(t) = \begin{cases} +\dfrac{[\tau_{ij}(t)]^{\alpha}\,[\eta_{ij}]^{\beta}} {\sum\limits_{l +\in N_i^{k}} [\tau_{il}(t)]^{\alpha}\,[\eta_{il}]^{\beta}}, & +\text{если } j \in N_i^{k}, \\ 0, & \text{если } j \notin N_i^{k} +\end{cases}, \] + +где \( \eta_{ij} = \frac{1}{d_{ij}} \) --- эвристическая функция, обратно пропорциональная расстоянию +между вершинами \(i\) и \(j\). +Параметр \( \beta \) регулирует "жадность" алгоритма: +- При \( \beta = 0 \) алгоритм игнорирует эвристическую информацию и + работает исключительно на основе феромонов +- При \( \beta > 0 \) алгоритм начинает учитывать расстояния между + вершинами, предпочитая более короткие переходы +- Высокие значения \( \beta \) усиливают жадную составляющую алгоритма + +Совместное использование параметров \( \alpha \) и \( \beta \) +позволяет балансировать между: +- влиянием феромонов, параметр \( \alpha \) +- жадным выбором, параметр \( \beta \) + +*** Общий алгоритм +1. Инициализировать начальные значения феромонов на всех рёбрах графа + малыми случайными величинами. +2. Установить начальное значение счётчика итераций. +3. Разместить всех муравьев в стартовой вершине графа. +4. Выполнять цикл до достижения критерия остановки: + 1. Для каждого муравья построить полный путь до конечной вершины: + 1. На каждом шаге выбирать следующую вершину на основе + вероятности, зависящей от концентрации феромона и + эвристической информации. + 2. Добавлять выбранное ребро в текущий путь муравья. + 2. Удалить возможные петли из построенных маршрутов. + 3. Вычислить длину каждого полученного пути. + 4. Обновить феромоновую матрицу: + 1. Уменьшить концентрацию феромона на всех рёбрах за счёт + испарения. + 2. Увеличить концентрацию феромона на рёбрах, входящих в + построенные пути, пропорционально качеству этих путей. + 5. Увеличить счётчик итераций. +5. Вернуть лучший найденный путь за всё время работы алгоритма. + +* Особенности реализации +В рамках работы была создана программа +=simple-ant-colony-optimization.c= для экспериментов с простыми +муравейными алгоритмами (МА) для решения задачи коммивояжёра. Она +позволяет легко управлять параметрами эксперимента, брать статистику о +времени выполнения и рисовать графики генерации. + +- *Феромоны*: Хранятся в линейном массиве, инициализируются случайными + значениями из \( \matcal{U}(0, 1) \). Феромоны испаряются в + зависимости от ~RHO~. +- *Строение пути муравья:* Посещенные города отслеживаются битовой + маской, и муравью запрещается повторно посещать одинаковые города, + таким образом не формируются циклы в пути, и она имеет заранее + известный размер. +- *Критерий остановки:* Используются критерий по отсутсвий улучшения за + 30 поколений и по достижению 100 поколений. +- *Визуализация:* снимок поколения включает оптимальный маршрут + (выделенный зелёным цветом), маршрут лучшей особи (выделенный + красным цветом), города (синие крестики). Функция: ~void plot (const + char *output, int population_size, int generation);~. + +* Результаты работы +На рис. [[generation-first]]-[[generation-last]] представлены результаты +работы муравьиного алгоритма со следующими параметрами: +- Количество муравей: 100 особей +- Максимальное количество поколений: 100 +- Критерии останова по стагнации: 30 итерации без улучшения +- Коэффициент испарения феромонов: \( \rho = 0.5 \) +- Параметры влияния: \( \alpha = 1, \beta = 3.5 \) + +На рис. [[fitness]] показан график изменения фитнесса по поколениям. +Видно, что алгоритм постепенно сходится к значению фитнесса +\(7966.763184\), но оптимального маршрута, со значением фитнесса +\(7498.270020\), так и не находит. + +#+name: fitness +#+caption: График изменения фитнесса по поколениям +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/convergence} +#+end_figure + +#+name: generation-first +#+caption: Лучший маршрут поколения №0 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/path-00} +#+end_figure + +#+caption: Лучший маршрут поколения №10 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/path-10} +#+end_figure + +#+caption: Лучший маршрут поколения №12 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/path-12} +#+end_figure + +#+caption: Лучший маршрут поколения №25 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/path-25} +#+end_figure + +#+caption: Лучший маршрут поколения №40 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/path-40} +#+end_figure + +#+name: generation-last +#+caption: Лучший маршрут поколения №71 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/path-71} +#+end_figure + +* Сравнение с генетическим алгоритмом +По рис. [[convergence-comparison]] видно насколько быстрее сходится +муравьиный алгоритм, а по рис. [[solution-comparison]] видно насколько +качественнее выглядит полученный результат. В таблице +[[comparison-table]] приведено сравнение численных результатов. Все +результаты показывают явное превосходство муравьиного алгоритма. + +#+name: comparison-table +#+caption: Сравнение численных результатов +#+attr_latex: :align lccc +| Параметр | Муравьиный алгоритм | Генетический алгоритм | \( \Delta \) | +|-----------------------+---------------------+-----------------------+--------------| +| Длина маршрута | 7966.763184 | 9689.396484 | 1722.6333 | +| Количество поколений | 71 | 1390 | 1319 | +| Отклонение от эталона | 6.24% | 29.22% | 22.97% | + +#+name: convergence-comparison +#+caption: Сравнение сходимости +#+attr_latex: :options [H] +#+begin_figure +\centering +#+caption: Муравьиный алгоритм +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure + \centering + \input{res/convergence} +#+end_subfigure +\vfill +#+caption: Генетический алгоритм +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure + \centering + \input{res/fitness} +#+end_subfigure +#+end_figure + +#+name: solution-comparison +#+caption: Сравнение найденного решения +#+attr_latex: :options [H] +#+begin_figure +\centering +#+caption: Муравьиный алгоритм +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure + \centering + \input{res/best-path-40} +#+end_subfigure +\vfill +#+caption: Генетический алгоритм +#+attr_latex: :options [b]{1\textwidth} +#+begin_subfigure + \centering + \input{res/ga} +#+end_subfigure +#+end_figure + +* Ответ на контрольный вопрос +#+latex: \noindent +*Вопрос:* Зачем нужно и как определяется испарение феромона в простом +МА? + +#+latex: \bigbreak\noindent +*Ответ:* Если феромон не уменьшать, ранний удачный путь «забивает» все +остальные, и колония перестаёт исследовать пространство. Если условия +меняются, испарение автоматически убирает устаревшую информацию. + +\[ \tau_{ij}(t) \leftarrow (1 − \rho) \cdot \tau_{ij}(t), \] + +где \( \rho \in [0, 1] \) --- коэффициент испарения. + +* ЗАКЛЮЧЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +В ходе выполнения практической работы была реализована и +проанализирована программная модель поиска кратчайшего маршрута на +графе с помощью муравьиного алгоритма. Рассмотрены основные +теоретические положения, касающиеся задачи коммивояжёра и принципов +функционирования муравьиной метаэвристики, в том числе роль феромонов, +влияние эвристик и особенности вероятностного построения решений. + +В рамках эксперимента с датасетом 52 городов Берлина проведено +сравнение эффективности муравьиного и генетического алгоритмов: +- Муравьиный алгоритм продемонстрировал более быстрое достижение плато + по критерию сходимости (71 поколений против 1390 у генетического), что + отражено на графиках сходимости. +- Полученное решение отклонилось от эталонного на 6.24%, что лучше + показателя у генетического алгоритма (29.22%). +- Таким образом было достигнуто улучшение на 22.97%. + +Проведённый анализ подтверждает, что муравьиные алгоритмы являются +эффективным инструментом для решения задачи поиска оптимального пути +на графах. Их достоинства проявляются в быстрой сходимости благодаря +коллективному взаимодействию агентов и адаптивному учёту опыта +предыдущих итераций, что делает метод особенно привлекательным для +сложных комбинаторных задач. + +* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ +:PROPERTIES: +:UNNUMBERED: t +:END: +#+latex: \nocite{METODA} +#+print_bibliography: :heading none + +* ПРИЛОЖЕНИЕ А +:PROPERTIES: +:UNNUMBERED: t +:CUSTOM_ID: A +:END: +#+include: "../src/simple-ant-colony-optimization.c" src c + +* ПРИЛОЖЕНИЕ Б +:PROPERTIES: +:UNNUMBERED: t +:CUSTOM_ID: B +:END: +#+include: "../src/data.h" src c + +# 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..07ca141 --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,34 @@ +#+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:t |:t +# #+creator: Emacs 29.1 (Org mode 9.6.9) + +#+select_tags: export +#+exclude_tags: noexport + +#+bibliography: biblio.bib +#+cite_export: biblatex + +#+latex_compiler: xelatex +#+latex_class: spbstu-report +# #+latex_class_options: [draft] + +#+latex_header: \usepackage{enumitem} +#+latex_header: \usepackage{float} +#+latex_header: \usepackage{soul} +#+latex_header: \usepackage{makecell} +# #+latex_header: \usepackage{cellspace} +# #+latex_header: \setlength\cellspacetoplimit{2ex} +# #+latex_header: \setlength\cellspacebottomlimit{2ex} + +#+latex_header: \usepackage[newfloat]{minted} +#+latex_header: \usemintedstyle{bw} +#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=@@,ignorelexererrors} + +#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} + +#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+latex_header: \setmainfont{Times New Roman} +#+latex_header: \setmonofont{Aporetic Serif Mono}[Contextuals=AlternateOff] diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..60c44ad --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,77 @@ +\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{amssymb} +\RequirePackage{adjustbox} +\RequirePackage{graphicx} +\RequirePackage{wrapfig} +\RequirePackage{rotating} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} +\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} +\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} +\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#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}}}$} +\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{\@university} + + \vspace{0.5cm} + \normalsize{\@institute} + + \normalsize{\@school} + + \normalsize{Направление \@direction} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130201/20101 & \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{\@city, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/src/bake.c b/src/bake.c new file mode 100644 index 0000000..99566d8 --- /dev/null +++ b/src/bake.c @@ -0,0 +1,22 @@ +#include +#include "utils.h" + +u16 graph[] = { + // 0123456789 + [0] = 0b0100100000, + [1] = 0b1001000000, + [2] = 0b0001001100, + [3] = 0b0010001100, + [4] = 0b1000010010, + [5] = 0b0000101000, + [6] = 0b0011010101, + [7] = 0b0011001000, + [8] = 0b0000100001, + [9] = 0b0000001010, +}; + +int +main (void) +{ + return EXIT_SUCCESS; +} diff --git a/src/built.h b/src/built.h new file mode 100644 index 0000000..7ed87fd --- /dev/null +++ b/src/built.h @@ -0,0 +1,66 @@ +#ifndef INCLUDED_BUILT_H +#define INCLUDED_BUILT_H + +uint8_t best_route[] = { + 0, 47, 30, 42, 17, 37, 6, 6, 6, 35, 26, 39, 6, + 38, 8, 7, 33, 17, 17, 17, 6, 15, 2, 3, 4, 2, + 10, 23, 17, 16, 17, 16, 15, 14, 13, 14, 14, 3, 9, + 12, 5, 7, 7, 0, 1, 6, 3, 1, 0, 0, 1, 0, +}; + +float distances[CHROMOSOME_SIZE][CHROMOSOME_SIZE] = { + { 0, 666.108, 281.114, 395.601, 291.204, 326.267, 640.8, 426.878, 600.188, 561.471, 1040.97, 655.019, 975, 1120.77, 299.04, 260.048, 429.535, 161.555, 305, 210.06, 286.923, 46.0977, 181.177, 274.591, 410.03, 728.972, 798.514, 707.001, 406.263, 360.069, 146.373, 90.5538, 827.315, 135.093, 121.655, 125, 207.966, 240.416, 166.208, 208.926, 395.38, 565.796, 463.816, 154.434, 240.208, 279.866, 791.281, 267.301, 64.0312, 217.083, 789.383, 1220.46, }, + { 666.108, 0, 649.327, 1047.09, 945.146, 978.085, 45, 956.151, 1134.96, 1132.98, 1638.79, 1258.59, 1440.08, 1515.73, 957.823, 724.034, 494.773, 595.483, 843.401, 564.469, 392.46, 636.416, 509.828, 921.792, 1028.85, 1191.51, 1301.51, 1243.72, 635.02, 390.448, 541.225, 730, 1488.71, 782.081, 776.981, 785, 857.7, 896.939, 827.964, 869.741, 896.172, 102.591, 1123.71, 744.883, 823.286, 859.084, 1151.27, 910.302, 728.011, 596.259, 1421.56, 1716.05, }, + { 281.114, 649.327, 0, 603.511, 508.945, 542.517, 610.573, 308.058, 485.644, 487.263, 1266.69, 891.361, 1247.76, 1399.73, 504.876, 537.401, 217.313, 134.629, 207.002, 440.965, 288.531, 240.52, 361.179, 505.693, 652.534, 1005.94, 1067.64, 970.322, 651.249, 504.207, 208.926, 245.204, 903.396, 393.605, 373.664, 367.696, 447.465, 462.088, 392.237, 426.878, 246.982, 550.091, 556.597, 434.195, 219.829, 552.675, 1072.31, 504.802, 288.487, 463.249, 995.314, 1483.59, }, + { 395.601, 1047.09, 603.511, 0, 104.403, 69.6419, 1026.36, 525, 611.003, 533.901, 663.193, 294.364, 711.073, 897.009, 100.125, 384.22, 800.25, 532.353, 474.684, 500.625, 681.487, 436.606, 537.703, 125.3, 109.202, 516.236, 526.806, 417.433, 579.871, 689.529, 540.856, 370.54, 517.349, 266.552, 275.136, 270.601, 190.394, 155.242, 230.489, 188.282, 544.541, 950.329, 245.204, 307.002, 411.096, 230.705, 659.564, 137.295, 345.254, 477.624, 397.02, 908.639, }, + { 291.204, 945.146, 508.945, 104.403, 0, 35.3553, 923.594, 470.558, 583.631, 513.469, 760.805, 382.426, 769.042, 944.312, 25, 309.233, 700.071, 430.465, 400.78, 406.602, 577.17, 332.453, 436.835, 31.6228, 150.083, 552.268, 584.145, 478.592, 509.755, 594.348, 436.606, 270.185, 589.958, 163.248, 170.88, 166.208, 87.4643, 50.9902, 126.59, 85.1469, 479.505, 847.659, 266.693, 212.25, 331.21, 170.66, 673.591, 47.4342, 241.868, 386.685, 499.925, 984.441, }, + { 326.267, 978.085, 542.517, 69.6419, 35.3553, 0, 957.04, 491.554, 596.008, 523.259, 726.103, 349.285, 744.194, 922.781, 40.3113, 328.824, 735.017, 465.672, 427.931, 435.23, 611.903, 367.73, 469.068, 57.0088, 124.197, 533.339, 559.129, 452.217, 528.015, 623.699, 471.832, 305.041, 568.243, 196.977, 205.548, 201.308, 120.83, 86.3134, 161.941, 120.416, 504.009, 881.036, 260.048, 240.832, 360.069, 182.003, 661.91, 70.7107, 277.218, 413.793, 464.57, 954.895, }, + { 640.8, 45, 610.573, 1026.36, 923.594, 957.04, 0, 918.096, 1095.92, 1095.73, 1627.42, 1245.2, 1440.31, 1521.73, 935.361, 713.863, 451.248, 562.25, 807.001, 551.77, 361.732, 609.139, 491.172, 901.18, 1012.42, 1190.09, 1297.79, 1236.74, 636.965, 385.519, 511.517, 701.231, 1459.63, 760.345, 754.205, 761.577, 836.316, 874.714, 804.394, 846.537, 857.555, 76.1577, 1094.81, 726.997, 789.383, 844.423, 1156.83, 890.183, 701.73, 584.637, 1405.08, 1715.07, }, + { 426.878, 956.151, 308.058, 525, 470.558, 491.554, 918.096, 0, 183.439, 180.347, 1144.9, 812.05, 1234.34, 1414.23, 452.548, 660.984, 506.582, 381.215, 125.897, 635.964, 580.388, 415.03, 586.728, 486.544, 615.549, 1022.8, 1049.4, 941.077, 831.039, 758.765, 457.22, 338.711, 645.155, 455, 435.46, 421.545, 460.57, 446.01, 413.824, 421.574, 64.0312, 855.862, 359.026, 529.74, 187.417, 598.54, 1135.89, 495.101, 383.438, 643.817, 860.145, 1430.47, }, + { 600.188, 1134.96, 485.644, 611.003, 583.631, 596.008, 1095.92, 183.439, 0, 83.2166, 1165.61, 873.856, 1316.76, 1507.12, 561.471, 817.955, 670.317, 564.646, 308.058, 810.247, 763.217, 593.043, 766.551, 606.238, 714.178, 1126.11, 1134.55, 1024.46, 998.211, 940.492, 640.312, 510.025, 570.197, 606.98, 589.428, 574.674, 596.091, 571.948, 557.853, 555, 239.27, 1035.59, 389.936, 685.584, 360.867, 733.894, 1257.06, 617.839, 550.568, 815.138, 883.233, 1486.78, }, + { 561.471, 1132.98, 487.263, 533.901, 513.469, 523.259, 1095.73, 180.347, 83.2166, 0, 1082.65, 792.086, 1236.58, 1428.29, 490.433, 763.692, 686.477, 547.951, 290.904, 770.276, 751.482, 560.29, 734.932, 537.82, 638.847, 1049.98, 1055.05, 944.934, 950.053, 912.14, 619.294, 471.01, 500.899, 552.268, 536.144, 521.177, 533.667, 506.211, 499.925, 492.443, 243.977, 1031.95, 307.774, 631.981, 329.014, 669.645, 1185.17, 550.273, 507.001, 771.962, 800.078, 1404.04, }, + { 1040.97, 1638.79, 1266.69, 663.193, 760.805, 726.103, 1627.42, 1144.9, 1165.61, 1082.65, 0, 387.072, 442.719, 619.556, 762.365, 914.822, 1460.69, 1190.09, 1124.3, 1075.66, 1314.17, 1085.56, 1143.53, 770.016, 631.269, 541.041, 417.433, 417.642, 1042.41, 1250.97, 1186.78, 1030.98, 706.134, 905.884, 920.34, 920.054, 835.06, 810.386, 885.127, 845.532, 1180.04, 1552.32, 789.24, 912.921, 1067.95, 786.67, 705.16, 775.065, 1000.01, 1042.93, 285.044, 398.56, }, + { 655.019, 1258.59, 891.361, 294.364, 382.426, 349.285, 1245.2, 812.05, 873.856, 792.086, 387.072, 0, 452.134, 653.242, 388.104, 537.703, 1078.36, 806.877, 768.847, 694.136, 927.16, 700.018, 758.172, 387.621, 245, 335.037, 283.24, 182.483, 688.186, 874.643, 800.391, 650.577, 584.209, 520, 535.21, 535.84, 450.999, 429.942, 503.016, 465.296, 836.316, 1169.63, 484.381, 526.118, 705.301, 401.404, 517.422, 391.152, 616.644, 662.59, 188.215, 618.567, }, + { 975, 1440.08, 1247.76, 711.073, 769.042, 744.194, 1440.31, 1234.34, 1316.76, 1236.58, 442.719, 452.134, 0, 205.548, 784.092, 759.276, 1399.51, 1136.54, 1169.47, 919.918, 1194.76, 1020.42, 1008.19, 759.951, 620.081, 254.018, 185.068, 293.641, 805.248, 1056.18, 1103.65, 1004.15, 1010.36, 854.181, 874.314, 881.192, 806.923, 804.316, 862.699, 836.376, 1248.08, 1371.31, 930.86, 821.721, 1098.33, 696.024, 324.423, 755.86, 959.284, 884.59, 539.676, 278.658, }, + { 1120.77, 1515.73, 1399.73, 897.009, 944.312, 922.781, 1521.73, 1414.23, 1507.12, 1428.29, 619.556, 653.242, 205.548, 0, 961.691, 883.883, 1534.22, 1280.67, 1340.63, 1034.65, 1313.2, 1164.69, 1127.21, 931.357, 799.156, 396.011, 374.433, 484.175, 887.426, 1146.48, 1238.79, 1160.87, 1215.91, 1009.72, 1030.59, 1039.25, 971.404, 974.59, 1026.16, 1004.45, 1423.04, 1457.48, 1125.28, 966.398, 1267.57, 848.764, 364.966, 925.216, 1113.56, 1000.12, 744.648, 318.904, }, + { 299.04, 957.823, 504.876, 100.125, 25, 40.3113, 935.361, 452.548, 561.471, 490.433, 762.365, 388.104, 784.092, 961.691, 0, 332.415, 700.161, 432.348, 387.621, 424.794, 585.875, 338.6, 451.054, 55.9017, 164.012, 571.074, 599.041, 492.367, 533.128, 611.658, 443.001, 270.416, 568.705, 176.139, 181.177, 174.642, 102.591, 61.0328, 132.853, 90.1388, 464.004, 859.593, 241.868, 231.138, 319.883, 195.576, 695.593, 71.5891, 246.221, 406.079, 497.041, 995.113, }, + { 260.048, 724.034, 537.401, 384.22, 309.233, 328.824, 713.863, 660.984, 817.955, 763.692, 914.822, 537.703, 759.276, 883.883, 332.415, 0, 650.711, 407.83, 548.862, 165.076, 435.488, 297.069, 249.098, 277.714, 326.497, 505.693, 597.537, 525.856, 200.811, 337.083, 356.721, 330.946, 897.065, 211.483, 228.528, 243.311, 244.182, 283.769, 265.047, 282.179, 640.781, 639.531, 570.088, 132.382, 476.366, 155.724, 539.49, 261.964, 281.824, 130.384, 710.106, 1022.67, }, + { 429.535, 494.773, 217.313, 800.25, 700.071, 735.017, 451.248, 506.582, 670.317, 686.477, 1460.69, 1078.36, 1399.51, 1534.22, 700.161, 650.711, 0, 271.662, 421.1, 512.079, 253.032, 383.438, 418.001, 691.158, 834.341, 1149.48, 1226.02, 1136.33, 707.425, 492.392, 296.184, 430, 1120.29, 561.471, 544.518, 542.794, 627.415, 650.308, 575.782, 615.183, 442.634, 408.075, 773.256, 579.008, 436.578, 708.255, 1187.7, 687.204, 461.736, 543.622, 1196.51, 1649.37, }, + { 161.555, 595.483, 134.629, 532.353, 430.465, 465.672, 562.25, 381.215, 564.646, 547.951, 1190.09, 806.877, 1136.54, 1280.67, 432.348, 407.83, 271.662, 0, 258.118, 306.472, 205.244, 116.297, 229.401, 420.119, 562.694, 890, 959.909, 867.439, 516.769, 385.032, 80.1561, 162.788, 903.244, 290.259, 272.947, 271.155, 355.879, 380.132, 305, 345.326, 330.492, 492.976, 541.133, 315.357, 228.035, 441.277, 946.005, 415.752, 190.263, 328.672, 929.368, 1381.2, }, + { 305, 843.401, 207.002, 474.684, 400.78, 427.931, 807.001, 125.897, 308.058, 290.904, 1124.3, 768.847, 1169.47, 1340.63, 387.621, 548.862, 421.1, 258.118, 0, 512.445, 460.652, 290.172, 460.977, 410.03, 550.681, 945.476, 984.733, 879.332, 711.003, 632.949, 332.415, 219.829, 700.589, 350.892, 330.189, 317.569, 371.248, 366.231, 318.904, 336.341, 91.9239, 741.923, 367.764, 420.387, 75, 504.48, 1044.84, 415.482, 267.442, 521.967, 843.445, 1381.96, }, + { 210.06, 564.469, 440.965, 500.625, 406.602, 435.23, 551.77, 635.964, 810.247, 770.276, 1075.66, 694.136, 919.918, 1034.65, 424.794, 165.076, 512.079, 306.472, 512.445, 0, 278.568, 223.607, 94.3398, 378.451, 467.386, 665.902, 761.643, 690.887, 210.297, 189.011, 236.008, 300.375, 990.013, 256.564, 261.773, 275.045, 322.684, 365.548, 313.847, 348.174, 601.041, 476.707, 638.161, 194.486, 450.028, 295.466, 679.779, 364.589, 263.866, 35.3553, 859.069, 1186.09, }, + { 286.923, 392.46, 288.531, 681.487, 577.17, 611.903, 361.732, 580.388, 763.217, 751.482, 1314.17, 927.16, 1194.76, 1313.2, 585.875, 435.488, 253.032, 205.244, 460.652, 278.568, 0, 250.599, 186.815, 558.413, 684.726, 941.077, 1030.97, 952.221, 459.157, 241.506, 150, 340.037, 1097.96, 416.203, 406.356, 411.4, 491.859, 526.711, 453.1, 495.807, 525.024, 289.914, 733.246, 401.528, 433.042, 530.377, 957.549, 549.477, 344.42, 313.129, 1072.01, 1456.71, }, + { 46.0977, 636.416, 240.52, 436.606, 332.453, 367.73, 609.139, 415.03, 593.043, 560.29, 1085.56, 700.018, 1020.42, 1164.69, 338.6, 297.069, 383.438, 116.297, 290.172, 223.607, 250.599, 0, 174.642, 317.53, 455.027, 773.709, 844.334, 753.077, 428.515, 352.598, 104.403, 97.0824, 852.951, 180.069, 165.303, 166.883, 251.247, 281.469, 206.155, 248.646, 377.69, 535.023, 488.109, 199.06, 232.648, 325.73, 832.406, 311.006, 93.9415, 237.171, 831.865, 1266.49, }, + { 181.177, 509.828, 361.179, 537.703, 436.835, 469.068, 491.172, 586.728, 766.551, 734.932, 1143.53, 758.172, 1008.19, 1127.21, 451.054, 249.098, 418.001, 229.401, 460.977, 94.3398, 186.815, 174.642, 0, 412.462, 521.776, 754.404, 845.931, 770.146, 296.015, 179.234, 152.315, 267.442, 1001.96, 275, 272.809, 282.931, 349.464, 390.032, 325.576, 365.548, 545.023, 415.03, 641.132, 235.85, 406.971, 356.931, 773.692, 400.656, 244.387, 127.475, 914.166, 1271.42, }, + { 274.591, 921.792, 505.693, 125.3, 31.6228, 57.0088, 901.18, 486.544, 606.238, 537.82, 770.016, 387.621, 759.951, 931.357, 55.9017, 277.714, 691.158, 420.119, 410.03, 378.451, 558.413, 317.53, 412.462, 0, 147.054, 537.401, 575.608, 472.07, 478.174, 566.789, 420.862, 263.059, 620.846, 142.302, 152.971, 150.748, 66.7083, 44.7214, 115.434, 79.0569, 491.757, 825.121, 297.7, 183.984, 338.378, 140.089, 652.553, 15.8114, 230, 357.526, 514.806, 981.542, }, + { 410.03, 1028.85, 652.534, 109.202, 150.083, 124.197, 1012.42, 615.549, 714.178, 638.847, 631.269, 245, 620.081, 799.156, 164.012, 326.497, 834.341, 562.694, 550.681, 467.386, 684.726, 455.027, 521.776, 147.054, 0, 412.098, 435.029, 328.672, 509.141, 654.313, 555.563, 408.932, 605.826, 275, 290.388, 291.548, 207.183, 191.377, 260.864, 226.108, 628.013, 936.376, 354.401, 286.4, 481.274, 173.349, 550.681, 148.071, 372.726, 439.09, 392.747, 835.135, }, + { 728.972, 1191.51, 1005.94, 516.236, 552.268, 533.339, 1190.09, 1022.8, 1126.11, 1049.98, 541.041, 335.037, 254.018, 396.011, 571.074, 505.693, 1149.48, 890, 945.476, 665.902, 941.077, 773.709, 754.404, 537.401, 412.098, 0, 126.194, 158.902, 558.793, 805.016, 853.302, 765.506, 917.306, 614.37, 635.138, 643.525, 575.543, 580, 630.179, 609.139, 1028.99, 1120.1, 755.794, 574.674, 872.067, 453.679, 185.54, 530.519, 718.679, 630.575, 496.009, 525, }, + { 798.514, 1301.51, 1067.64, 526.806, 584.145, 559.129, 1297.79, 1049.4, 1134.55, 1055.05, 417.433, 283.24, 185.068, 374.433, 599.041, 597.537, 1226.02, 959.909, 984.733, 761.643, 1030.97, 844.334, 845.931, 575.608, 435.029, 126.194, 0, 110.114, 673.665, 912.318, 931.451, 823.119, 861.931, 674.259, 693.992, 700.179, 624.119, 620.101, 680, 652.553, 1063.04, 1226.23, 751.033, 647.012, 913.906, 518.652, 291.548, 571.948, 779.311, 726.395, 410.488, 425.793, }, + { 707.001, 1243.72, 970.322, 417.433, 478.592, 452.217, 1236.74, 941.077, 1024.46, 944.934, 417.642, 182.483, 293.641, 484.175, 492.367, 525.856, 1136.33, 867.439, 879.332, 690.887, 952.221, 753.077, 770.146, 472.07, 328.672, 158.902, 110.114, 0, 629.682, 853.288, 844.349, 725.155, 766.551, 578.705, 597.704, 602.764, 523.927, 516.769, 579.763, 550.091, 956.151, 1163.45, 641.112, 559.017, 809.475, 428.515, 344.42, 469.574, 683.118, 656.22, 337.231, 513.931, }, + { 406.263, 635.02, 651.249, 579.871, 509.755, 528.015, 636.965, 831.039, 998.211, 950.053, 1042.41, 688.186, 805.248, 887.426, 533.128, 200.811, 707.425, 516.769, 711.003, 210.297, 459.157, 428.515, 296.015, 478.174, 509.141, 558.793, 673.665, 629.682, 0, 259.615, 445.225, 492.392, 1095.67, 401.995, 415.752, 430.726, 443.847, 484.2, 458.939, 480.521, 801.639, 570.636, 770.6, 322.49, 643.623, 349.178, 522.805, 462.385, 448.386, 191.377, 871.45, 1081.95, }, + { 360.069, 390.448, 504.207, 689.529, 594.348, 623.699, 385.519, 758.765, 940.492, 912.14, 1250.97, 874.643, 1056.18, 1146.48, 611.658, 337.083, 492.392, 385.032, 632.949, 189.011, 241.506, 352.598, 179.234, 566.789, 654.313, 805.016, 912.318, 853.288, 259.615, 0, 305.164, 446.598, 1172.9, 439.318, 441.192, 453.018, 509.117, 551.589, 494.292, 531.507, 712.969, 315.159, 815.552, 382.884, 583.31, 481.274, 782.192, 553.173, 422.67, 215.232, 1044.28, 1330.01, }, + { 146.373, 541.225, 208.926, 540.856, 436.606, 471.832, 511.517, 457.22, 640.312, 619.294, 1186.78, 800.391, 1103.65, 1238.79, 443.001, 356.721, 296.184, 80.1561, 332.415, 236.008, 150, 104.403, 152.315, 420.862, 555.563, 853.302, 931.451, 844.349, 445.225, 305.164, 0, 190.066, 948.117, 281.114, 268.002, 270.647, 354.295, 385.649, 310.483, 353.023, 408.717, 438.919, 583.31, 285.351, 292.959, 415.933, 895.879, 413.673, 197.8, 262.011, 935.575, 1355.91, }, + { 90.5538, 730, 245.204, 370.54, 270.185, 305.041, 701.231, 338.711, 510.025, 471.01, 1030.98, 650.577, 1004.15, 1160.87, 270.416, 330.946, 430, 162.788, 219.829, 300.375, 340.037, 97.0824, 267.442, 263.059, 408.932, 765.506, 823.119, 725.155, 492.392, 446.598, 190.066, 0, 758.716, 151.162, 130.384, 122.984, 202.608, 220.907, 148.071, 185.607, 311.488, 628.033, 393.732, 207.002, 151.327, 312.13, 845, 260.864, 50, 305.655, 767.349, 1238.4, }, + { 827.315, 1488.71, 903.396, 517.349, 589.958, 568.243, 1459.63, 645.155, 570.197, 500.899, 706.134, 584.209, 1010.36, 1215.91, 568.705, 897.065, 1120.29, 903.244, 700.589, 990.013, 1097.96, 852.951, 1001.96, 620.846, 605.826, 917.306, 861.931, 766.551, 1095.67, 1172.9, 948.117, 758.716, 0, 734.098, 731.745, 720.226, 668.506, 625.5, 678.62, 642.028, 704.006, 1386.73, 365, 798.812, 687.786, 747.011, 1095.18, 636.318, 763.708, 973.666, 474.684, 1088.73, }, + { 135.093, 782.081, 393.605, 266.552, 163.248, 196.977, 760.345, 455, 606.98, 552.268, 905.884, 520, 854.181, 1009.72, 176.139, 211.483, 561.471, 290.259, 350.892, 256.564, 416.203, 180.069, 275, 142.302, 275, 614.37, 674.259, 578.705, 401.995, 439.318, 281.114, 151.162, 734.098, 0, 21.2132, 33.541, 76.1577, 115.109, 58.5235, 92.1954, 441.616, 684.416, 382.394, 80, 276.134, 161.012, 697.227, 133.417, 105.119, 243.772, 656.22, 1092.62, }, + { 121.655, 776.981, 373.664, 275.136, 170.88, 205.548, 754.205, 435.46, 589.428, 536.144, 920.34, 535.21, 874.314, 1030.59, 181.177, 228.528, 544.518, 272.947, 330.189, 261.773, 406.356, 165.303, 272.809, 152.971, 290.388, 635.138, 693.992, 597.704, 415.752, 441.192, 268.002, 130.384, 731.745, 21.2132, 0, 15, 86.3134, 120.83, 53.1507, 93.0054, 421.1, 678.473, 376.464, 96.1769, 255.539, 182.003, 718.418, 145.774, 85.44, 251.645, 667.776, 1111.54, }, + { 125, 785, 367.696, 270.601, 166.208, 201.308, 761.577, 421.545, 574.674, 521.177, 920.054, 535.84, 881.192, 1039.25, 174.642, 243.311, 542.794, 271.155, 317.569, 275.045, 411.4, 166.883, 282.931, 150.748, 291.548, 643.525, 700.179, 602.764, 430.726, 453.018, 270.647, 122.984, 720.226, 33.541, 15, 0, 85, 115.434, 43.0116, 85, 408.167, 686.003, 363.593, 111.018, 242.745, 191.442, 729.555, 145, 81.3941, 265.707, 665.019, 1116.36, }, + { 207.966, 857.7, 447.465, 190.394, 87.4643, 120.83, 836.316, 460.57, 596.091, 533.667, 835.06, 450.999, 806.923, 971.404, 102.591, 244.182, 627.415, 355.879, 371.248, 322.684, 491.859, 251.247, 349.464, 66.7083, 207.183, 575.543, 624.119, 523.927, 443.847, 509.117, 354.295, 202.608, 668.506, 76.1577, 86.3134, 85, 0, 43.0116, 55.9017, 41.2311, 457.739, 760.345, 327.3, 130.384, 297.069, 138.654, 676.036, 60, 165.68, 305.164, 581.485, 1036.4, }, + { 240.416, 896.939, 462.088, 155.242, 50.9902, 86.3134, 874.714, 446.01, 571.948, 506.211, 810.386, 429.942, 804.316, 974.59, 61.0328, 283.769, 650.308, 380.132, 366.231, 365.548, 526.711, 281.469, 390.032, 44.7214, 191.377, 580, 620.101, 516.769, 484.2, 551.589, 385.649, 220.907, 625.5, 115.109, 120.83, 115.434, 43.0116, 0, 75.6637, 35.3553, 449.027, 798.89, 286.4, 173.349, 294.109, 163.783, 690.67, 49.4975, 191.05, 348.174, 550.84, 1026.17, }, + { 166.208, 827.964, 392.237, 230.489, 126.59, 161.941, 804.394, 413.824, 557.853, 499.925, 885.127, 503.016, 862.699, 1026.16, 132.853, 265.047, 575.782, 305, 318.904, 313.847, 453.1, 206.155, 325.576, 115.434, 260.864, 630.179, 680, 579.763, 458.939, 494.292, 310.483, 148.071, 678.62, 58.5235, 53.1507, 43.0116, 55.9017, 75.6637, 0, 42.72, 407.001, 728.869, 324.423, 136.473, 244.182, 186.011, 726.223, 112.805, 115.434, 302.076, 626.498, 1092.02, }, + { 208.926, 869.741, 426.878, 188.282, 85.1469, 120.416, 846.537, 421.574, 555, 492.443, 845.532, 465.296, 836.376, 1004.45, 90.1388, 282.179, 615.183, 345.326, 336.341, 348.174, 495.807, 248.646, 365.548, 79.0569, 226.108, 609.139, 652.553, 550.091, 480.521, 531.507, 353.023, 185.607, 642.028, 92.1954, 93.0054, 85, 41.2311, 35.3553, 42.72, 0, 421.1, 770.925, 293.471, 161.555, 263.154, 179.234, 714.37, 80.6226, 157.003, 333.654, 584.829, 1060.39, }, + { 395.38, 896.172, 246.982, 544.541, 479.505, 504.009, 857.555, 64.0312, 239.27, 243.977, 1180.04, 836.316, 1248.08, 1423.04, 464.004, 640.781, 442.634, 330.492, 91.9239, 601.041, 525.024, 377.69, 545.023, 491.757, 628.013, 1028.99, 1063.04, 956.151, 801.639, 712.969, 408.717, 311.488, 704.006, 441.616, 421.1, 408.167, 457.739, 449.027, 407.001, 421.1, 0, 796.492, 401.995, 512.079, 165.605, 593.001, 1133.16, 498.523, 359.34, 611.882, 896.354, 1453.08, }, + { 565.796, 102.591, 550.091, 950.329, 847.659, 881.036, 76.1577, 855.862, 1035.59, 1031.95, 1552.32, 1169.63, 1371.31, 1457.48, 859.593, 639.531, 408.075, 492.976, 741.923, 476.707, 289.914, 535.023, 415.03, 825.121, 936.376, 1120.1, 1226.23, 1163.45, 570.636, 315.159, 438.919, 628.033, 1386.73, 684.416, 678.473, 686.003, 760.345, 798.89, 728.869, 770.925, 796.492, 0, 1021.76, 650.865, 720.85, 768.668, 1092.54, 814.079, 627.156, 509.902, 1329, 1645.07, }, + { 463.816, 1123.71, 556.597, 245.204, 266.693, 260.048, 1094.81, 359.026, 389.936, 307.774, 789.24, 484.381, 930.86, 1125.28, 241.868, 570.088, 773.256, 541.133, 367.764, 638.161, 733.246, 488.109, 641.132, 297.7, 354.401, 755.794, 751.033, 641.112, 770.6, 815.552, 583.31, 393.732, 365, 382.394, 376.464, 363.593, 327.3, 286.4, 324.423, 293.471, 401.995, 1021.76, 0, 455, 336.786, 437.321, 904.461, 313.249, 399.906, 626.099, 504.232, 1097.2, }, + { 154.434, 744.883, 434.195, 307.002, 212.25, 240.832, 726.997, 529.74, 685.584, 631.981, 912.921, 526.118, 821.721, 966.398, 231.138, 132.382, 579.008, 315.357, 420.387, 194.486, 401.528, 199.06, 235.85, 183.984, 286.4, 574.674, 647.012, 559.017, 322.49, 382.884, 285.351, 207.002, 798.812, 80, 96.1769, 111.018, 130.384, 173.349, 136.473, 161.555, 512.079, 650.865, 455, 0, 346.771, 130.863, 640.41, 170.294, 157.003, 175, 678.399, 1070.81, }, + { 240.208, 823.286, 219.829, 411.096, 331.21, 360.069, 789.383, 187.417, 360.867, 329.014, 1067.95, 705.301, 1098.33, 1267.57, 319.883, 476.366, 436.578, 228.035, 75, 450.028, 433.042, 232.648, 406.971, 338.378, 481.274, 872.067, 913.906, 809.475, 643.623, 583.31, 292.959, 151.327, 687.786, 276.134, 255.539, 242.745, 297.069, 294.109, 244.182, 263.154, 165.605, 720.85, 336.786, 346.771, 0, 429.564, 969.91, 343.001, 196.469, 456.755, 790.142, 1314.96, }, + { 279.866, 859.084, 552.675, 230.705, 170.66, 182.003, 844.423, 598.54, 733.894, 669.645, 786.67, 401.404, 696.024, 848.764, 195.576, 155.724, 708.255, 441.277, 504.48, 295.466, 530.377, 325.73, 356.931, 140.089, 173.349, 453.679, 518.652, 428.515, 349.178, 481.274, 415.933, 312.13, 747.011, 161.012, 182.003, 191.442, 138.654, 163.783, 186.011, 179.234, 593.001, 768.668, 437.321, 130.863, 429.564, 0, 540.37, 125, 265, 266.177, 563.649, 941.116, }, + { 791.281, 1151.27, 1072.31, 659.564, 673.591, 661.91, 1156.83, 1135.89, 1257.06, 1185.17, 705.16, 517.422, 324.423, 364.966, 695.593, 539.49, 1187.7, 946.005, 1044.84, 679.779, 957.549, 832.406, 773.692, 652.553, 550.681, 185.54, 291.548, 344.42, 522.805, 782.192, 895.879, 845, 1095.18, 697.227, 718.418, 729.555, 676.036, 690.67, 726.223, 714.37, 1133.16, 1092.54, 904.461, 640.41, 969.91, 540.37, 0, 642.359, 795.503, 646.258, 681.542, 597.746, }, + { 267.301, 910.302, 504.802, 137.295, 47.4342, 70.7107, 890.183, 495.101, 617.839, 550.273, 775.065, 391.152, 755.86, 925.216, 71.5891, 261.964, 687.204, 415.752, 415.482, 364.589, 549.477, 311.006, 400.656, 15.8114, 148.071, 530.519, 571.948, 469.574, 462.385, 553.173, 413.673, 260.864, 636.318, 133.417, 145.774, 145, 60, 49.4975, 112.805, 80.6226, 498.523, 814.079, 313.249, 170.294, 343.001, 125, 642.359, 0, 225.499, 343.111, 522.805, 980.472, }, + { 64.0312, 728.011, 288.487, 345.254, 241.868, 277.218, 701.73, 383.438, 550.568, 507.001, 1000.01, 616.644, 959.284, 1113.56, 246.221, 281.824, 461.736, 190.263, 267.442, 263.866, 344.42, 93.9415, 244.387, 230, 372.726, 718.679, 779.311, 683.118, 448.386, 422.67, 197.8, 50, 763.708, 105.119, 85.44, 81.3941, 165.68, 191.05, 115.434, 157.003, 359.34, 627.156, 399.906, 157.003, 196.469, 265, 795.503, 225.499, 0, 265.189, 741.772, 1196.92, }, + { 217.083, 596.259, 463.249, 477.624, 386.685, 413.793, 584.637, 643.817, 815.138, 771.962, 1042.93, 662.59, 884.59, 1000.12, 406.079, 130.384, 543.622, 328.672, 521.967, 35.3553, 313.129, 237.171, 127.475, 357.526, 439.09, 630.575, 726.395, 656.22, 191.377, 215.232, 262.011, 305.655, 973.666, 243.772, 251.645, 265.707, 305.164, 348.174, 302.076, 333.654, 611.882, 509.902, 626.099, 175, 456.755, 266.177, 646.258, 343.111, 265.189, 0, 829.608, 1150.76, }, + { 789.383, 1421.56, 995.314, 397.02, 499.925, 464.57, 1405.08, 860.145, 883.233, 800.078, 285.044, 188.215, 539.676, 744.648, 497.041, 710.106, 1196.51, 929.368, 843.445, 859.069, 1072.01, 831.865, 914.166, 514.806, 392.747, 496.009, 410.488, 337.231, 871.45, 1044.28, 935.575, 767.349, 474.684, 656.22, 667.776, 665.019, 581.485, 550.84, 626.498, 584.829, 896.354, 1329, 504.232, 678.399, 790.142, 563.649, 681.542, 522.805, 741.772, 829.608, 0, 624.82, }, + { 1220.46, 1716.05, 1483.59, 908.639, 984.441, 954.895, 1715.07, 1430.47, 1486.78, 1404.04, 398.56, 618.567, 278.658, 318.904, 995.113, 1022.67, 1649.37, 1381.2, 1381.96, 1186.09, 1456.71, 1266.49, 1271.42, 981.542, 835.135, 525, 425.793, 513.931, 1081.95, 1330.01, 1355.91, 1238.4, 1088.73, 1092.62, 1111.54, 1116.36, 1036.4, 1026.17, 1092.02, 1060.39, 1453.08, 1645.07, 1097.2, 1070.81, 1314.96, 941.116, 597.746, 980.472, 1196.92, 1150.76, 624.82, 0, }, +}; + +#endif // INCLUDED_BUILT_H diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..7a186ba --- /dev/null +++ b/src/common.h @@ -0,0 +1,27 @@ +#ifndef INCLUDED_COMMON_H +#define INCLUDED_COMMON_H + +extern struct path { + u8 *items; + u32 count; + u32 capacity; +} path; + +extern struct crdf { + struct crdf_entry { + f32 c; + u32 j; + } *items; + u32 count; + u32 capacity; +} crdf; + +f32 build_crdf (u8 i); +f32 measure_path (void); +void added_j (u8 j); +void export_path (u8 path[NODE_COUNT], int generation); +bool finished (void); + +extern f32 (*pheromones_current)[NODE_COUNT]; + +#endif // INCLUDED_COMMON_H diff --git a/src/data.h b/src/data.h new file mode 100644 index 0000000..2c1938a --- /dev/null +++ b/src/data.h @@ -0,0 +1,124 @@ +// data.h --- 52 locations in Berlin, distance matrix, TSP solution +#ifndef INCLUDED_DATA_H +#define INCLUDED_DATA_H + +struct point { int16_t x, y; }; +struct point buildings[] = { + { 565, 575 }, + { 25, 185 }, + { 345, 750 }, + { 945, 685 }, + { 845, 655 }, + { 880, 660 }, + { 25, 230 }, + { 525, 1000 }, + { 580, 1175 }, + { 650, 1130 }, + { 1605, 620 }, + { 1220, 580 }, + { 1465, 200 }, + { 1530, 5 }, + { 845, 680 }, + { 725, 370 }, + { 145, 665 }, + { 415, 635 }, + { 510, 875 }, + { 560, 365 }, + { 300, 465 }, + { 520, 585 }, + { 480, 415 }, + { 835, 625 }, + { 975, 580 }, + { 1215, 245 }, + { 1320, 315 }, + { 1250, 400 }, + { 660, 180 }, + { 410, 250 }, + { 420, 555 }, + { 575, 665 }, + { 1150, 1160 }, + { 700, 580 }, + { 685, 595 }, + { 685, 610 }, + { 770, 610 }, + { 795, 645 }, + { 720, 635 }, + { 760, 650 }, + { 475, 960 }, + { 95, 260 }, + { 875, 920 }, + { 700, 500 }, + { 555, 815 }, + { 830, 485 }, + { 1170, 65 }, + { 830, 610 }, + { 605, 625 }, + { 595, 360 }, + { 1340, 725 }, + { 1740, 245 }, +}; + +static f32 distances[52][52] = { + { 0, 666.108, 281.114, 395.601, 291.204, 326.267, 640.8, 426.878, 600.188, 561.471, 1040.97, 655.019, 975, 1120.77, 299.04, 260.048, 429.535, 161.555, 305, 210.06, 286.923, 46.0977, 181.177, 274.591, 410.03, 728.972, 798.514, 707.001, 406.263, 360.069, 146.373, 90.5538, 827.315, 135.093, 121.655, 125, 207.966, 240.416, 166.208, 208.926, 395.38, 565.796, 463.816, 154.434, 240.208, 279.866, 791.281, 267.301, 64.0312, 217.083, 789.383, 1220.46, }, + { 666.108, 0, 649.327, 1047.09, 945.146, 978.085, 45, 956.151, 1134.96, 1132.98, 1638.79, 1258.59, 1440.08, 1515.73, 957.823, 724.034, 494.773, 595.483, 843.401, 564.469, 392.46, 636.416, 509.828, 921.792, 1028.85, 1191.51, 1301.51, 1243.72, 635.02, 390.448, 541.225, 730, 1488.71, 782.081, 776.981, 785, 857.7, 896.939, 827.964, 869.741, 896.172, 102.591, 1123.71, 744.883, 823.286, 859.084, 1151.27, 910.302, 728.011, 596.259, 1421.56, 1716.05, }, + { 281.114, 649.327, 0, 603.511, 508.945, 542.517, 610.573, 308.058, 485.644, 487.263, 1266.69, 891.361, 1247.76, 1399.73, 504.876, 537.401, 217.313, 134.629, 207.002, 440.965, 288.531, 240.52, 361.179, 505.693, 652.534, 1005.94, 1067.64, 970.322, 651.249, 504.207, 208.926, 245.204, 903.396, 393.605, 373.664, 367.696, 447.465, 462.088, 392.237, 426.878, 246.982, 550.091, 556.597, 434.195, 219.829, 552.675, 1072.31, 504.802, 288.487, 463.249, 995.314, 1483.59, }, + { 395.601, 1047.09, 603.511, 0, 104.403, 69.6419, 1026.36, 525, 611.003, 533.901, 663.193, 294.364, 711.073, 897.009, 100.125, 384.22, 800.25, 532.353, 474.684, 500.625, 681.487, 436.606, 537.703, 125.3, 109.202, 516.236, 526.806, 417.433, 579.871, 689.529, 540.856, 370.54, 517.349, 266.552, 275.136, 270.601, 190.394, 155.242, 230.489, 188.282, 544.541, 950.329, 245.204, 307.002, 411.096, 230.705, 659.564, 137.295, 345.254, 477.624, 397.02, 908.639, }, + { 291.204, 945.146, 508.945, 104.403, 0, 35.3553, 923.594, 470.558, 583.631, 513.469, 760.805, 382.426, 769.042, 944.312, 25, 309.233, 700.071, 430.465, 400.78, 406.602, 577.17, 332.453, 436.835, 31.6228, 150.083, 552.268, 584.145, 478.592, 509.755, 594.348, 436.606, 270.185, 589.958, 163.248, 170.88, 166.208, 87.4643, 50.9902, 126.59, 85.1469, 479.505, 847.659, 266.693, 212.25, 331.21, 170.66, 673.591, 47.4342, 241.868, 386.685, 499.925, 984.441, }, + { 326.267, 978.085, 542.517, 69.6419, 35.3553, 0, 957.04, 491.554, 596.008, 523.259, 726.103, 349.285, 744.194, 922.781, 40.3113, 328.824, 735.017, 465.672, 427.931, 435.23, 611.903, 367.73, 469.068, 57.0088, 124.197, 533.339, 559.129, 452.217, 528.015, 623.699, 471.832, 305.041, 568.243, 196.977, 205.548, 201.308, 120.83, 86.3134, 161.941, 120.416, 504.009, 881.036, 260.048, 240.832, 360.069, 182.003, 661.91, 70.7107, 277.218, 413.793, 464.57, 954.895, }, + { 640.8, 45, 610.573, 1026.36, 923.594, 957.04, 0, 918.096, 1095.92, 1095.73, 1627.42, 1245.2, 1440.31, 1521.73, 935.361, 713.863, 451.248, 562.25, 807.001, 551.77, 361.732, 609.139, 491.172, 901.18, 1012.42, 1190.09, 1297.79, 1236.74, 636.965, 385.519, 511.517, 701.231, 1459.63, 760.345, 754.205, 761.577, 836.316, 874.714, 804.394, 846.537, 857.555, 76.1577, 1094.81, 726.997, 789.383, 844.423, 1156.83, 890.183, 701.73, 584.637, 1405.08, 1715.07, }, + { 426.878, 956.151, 308.058, 525, 470.558, 491.554, 918.096, 0, 183.439, 180.347, 1144.9, 812.05, 1234.34, 1414.23, 452.548, 660.984, 506.582, 381.215, 125.897, 635.964, 580.388, 415.03, 586.728, 486.544, 615.549, 1022.8, 1049.4, 941.077, 831.039, 758.765, 457.22, 338.711, 645.155, 455, 435.46, 421.545, 460.57, 446.01, 413.824, 421.574, 64.0312, 855.862, 359.026, 529.74, 187.417, 598.54, 1135.89, 495.101, 383.438, 643.817, 860.145, 1430.47, }, + { 600.188, 1134.96, 485.644, 611.003, 583.631, 596.008, 1095.92, 183.439, 0, 83.2166, 1165.61, 873.856, 1316.76, 1507.12, 561.471, 817.955, 670.317, 564.646, 308.058, 810.247, 763.217, 593.043, 766.551, 606.238, 714.178, 1126.11, 1134.55, 1024.46, 998.211, 940.492, 640.312, 510.025, 570.197, 606.98, 589.428, 574.674, 596.091, 571.948, 557.853, 555, 239.27, 1035.59, 389.936, 685.584, 360.867, 733.894, 1257.06, 617.839, 550.568, 815.138, 883.233, 1486.78, }, + { 561.471, 1132.98, 487.263, 533.901, 513.469, 523.259, 1095.73, 180.347, 83.2166, 0, 1082.65, 792.086, 1236.58, 1428.29, 490.433, 763.692, 686.477, 547.951, 290.904, 770.276, 751.482, 560.29, 734.932, 537.82, 638.847, 1049.98, 1055.05, 944.934, 950.053, 912.14, 619.294, 471.01, 500.899, 552.268, 536.144, 521.177, 533.667, 506.211, 499.925, 492.443, 243.977, 1031.95, 307.774, 631.981, 329.014, 669.645, 1185.17, 550.273, 507.001, 771.962, 800.078, 1404.04, }, + { 1040.97, 1638.79, 1266.69, 663.193, 760.805, 726.103, 1627.42, 1144.9, 1165.61, 1082.65, 0, 387.072, 442.719, 619.556, 762.365, 914.822, 1460.69, 1190.09, 1124.3, 1075.66, 1314.17, 1085.56, 1143.53, 770.016, 631.269, 541.041, 417.433, 417.642, 1042.41, 1250.97, 1186.78, 1030.98, 706.134, 905.884, 920.34, 920.054, 835.06, 810.386, 885.127, 845.532, 1180.04, 1552.32, 789.24, 912.921, 1067.95, 786.67, 705.16, 775.065, 1000.01, 1042.93, 285.044, 398.56, }, + { 655.019, 1258.59, 891.361, 294.364, 382.426, 349.285, 1245.2, 812.05, 873.856, 792.086, 387.072, 0, 452.134, 653.242, 388.104, 537.703, 1078.36, 806.877, 768.847, 694.136, 927.16, 700.018, 758.172, 387.621, 245, 335.037, 283.24, 182.483, 688.186, 874.643, 800.391, 650.577, 584.209, 520, 535.21, 535.84, 450.999, 429.942, 503.016, 465.296, 836.316, 1169.63, 484.381, 526.118, 705.301, 401.404, 517.422, 391.152, 616.644, 662.59, 188.215, 618.567, }, + { 975, 1440.08, 1247.76, 711.073, 769.042, 744.194, 1440.31, 1234.34, 1316.76, 1236.58, 442.719, 452.134, 0, 205.548, 784.092, 759.276, 1399.51, 1136.54, 1169.47, 919.918, 1194.76, 1020.42, 1008.19, 759.951, 620.081, 254.018, 185.068, 293.641, 805.248, 1056.18, 1103.65, 1004.15, 1010.36, 854.181, 874.314, 881.192, 806.923, 804.316, 862.699, 836.376, 1248.08, 1371.31, 930.86, 821.721, 1098.33, 696.024, 324.423, 755.86, 959.284, 884.59, 539.676, 278.658, }, + { 1120.77, 1515.73, 1399.73, 897.009, 944.312, 922.781, 1521.73, 1414.23, 1507.12, 1428.29, 619.556, 653.242, 205.548, 0, 961.691, 883.883, 1534.22, 1280.67, 1340.63, 1034.65, 1313.2, 1164.69, 1127.21, 931.357, 799.156, 396.011, 374.433, 484.175, 887.426, 1146.48, 1238.79, 1160.87, 1215.91, 1009.72, 1030.59, 1039.25, 971.404, 974.59, 1026.16, 1004.45, 1423.04, 1457.48, 1125.28, 966.398, 1267.57, 848.764, 364.966, 925.216, 1113.56, 1000.12, 744.648, 318.904, }, + { 299.04, 957.823, 504.876, 100.125, 25, 40.3113, 935.361, 452.548, 561.471, 490.433, 762.365, 388.104, 784.092, 961.691, 0, 332.415, 700.161, 432.348, 387.621, 424.794, 585.875, 338.6, 451.054, 55.9017, 164.012, 571.074, 599.041, 492.367, 533.128, 611.658, 443.001, 270.416, 568.705, 176.139, 181.177, 174.642, 102.591, 61.0328, 132.853, 90.1388, 464.004, 859.593, 241.868, 231.138, 319.883, 195.576, 695.593, 71.5891, 246.221, 406.079, 497.041, 995.113, }, + { 260.048, 724.034, 537.401, 384.22, 309.233, 328.824, 713.863, 660.984, 817.955, 763.692, 914.822, 537.703, 759.276, 883.883, 332.415, 0, 650.711, 407.83, 548.862, 165.076, 435.488, 297.069, 249.098, 277.714, 326.497, 505.693, 597.537, 525.856, 200.811, 337.083, 356.721, 330.946, 897.065, 211.483, 228.528, 243.311, 244.182, 283.769, 265.047, 282.179, 640.781, 639.531, 570.088, 132.382, 476.366, 155.724, 539.49, 261.964, 281.824, 130.384, 710.106, 1022.67, }, + { 429.535, 494.773, 217.313, 800.25, 700.071, 735.017, 451.248, 506.582, 670.317, 686.477, 1460.69, 1078.36, 1399.51, 1534.22, 700.161, 650.711, 0, 271.662, 421.1, 512.079, 253.032, 383.438, 418.001, 691.158, 834.341, 1149.48, 1226.02, 1136.33, 707.425, 492.392, 296.184, 430, 1120.29, 561.471, 544.518, 542.794, 627.415, 650.308, 575.782, 615.183, 442.634, 408.075, 773.256, 579.008, 436.578, 708.255, 1187.7, 687.204, 461.736, 543.622, 1196.51, 1649.37, }, + { 161.555, 595.483, 134.629, 532.353, 430.465, 465.672, 562.25, 381.215, 564.646, 547.951, 1190.09, 806.877, 1136.54, 1280.67, 432.348, 407.83, 271.662, 0, 258.118, 306.472, 205.244, 116.297, 229.401, 420.119, 562.694, 890, 959.909, 867.439, 516.769, 385.032, 80.1561, 162.788, 903.244, 290.259, 272.947, 271.155, 355.879, 380.132, 305, 345.326, 330.492, 492.976, 541.133, 315.357, 228.035, 441.277, 946.005, 415.752, 190.263, 328.672, 929.368, 1381.2, }, + { 305, 843.401, 207.002, 474.684, 400.78, 427.931, 807.001, 125.897, 308.058, 290.904, 1124.3, 768.847, 1169.47, 1340.63, 387.621, 548.862, 421.1, 258.118, 0, 512.445, 460.652, 290.172, 460.977, 410.03, 550.681, 945.476, 984.733, 879.332, 711.003, 632.949, 332.415, 219.829, 700.589, 350.892, 330.189, 317.569, 371.248, 366.231, 318.904, 336.341, 91.9239, 741.923, 367.764, 420.387, 75, 504.48, 1044.84, 415.482, 267.442, 521.967, 843.445, 1381.96, }, + { 210.06, 564.469, 440.965, 500.625, 406.602, 435.23, 551.77, 635.964, 810.247, 770.276, 1075.66, 694.136, 919.918, 1034.65, 424.794, 165.076, 512.079, 306.472, 512.445, 0, 278.568, 223.607, 94.3398, 378.451, 467.386, 665.902, 761.643, 690.887, 210.297, 189.011, 236.008, 300.375, 990.013, 256.564, 261.773, 275.045, 322.684, 365.548, 313.847, 348.174, 601.041, 476.707, 638.161, 194.486, 450.028, 295.466, 679.779, 364.589, 263.866, 35.3553, 859.069, 1186.09, }, + { 286.923, 392.46, 288.531, 681.487, 577.17, 611.903, 361.732, 580.388, 763.217, 751.482, 1314.17, 927.16, 1194.76, 1313.2, 585.875, 435.488, 253.032, 205.244, 460.652, 278.568, 0, 250.599, 186.815, 558.413, 684.726, 941.077, 1030.97, 952.221, 459.157, 241.506, 150, 340.037, 1097.96, 416.203, 406.356, 411.4, 491.859, 526.711, 453.1, 495.807, 525.024, 289.914, 733.246, 401.528, 433.042, 530.377, 957.549, 549.477, 344.42, 313.129, 1072.01, 1456.71, }, + { 46.0977, 636.416, 240.52, 436.606, 332.453, 367.73, 609.139, 415.03, 593.043, 560.29, 1085.56, 700.018, 1020.42, 1164.69, 338.6, 297.069, 383.438, 116.297, 290.172, 223.607, 250.599, 0, 174.642, 317.53, 455.027, 773.709, 844.334, 753.077, 428.515, 352.598, 104.403, 97.0824, 852.951, 180.069, 165.303, 166.883, 251.247, 281.469, 206.155, 248.646, 377.69, 535.023, 488.109, 199.06, 232.648, 325.73, 832.406, 311.006, 93.9415, 237.171, 831.865, 1266.49, }, + { 181.177, 509.828, 361.179, 537.703, 436.835, 469.068, 491.172, 586.728, 766.551, 734.932, 1143.53, 758.172, 1008.19, 1127.21, 451.054, 249.098, 418.001, 229.401, 460.977, 94.3398, 186.815, 174.642, 0, 412.462, 521.776, 754.404, 845.931, 770.146, 296.015, 179.234, 152.315, 267.442, 1001.96, 275, 272.809, 282.931, 349.464, 390.032, 325.576, 365.548, 545.023, 415.03, 641.132, 235.85, 406.971, 356.931, 773.692, 400.656, 244.387, 127.475, 914.166, 1271.42, }, + { 274.591, 921.792, 505.693, 125.3, 31.6228, 57.0088, 901.18, 486.544, 606.238, 537.82, 770.016, 387.621, 759.951, 931.357, 55.9017, 277.714, 691.158, 420.119, 410.03, 378.451, 558.413, 317.53, 412.462, 0, 147.054, 537.401, 575.608, 472.07, 478.174, 566.789, 420.862, 263.059, 620.846, 142.302, 152.971, 150.748, 66.7083, 44.7214, 115.434, 79.0569, 491.757, 825.121, 297.7, 183.984, 338.378, 140.089, 652.553, 15.8114, 230, 357.526, 514.806, 981.542, }, + { 410.03, 1028.85, 652.534, 109.202, 150.083, 124.197, 1012.42, 615.549, 714.178, 638.847, 631.269, 245, 620.081, 799.156, 164.012, 326.497, 834.341, 562.694, 550.681, 467.386, 684.726, 455.027, 521.776, 147.054, 0, 412.098, 435.029, 328.672, 509.141, 654.313, 555.563, 408.932, 605.826, 275, 290.388, 291.548, 207.183, 191.377, 260.864, 226.108, 628.013, 936.376, 354.401, 286.4, 481.274, 173.349, 550.681, 148.071, 372.726, 439.09, 392.747, 835.135, }, + { 728.972, 1191.51, 1005.94, 516.236, 552.268, 533.339, 1190.09, 1022.8, 1126.11, 1049.98, 541.041, 335.037, 254.018, 396.011, 571.074, 505.693, 1149.48, 890, 945.476, 665.902, 941.077, 773.709, 754.404, 537.401, 412.098, 0, 126.194, 158.902, 558.793, 805.016, 853.302, 765.506, 917.306, 614.37, 635.138, 643.525, 575.543, 580, 630.179, 609.139, 1028.99, 1120.1, 755.794, 574.674, 872.067, 453.679, 185.54, 530.519, 718.679, 630.575, 496.009, 525, }, + { 798.514, 1301.51, 1067.64, 526.806, 584.145, 559.129, 1297.79, 1049.4, 1134.55, 1055.05, 417.433, 283.24, 185.068, 374.433, 599.041, 597.537, 1226.02, 959.909, 984.733, 761.643, 1030.97, 844.334, 845.931, 575.608, 435.029, 126.194, 0, 110.114, 673.665, 912.318, 931.451, 823.119, 861.931, 674.259, 693.992, 700.179, 624.119, 620.101, 680, 652.553, 1063.04, 1226.23, 751.033, 647.012, 913.906, 518.652, 291.548, 571.948, 779.311, 726.395, 410.488, 425.793, }, + { 707.001, 1243.72, 970.322, 417.433, 478.592, 452.217, 1236.74, 941.077, 1024.46, 944.934, 417.642, 182.483, 293.641, 484.175, 492.367, 525.856, 1136.33, 867.439, 879.332, 690.887, 952.221, 753.077, 770.146, 472.07, 328.672, 158.902, 110.114, 0, 629.682, 853.288, 844.349, 725.155, 766.551, 578.705, 597.704, 602.764, 523.927, 516.769, 579.763, 550.091, 956.151, 1163.45, 641.112, 559.017, 809.475, 428.515, 344.42, 469.574, 683.118, 656.22, 337.231, 513.931, }, + { 406.263, 635.02, 651.249, 579.871, 509.755, 528.015, 636.965, 831.039, 998.211, 950.053, 1042.41, 688.186, 805.248, 887.426, 533.128, 200.811, 707.425, 516.769, 711.003, 210.297, 459.157, 428.515, 296.015, 478.174, 509.141, 558.793, 673.665, 629.682, 0, 259.615, 445.225, 492.392, 1095.67, 401.995, 415.752, 430.726, 443.847, 484.2, 458.939, 480.521, 801.639, 570.636, 770.6, 322.49, 643.623, 349.178, 522.805, 462.385, 448.386, 191.377, 871.45, 1081.95, }, + { 360.069, 390.448, 504.207, 689.529, 594.348, 623.699, 385.519, 758.765, 940.492, 912.14, 1250.97, 874.643, 1056.18, 1146.48, 611.658, 337.083, 492.392, 385.032, 632.949, 189.011, 241.506, 352.598, 179.234, 566.789, 654.313, 805.016, 912.318, 853.288, 259.615, 0, 305.164, 446.598, 1172.9, 439.318, 441.192, 453.018, 509.117, 551.589, 494.292, 531.507, 712.969, 315.159, 815.552, 382.884, 583.31, 481.274, 782.192, 553.173, 422.67, 215.232, 1044.28, 1330.01, }, + { 146.373, 541.225, 208.926, 540.856, 436.606, 471.832, 511.517, 457.22, 640.312, 619.294, 1186.78, 800.391, 1103.65, 1238.79, 443.001, 356.721, 296.184, 80.1561, 332.415, 236.008, 150, 104.403, 152.315, 420.862, 555.563, 853.302, 931.451, 844.349, 445.225, 305.164, 0, 190.066, 948.117, 281.114, 268.002, 270.647, 354.295, 385.649, 310.483, 353.023, 408.717, 438.919, 583.31, 285.351, 292.959, 415.933, 895.879, 413.673, 197.8, 262.011, 935.575, 1355.91, }, + { 90.5538, 730, 245.204, 370.54, 270.185, 305.041, 701.231, 338.711, 510.025, 471.01, 1030.98, 650.577, 1004.15, 1160.87, 270.416, 330.946, 430, 162.788, 219.829, 300.375, 340.037, 97.0824, 267.442, 263.059, 408.932, 765.506, 823.119, 725.155, 492.392, 446.598, 190.066, 0, 758.716, 151.162, 130.384, 122.984, 202.608, 220.907, 148.071, 185.607, 311.488, 628.033, 393.732, 207.002, 151.327, 312.13, 845, 260.864, 50, 305.655, 767.349, 1238.4, }, + { 827.315, 1488.71, 903.396, 517.349, 589.958, 568.243, 1459.63, 645.155, 570.197, 500.899, 706.134, 584.209, 1010.36, 1215.91, 568.705, 897.065, 1120.29, 903.244, 700.589, 990.013, 1097.96, 852.951, 1001.96, 620.846, 605.826, 917.306, 861.931, 766.551, 1095.67, 1172.9, 948.117, 758.716, 0, 734.098, 731.745, 720.226, 668.506, 625.5, 678.62, 642.028, 704.006, 1386.73, 365, 798.812, 687.786, 747.011, 1095.18, 636.318, 763.708, 973.666, 474.684, 1088.73, }, + { 135.093, 782.081, 393.605, 266.552, 163.248, 196.977, 760.345, 455, 606.98, 552.268, 905.884, 520, 854.181, 1009.72, 176.139, 211.483, 561.471, 290.259, 350.892, 256.564, 416.203, 180.069, 275, 142.302, 275, 614.37, 674.259, 578.705, 401.995, 439.318, 281.114, 151.162, 734.098, 0, 21.2132, 33.541, 76.1577, 115.109, 58.5235, 92.1954, 441.616, 684.416, 382.394, 80, 276.134, 161.012, 697.227, 133.417, 105.119, 243.772, 656.22, 1092.62, }, + { 121.655, 776.981, 373.664, 275.136, 170.88, 205.548, 754.205, 435.46, 589.428, 536.144, 920.34, 535.21, 874.314, 1030.59, 181.177, 228.528, 544.518, 272.947, 330.189, 261.773, 406.356, 165.303, 272.809, 152.971, 290.388, 635.138, 693.992, 597.704, 415.752, 441.192, 268.002, 130.384, 731.745, 21.2132, 0, 15, 86.3134, 120.83, 53.1507, 93.0054, 421.1, 678.473, 376.464, 96.1769, 255.539, 182.003, 718.418, 145.774, 85.44, 251.645, 667.776, 1111.54, }, + { 125, 785, 367.696, 270.601, 166.208, 201.308, 761.577, 421.545, 574.674, 521.177, 920.054, 535.84, 881.192, 1039.25, 174.642, 243.311, 542.794, 271.155, 317.569, 275.045, 411.4, 166.883, 282.931, 150.748, 291.548, 643.525, 700.179, 602.764, 430.726, 453.018, 270.647, 122.984, 720.226, 33.541, 15, 0, 85, 115.434, 43.0116, 85, 408.167, 686.003, 363.593, 111.018, 242.745, 191.442, 729.555, 145, 81.3941, 265.707, 665.019, 1116.36, }, + { 207.966, 857.7, 447.465, 190.394, 87.4643, 120.83, 836.316, 460.57, 596.091, 533.667, 835.06, 450.999, 806.923, 971.404, 102.591, 244.182, 627.415, 355.879, 371.248, 322.684, 491.859, 251.247, 349.464, 66.7083, 207.183, 575.543, 624.119, 523.927, 443.847, 509.117, 354.295, 202.608, 668.506, 76.1577, 86.3134, 85, 0, 43.0116, 55.9017, 41.2311, 457.739, 760.345, 327.3, 130.384, 297.069, 138.654, 676.036, 60, 165.68, 305.164, 581.485, 1036.4, }, + { 240.416, 896.939, 462.088, 155.242, 50.9902, 86.3134, 874.714, 446.01, 571.948, 506.211, 810.386, 429.942, 804.316, 974.59, 61.0328, 283.769, 650.308, 380.132, 366.231, 365.548, 526.711, 281.469, 390.032, 44.7214, 191.377, 580, 620.101, 516.769, 484.2, 551.589, 385.649, 220.907, 625.5, 115.109, 120.83, 115.434, 43.0116, 0, 75.6637, 35.3553, 449.027, 798.89, 286.4, 173.349, 294.109, 163.783, 690.67, 49.4975, 191.05, 348.174, 550.84, 1026.17, }, + { 166.208, 827.964, 392.237, 230.489, 126.59, 161.941, 804.394, 413.824, 557.853, 499.925, 885.127, 503.016, 862.699, 1026.16, 132.853, 265.047, 575.782, 305, 318.904, 313.847, 453.1, 206.155, 325.576, 115.434, 260.864, 630.179, 680, 579.763, 458.939, 494.292, 310.483, 148.071, 678.62, 58.5235, 53.1507, 43.0116, 55.9017, 75.6637, 0, 42.72, 407.001, 728.869, 324.423, 136.473, 244.182, 186.011, 726.223, 112.805, 115.434, 302.076, 626.498, 1092.02, }, + { 208.926, 869.741, 426.878, 188.282, 85.1469, 120.416, 846.537, 421.574, 555, 492.443, 845.532, 465.296, 836.376, 1004.45, 90.1388, 282.179, 615.183, 345.326, 336.341, 348.174, 495.807, 248.646, 365.548, 79.0569, 226.108, 609.139, 652.553, 550.091, 480.521, 531.507, 353.023, 185.607, 642.028, 92.1954, 93.0054, 85, 41.2311, 35.3553, 42.72, 0, 421.1, 770.925, 293.471, 161.555, 263.154, 179.234, 714.37, 80.6226, 157.003, 333.654, 584.829, 1060.39, }, + { 395.38, 896.172, 246.982, 544.541, 479.505, 504.009, 857.555, 64.0312, 239.27, 243.977, 1180.04, 836.316, 1248.08, 1423.04, 464.004, 640.781, 442.634, 330.492, 91.9239, 601.041, 525.024, 377.69, 545.023, 491.757, 628.013, 1028.99, 1063.04, 956.151, 801.639, 712.969, 408.717, 311.488, 704.006, 441.616, 421.1, 408.167, 457.739, 449.027, 407.001, 421.1, 0, 796.492, 401.995, 512.079, 165.605, 593.001, 1133.16, 498.523, 359.34, 611.882, 896.354, 1453.08, }, + { 565.796, 102.591, 550.091, 950.329, 847.659, 881.036, 76.1577, 855.862, 1035.59, 1031.95, 1552.32, 1169.63, 1371.31, 1457.48, 859.593, 639.531, 408.075, 492.976, 741.923, 476.707, 289.914, 535.023, 415.03, 825.121, 936.376, 1120.1, 1226.23, 1163.45, 570.636, 315.159, 438.919, 628.033, 1386.73, 684.416, 678.473, 686.003, 760.345, 798.89, 728.869, 770.925, 796.492, 0, 1021.76, 650.865, 720.85, 768.668, 1092.54, 814.079, 627.156, 509.902, 1329, 1645.07, }, + { 463.816, 1123.71, 556.597, 245.204, 266.693, 260.048, 1094.81, 359.026, 389.936, 307.774, 789.24, 484.381, 930.86, 1125.28, 241.868, 570.088, 773.256, 541.133, 367.764, 638.161, 733.246, 488.109, 641.132, 297.7, 354.401, 755.794, 751.033, 641.112, 770.6, 815.552, 583.31, 393.732, 365, 382.394, 376.464, 363.593, 327.3, 286.4, 324.423, 293.471, 401.995, 1021.76, 0, 455, 336.786, 437.321, 904.461, 313.249, 399.906, 626.099, 504.232, 1097.2, }, + { 154.434, 744.883, 434.195, 307.002, 212.25, 240.832, 726.997, 529.74, 685.584, 631.981, 912.921, 526.118, 821.721, 966.398, 231.138, 132.382, 579.008, 315.357, 420.387, 194.486, 401.528, 199.06, 235.85, 183.984, 286.4, 574.674, 647.012, 559.017, 322.49, 382.884, 285.351, 207.002, 798.812, 80, 96.1769, 111.018, 130.384, 173.349, 136.473, 161.555, 512.079, 650.865, 455, 0, 346.771, 130.863, 640.41, 170.294, 157.003, 175, 678.399, 1070.81, }, + { 240.208, 823.286, 219.829, 411.096, 331.21, 360.069, 789.383, 187.417, 360.867, 329.014, 1067.95, 705.301, 1098.33, 1267.57, 319.883, 476.366, 436.578, 228.035, 75, 450.028, 433.042, 232.648, 406.971, 338.378, 481.274, 872.067, 913.906, 809.475, 643.623, 583.31, 292.959, 151.327, 687.786, 276.134, 255.539, 242.745, 297.069, 294.109, 244.182, 263.154, 165.605, 720.85, 336.786, 346.771, 0, 429.564, 969.91, 343.001, 196.469, 456.755, 790.142, 1314.96, }, + { 279.866, 859.084, 552.675, 230.705, 170.66, 182.003, 844.423, 598.54, 733.894, 669.645, 786.67, 401.404, 696.024, 848.764, 195.576, 155.724, 708.255, 441.277, 504.48, 295.466, 530.377, 325.73, 356.931, 140.089, 173.349, 453.679, 518.652, 428.515, 349.178, 481.274, 415.933, 312.13, 747.011, 161.012, 182.003, 191.442, 138.654, 163.783, 186.011, 179.234, 593.001, 768.668, 437.321, 130.863, 429.564, 0, 540.37, 125, 265, 266.177, 563.649, 941.116, }, + { 791.281, 1151.27, 1072.31, 659.564, 673.591, 661.91, 1156.83, 1135.89, 1257.06, 1185.17, 705.16, 517.422, 324.423, 364.966, 695.593, 539.49, 1187.7, 946.005, 1044.84, 679.779, 957.549, 832.406, 773.692, 652.553, 550.681, 185.54, 291.548, 344.42, 522.805, 782.192, 895.879, 845, 1095.18, 697.227, 718.418, 729.555, 676.036, 690.67, 726.223, 714.37, 1133.16, 1092.54, 904.461, 640.41, 969.91, 540.37, 0, 642.359, 795.503, 646.258, 681.542, 597.746, }, + { 267.301, 910.302, 504.802, 137.295, 47.4342, 70.7107, 890.183, 495.101, 617.839, 550.273, 775.065, 391.152, 755.86, 925.216, 71.5891, 261.964, 687.204, 415.752, 415.482, 364.589, 549.477, 311.006, 400.656, 15.8114, 148.071, 530.519, 571.948, 469.574, 462.385, 553.173, 413.673, 260.864, 636.318, 133.417, 145.774, 145, 60, 49.4975, 112.805, 80.6226, 498.523, 814.079, 313.249, 170.294, 343.001, 125, 642.359, 0, 225.499, 343.111, 522.805, 980.472, }, + { 64.0312, 728.011, 288.487, 345.254, 241.868, 277.218, 701.73, 383.438, 550.568, 507.001, 1000.01, 616.644, 959.284, 1113.56, 246.221, 281.824, 461.736, 190.263, 267.442, 263.866, 344.42, 93.9415, 244.387, 230, 372.726, 718.679, 779.311, 683.118, 448.386, 422.67, 197.8, 50, 763.708, 105.119, 85.44, 81.3941, 165.68, 191.05, 115.434, 157.003, 359.34, 627.156, 399.906, 157.003, 196.469, 265, 795.503, 225.499, 0, 265.189, 741.772, 1196.92, }, + { 217.083, 596.259, 463.249, 477.624, 386.685, 413.793, 584.637, 643.817, 815.138, 771.962, 1042.93, 662.59, 884.59, 1000.12, 406.079, 130.384, 543.622, 328.672, 521.967, 35.3553, 313.129, 237.171, 127.475, 357.526, 439.09, 630.575, 726.395, 656.22, 191.377, 215.232, 262.011, 305.655, 973.666, 243.772, 251.645, 265.707, 305.164, 348.174, 302.076, 333.654, 611.882, 509.902, 626.099, 175, 456.755, 266.177, 646.258, 343.111, 265.189, 0, 829.608, 1150.76, }, + { 789.383, 1421.56, 995.314, 397.02, 499.925, 464.57, 1405.08, 860.145, 883.233, 800.078, 285.044, 188.215, 539.676, 744.648, 497.041, 710.106, 1196.51, 929.368, 843.445, 859.069, 1072.01, 831.865, 914.166, 514.806, 392.747, 496.009, 410.488, 337.231, 871.45, 1044.28, 935.575, 767.349, 474.684, 656.22, 667.776, 665.019, 581.485, 550.84, 626.498, 584.829, 896.354, 1329, 504.232, 678.399, 790.142, 563.649, 681.542, 522.805, 741.772, 829.608, 0, 624.82, }, + { 1220.46, 1716.05, 1483.59, 908.639, 984.441, 954.895, 1715.07, 1430.47, 1486.78, 1404.04, 398.56, 618.567, 278.658, 318.904, 995.113, 1022.67, 1649.37, 1381.2, 1381.96, 1186.09, 1456.71, 1266.49, 1271.42, 981.542, 835.135, 525, 425.793, 513.931, 1081.95, 1330.01, 1355.91, 1238.4, 1088.73, 1092.62, 1111.54, 1116.36, 1036.4, 1026.17, 1092.02, 1060.39, 1453.08, 1645.07, 1097.2, 1070.81, 1314.96, 941.116, 597.746, 980.472, 1196.92, 1150.76, 624.82, 0, }, +}; + +uint8_t optimal_path[] = { + 1, 49, 32, 45, 19, 41, 8, 9, 10, 43, 33, 51, 11, + 52, 14, 13, 47, 26, 27, 28, 12, 25, 4, 6, 15, 5, + 24, 48, 38, 37, 40, 39, 36, 35, 34, 44, 46, 16, 29, + 50, 20, 23, 30, 2, 7, 42, 21, 17, 3, 18, 31, 22, +}; + +#endif // INCLUDED_DATA_H +// data.h ends here diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..2ae69b4 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,66 @@ +#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__KNOWN_CAPACITY(DYNAMIC_ARRAY, ITEM) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + +#define DYNAMIC_ARRAY__APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY__ENSURE_CAPACITY ((DYNAMIC_ARRAY), 1); \ + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY ((DYNAMIC_ARRAY), 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__LAST(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] + +#define DYNAMIC_ARRAY__POP(DYNAMIC_ARRAY) ({ \ + ASSERT ((DYNAMIC_ARRAY).count > 0); \ + (DYNAMIC_ARRAY).items[--(DYNAMIC_ARRAY).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/simple-ant-colony-optimization.c b/src/simple-ant-colony-optimization.c new file mode 100644 index 0000000..9e19feb --- /dev/null +++ b/src/simple-ant-colony-optimization.c @@ -0,0 +1,379 @@ +// simple-ant-colony-optimization.c --- simple ant colony optimization + +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "data.h" +#include "dynamic-array.h" + +#define ANT_COUNT 100 +#define I_START 0 +#define I_END 0 +#define NODE_COUNT ((int) (sizeof (*distances)/sizeof (**distances))) +#define ALPHA 1 +#define BETA 3.5 +#define RHO .4 +#define MAX_GENERATIONS 100 +#define MAX_GENERATIONS_NO_IMPROVEMENT 30 +#define SEED 1763499947 // 7967 +// #define SEED time (NULL) +// #define PLOT_PNG +#define X_MIN ( 25 - 100) +#define X_MAX (1740 + 100) +#define Y_MIN ( 5 - 100) +#define Y_MAX (1175 + 100) + +struct path { + u8 *items; + u32 count; + u32 capacity; +} path = {0}; + +struct crdf { + struct crdf_entry { + f32 c; + u32 j; + } *items; + u32 count; + u32 capacity; +} crdf = {0}; + +f32 pheromones1[NODE_COUNT][NODE_COUNT]; +f32 pheromones2[NODE_COUNT][NODE_COUNT]; + +f32 (*pheromones_current)[NODE_COUNT] = pheromones1; +f32 (*pheromones_next )[NODE_COUNT] = pheromones2; + +u8 shortest_path[NODE_COUNT]; +float shortest_path_length = FLT_MAX; +int shortest_path_generation = 0; + +static u64 visited = 1; + +static f32 distances[NODE_COUNT][NODE_COUNT]; + +f32 +build_crdf (u8 i) +{ + f32 sum = 0; + + if (path.count == NODE_COUNT) { + u8 j = I_END; + + sum += (powf (pheromones_current[i][j], ALPHA) * + powf ( 1/distances[i][j], BETA )); + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (crdf, ((struct crdf_entry) { sum, j })); + return sum; + } + + for (u8 j = 0; j < NODE_COUNT; ++j) { + if (j == I_END) continue; + if (j == i) continue; + if (visited & (u64) 1 << j) continue; + + sum += (powf (pheromones_current[i][j], ALPHA) * + powf ( 1/distances[i][j], BETA )); + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (crdf, ((struct crdf_entry) { sum, j })); + } + + return sum; +} + +f32 +measure_path (void) +{ + f32 distance = 0; + + u8 prev = I_START; + for (u32 i = 1; i < path.count; ++i) { + u8 curr = path.items[i]; + distance += distances[prev][curr]; + prev = curr; + } + + return distance; +} + +int +sort_crdf (const void *lhs, const void *rhs) +{ + const struct crdf_entry *lhs_e = lhs; + const struct crdf_entry *rhs_e = rhs; + + if (lhs_e->c < rhs_e->c) return -1; + if (lhs_e->c > rhs_e->c) return +1; + return 0; +} + +u8 +select_j (u8 i) +{ + DYNAMIC_ARRAY__RESET (crdf); + f32 r = build_crdf (i); + + // NOTE(cmmm): might cause infinite loop + if (crdf.count == 0) { + path.count -= 1; + return DYNAMIC_ARRAY__POP (path); + } + + qsort (crdf.items, crdf.count, sizeof (*crdf.items), sort_crdf); + r *= rand () /(float) RAND_MAX; + + DYNAMIC_ARRAY__FOREACH (e, crdf) { + if (e->c >= r) + return e->j; + } + + UNREACHABLE (); +} + +f32 +remap (f32 value, f32 input_start, f32 input_end, f32 output_start, f32 output_end) +{ + return ((value - input_start) / + ( input_end - input_start) * + (output_end - output_start) + + output_start); +} + +void +plot (const char *output, u8 path[NODE_COUNT], float path_length, int generation, bool pheromones) +{ + FILE *gp = popen ("gnuplot", "w"); + // FILE *gp = fopen ("test.gp", "w"); +#ifdef PLOT_PNG + fprintf (gp, "set term pngcairo\n"); + fprintf (gp, "set output '%s-%02d.png'\n", output, generation); +#else + fprintf (gp, "set term cairolatex pdf input blacktext notransparent" + " nocrop size 15cm,10cm noheader\n"); + fprintf (gp, "set output '%s-%02d.tex'\n", output, generation); +#endif + + fprintf (gp, "set title 'Поколение №%d, \\quad Лучшая особь: %f'\n", + generation, path_length); + fprintf (gp, "set xlabel '\\(x\\)'\n"); + fprintf (gp, "set ylabel '\\(y\\)' norotate\n"); + fprintf (gp, "set xrange [%hd:%hd]\n", X_MIN, X_MAX); + fprintf (gp, "set yrange [%hd:%hd]\n", Y_MIN, Y_MAX); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines lw 9.0 lc 'gray' title '\\small{Оптимальный путь}',"); + fprintf (gp, "'-' with lines lw 3.0 lc 'red' title '\\small{Лучшая особь}',"); + if (pheromones) + fprintf (gp, "'-' with lines lw 1.5 lc rgb var title '\\small{Феромоны}',"); + fprintf (gp, "'-' with points ps 0.5 pt 2 lc 'blue' title '\\small{Координаты}'\n"); + + for (int i = 0; i < NODE_COUNT; ++i) { + struct point p = buildings[optimal_path[i] - 1]; + fprintf (gp, "%hd %hd\n", p.x, p.y); + } fprintf (gp, "%hd %hd\ne\n", + buildings[optimal_path[0] - 1].x, + buildings[optimal_path[0] - 1].y); + + for (int i = 0; i <= NODE_COUNT; ++i) { + struct point p = buildings[path[i]]; + fprintf (gp, "%hd %hd\n", p.x, p.y); + } fprintf (gp, "e\n"); + + if (pheromones) { + f32 min = FLT_MAX; + f32 max = FLT_MIN; + for (int i = 0; i < NODE_COUNT; ++i) { + for (int j = i; j < NODE_COUNT; ++j) { + f32 c = pheromones_current[i][j]; + if (c < min) min = c; + if (c > max) max = c; + } + } + for (int i = 0; i < NODE_COUNT; ++i) { + for (int j = i; j < NODE_COUNT; ++j) { + struct point from = buildings[i]; + struct point to = buildings[j]; + u8 s = remap (pheromones_current[i][j], min, max, 255, 63); + u32 c = s << 24 | 0x000000; + fprintf (gp, "%hd %hd %u\n%hd %hd %u\n\n", from.x, from.y, c, to.x, to.y, c); + } + } fprintf (gp, "e\n"); + } + + for (int i = 0; i < NODE_COUNT; ++i) { + struct point p = buildings[i]; + fprintf (gp, "%hd %hd\n", p.x, p.y); + } fprintf (gp, "e\n"); + + pclose (gp); +} + +struct { + f32 min, average; +} generation_fitness[MAX_GENERATIONS]; + +void +plot__fitness_over_generations (const char *output, int generations) +{ + FILE *gp = popen ("gnuplot", "w"); + // FILE *gp = fopen ("test.gp", "w"); +#ifdef PLOT_PNG + fprintf (gp, "set term pngcairo\n"); + fprintf (gp, "set output '%s.png'\n", output); +#else + fprintf (gp, "set term cairolatex pdf input blacktext notransparent" + " nocrop size 15cm,10cm noheader\n"); + fprintf (gp, "set output '%s.tex'\n", output); +#endif + + fprintf (gp, "set xrange [0:%d]\n", MAX_GENERATIONS); + fprintf (gp, "set yrange [7000:13000]\n"); + fprintf (gp, "set xlabel '№ поколения'\n"); + fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n"); + fprintf (gp, "set y2range [7000:13000]\n"); + fprintf (gp, "set y2tics ('7498.270020' 7498.270020, '7966.763184' 7966.763184)\n"); + fprintf (gp, "set xtics (%d, %d)\n", shortest_path_generation, generations); + fprintf (gp, "set x2tics\n"); + fprintf (gp, "set arrow from %d, graph 0 to %d,%f nohead lc 1 dt 2\n", shortest_path_generation, shortest_path_generation, shortest_path_length); + fprintf (gp, "set arrow from %d,%f to %d,%f nohead lc 1 dt 2\n", shortest_path_generation, shortest_path_length, MAX_GENERATIONS, shortest_path_length); + fprintf (gp, "set arrow from %d, graph 0 to %d, graph 1 nohead lc 4 dt 3\n", generations, generations); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines title 'Лучшее значение',"); + fprintf (gp, "'-' with lines title 'Среднее значение',"); + fprintf (gp, "7498.270020 title 'Оптимальное значение'\n"); + + for (int i = 0; i <= generations; ++i) { + fprintf (gp, "%d %f\n", i, generation_fitness[i].min); + } fprintf (gp, "e\n"); + + for (int i = 0; i <= generations; ++i) { + fprintf (gp, "%d %f\n", i, generation_fitness[i].average); + } fprintf (gp, "e\n"); + + pclose (gp); +} + +int +main (void) +{ + printf ("%u\n", (u32) SEED); + srand (SEED); + + DYNAMIC_ARRAY__ENSURE_CAPACITY (crdf, NODE_COUNT); + DYNAMIC_ARRAY__ENSURE_CAPACITY (path, NODE_COUNT); + + // init pheromones + for (u16 i = 0; i < NODE_COUNT; ++i) { + for (u16 j = i; j < NODE_COUNT; ++j) { + f32 c = rand () /(float) RAND_MAX; + pheromones_current[i][j] = c; + pheromones_current[j][i] = c; + } + } + + u8 last_improvement = 0; + int generation; + for (generation = 0; generation < MAX_GENERATIONS; ++generation) { + u8 generation_shortest_path[NODE_COUNT]; + float generation_shortest_path_length = FLT_MAX; + + printf ("generation: %4d ", generation); + + // prepare next pheromones + memcpy (pheromones_next, pheromones_current, + NODE_COUNT*NODE_COUNT*sizeof (**pheromones_next)); + for (u16 i = 0; i < NODE_COUNT*NODE_COUNT; ++i) + (*pheromones_next)[i] *= 1 - RHO; + + f32 path_length_sum = 0; + // for each ant build path + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (path, I_START); + for (u16 k = 0; k < ANT_COUNT; ++k) { + visited = 1; + u8 i = I_START; // ants current location + path.count = 1; + while (i != I_END || path.count == 1) { + u8 j = select_j (i); + DYNAMIC_ARRAY__APPEND (path, j); + visited |= (u64) 1 << j; + i = j; + } + + // eliminate loops + eliminate_loop: + for (u32 i = 0; i < path.count; ++i) { + for (u32 j = i + 1; j < path.count - 1; ++j) { + if (path.items[j] == path.items[i]) { + memmove (&path.items[i + 1], &path.items[j + 1], + (path.count - j)*sizeof (*path.items)); + path.count -= j - i; + goto eliminate_loop; + } + } + } + + f32 path_length = measure_path (); + path_length_sum += path_length; + if (path_length < shortest_path_length) { + shortest_path_length = path_length; + memcpy (shortest_path, path.items, sizeof (shortest_path)); + last_improvement = generation; + shortest_path_generation = generation; + } + if (path_length < generation_shortest_path_length) { + generation_shortest_path_length = path_length; + memcpy (generation_shortest_path, path.items, + sizeof (generation_shortest_path)); + } + + // print path + if (k == 0) { + DYNAMIC_ARRAY__FOREACH (point, path) { + if (point == path.items) printf ("%d", *point); + else printf (" -> %d", *point); + } printf (" %5.f\n", path_length); + } + + // update pheromones + i = I_START; + f32 delta_tau = 1./path_length; + for (const u8 *jp = &path.items[1]; jp < path.items + path.count; ++jp) { + u8 j = *jp; + pheromones_next[i][j] += delta_tau; + pheromones_next[j][i] += delta_tau; + i = j; + } + } + // plot best of generation + plot ("./res/path", generation_shortest_path, + generation_shortest_path_length, generation, generation >= 10); + + generation_fitness[generation].min = generation_shortest_path_length; + generation_fitness[generation].average = path_length_sum/ANT_COUNT; + + SWAP_PTR (pheromones_current, pheromones_next); + + if (generation - last_improvement > MAX_GENERATIONS_NO_IMPROVEMENT) + break; + } + + printf ("shortest-at: %3d ", shortest_path_generation); + DYNAMIC_ARRAY__FOREACH (point, path) { + if (point == path.items) printf ("%d", *point); + else printf (" -> %d", *point); + } printf (" %5.f\n", shortest_path_length); + + plot ("./res/best-path", shortest_path, shortest_path_length, + shortest_path_generation, false); + + plot__fitness_over_generations ("./res/convergence", generation); + + return EXIT_SUCCESS; +} + +// simple-ant-colony-optimization.c ends here diff --git a/src/task2.c b/src/task2.c new file mode 100644 index 0000000..e290c95 --- /dev/null +++ b/src/task2.c @@ -0,0 +1,8 @@ +#include +#include +#include +#include "utils.h" +#include "dynamic-array.h" +#include "task2.h" +#include "common.h" + diff --git a/src/task2.h b/src/task2.h new file mode 100644 index 0000000..cb1e225 --- /dev/null +++ b/src/task2.h @@ -0,0 +1,18 @@ +#ifndef INCLUDED_TASK2_H +#define INCLUDED_TASK2_H + +#include + +#define ANT_COUNT 100 +#define I_START 0 +#define I_END 0 +#define NODE_COUNT 52 +#define ALPHA 1 +#define BETA 3.5 +#define RHO .4 +#define MAX_GENERATIONS 100 +#define MAX_GENERATIONS_NO_IMPROVEMENT 30 +#define SEED 1763499947 // 7967 +// #define SEED time (NULL) + +#endif // INCLUDED_TASK2_H diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..02b24b9 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,54 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert +// #define ASSERT(...) + +#define UNUSED(X) ((void) (X)) +#define UNREACHABLE() ASSERT (0) + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; +typedef float f32; + +#define XOR_SWAP(A, B) ({ \ + A ^= B; \ + B ^= A; \ + A ^= B; \ + }) + +#define SWAP_PTR(A, B) ({ \ + void *__swap_ptr_tmp = A; \ + A = B; \ + B = __swap_ptr_tmp; \ + }) + +#define DIAGONAL_MATRIX_COUNT(LENGTH) ((LENGTH)*((LENGTH) + 1)/2) +inline bool bitarray__get (u8 *arr, u8 i) { return (arr[i/8] >> (7 - i)) & 1; } +inline void bitarray__set (u8 *arr, u8 i) { arr[i/8] |= 1 << (7 - i); } +inline void bitarray__clear (u8 *arr, u8 i) { arr[i/8] &= ~(1 << (7 - i)); } + +inline u8 +diagonal_matrix_index (u8 side, u8 i, u8 j) +{ + ASSERT (i < side); + ASSERT (j < side); + + if (j < i) + XOR_SWAP (i, j); + + return (DIAGONAL_MATRIX_COUNT (side) - + DIAGONAL_MATRIX_COUNT (side - i) + + (j - i)); +} + +#endif // INCLUDED_UTILS_H -- cgit v1.3.1