Migrate to Zensical (#1869)

* Fix Russian Ruby code extraction.

* Add zensical configs.
This commit is contained in:
Yudong Jin
2026-03-29 05:41:25 +08:00
committed by GitHub
parent bc4c5ec414
commit 7a78369e4c
84 changed files with 1302 additions and 445 deletions

7
.gitignore vendored
View File

@@ -1,12 +1,7 @@
# macOS
.DS_Store
# editors
.vscode/
**/.idea
# mkdocs files
.cache/
/node_modules
# build
/build

View File

@@ -9,6 +9,8 @@
{% set announcements = 'Welcome to contribute to Chinese-to-English translation! For more details, please refer to <a href="https://github.com/krahets/hello-algo/blob/main/en/CONTRIBUTING.md">CONTRIBUTING.md</a>.' %}
{% elif config.theme.language == 'ja' %}
{% set announcements = '日本語版審閱者を募集しています!詳細は <a href="https://github.com/krahets/hello-algo/blob/main/ja/CONTRIBUTING.md">CONTRIBUTING.md</a> を参照してください。' %}
{% elif config.theme.language == 'ru' %}
{% set announcements = 'Приглашаем вас участвовать в развитии русской версии! Подробнее <a href="/ru/chapter_appendix/contribution/">здесь</a>.' %}
{% endif %}
<div class="banner-svg">
<svg xmlns="http://www.w3.org/2000/svg"

View File

@@ -1 +0,0 @@
comments.html

View File

@@ -0,0 +1,71 @@
{% if page.meta.comments %}
{% if config.theme.language == 'zh' %}
{% set comm = "欢迎在评论区留下你的见解、问题或建议" %}
{% set lang = "zh-CN" %}
{% elif config.theme.language == 'zh-Hant' %}
{% set comm = "歡迎在評論區留下你的見解、問題或建議" %}
{% set lang = "zh-TW" %}
{% elif config.theme.language == 'en' %}
{% set comm = "Feel free to drop your insights, questions or suggestions" %}
{% set lang = "en" %}
{% elif config.theme.language == 'ja' %}
{% set comm = "ご意見、ご質問、ご提案があればぜひコメントしてください" %}
{% set lang = "ja" %}
{% elif config.theme.language == 'ru' %}
{% set comm = "Оставляйте свои идеи, вопросы и предложения в комментариях" %}
{% set lang = "ru" %}
{% endif %}
<!-- Check-in button above comments -->
{% include "partials/checkin.html" ignore missing %}
<h5 align="center" id="__comments">{{ comm }}</h5>
<!-- Insert generated snippet here -->
<script
src="https://giscus.app/client.js"
data-repo="krahets/hello-algo"
data-repo-id="R_kgDOIXtSqw"
data-category="Announcements"
data-category-id="DIC_kwDOIXtSq84CSZk_"
data-mapping="pathname"
data-strict="1"
data-reactions-enabled="1"
data-emit-metadata="1"
data-input-position="top"
data-theme="light"
data-lang="{{ lang }}"
crossorigin="anonymous"
async
>
</script>
<!-- Synchronize Giscus theme with palette -->
<script>
var giscus = document.querySelector("script[src*=giscus]")
/* Set palette on initial load */
var palette = __md_get("__palette")
if (palette && typeof palette.color === "object") {
var theme = palette.color.scheme === "slate" ? "dark_dimmed" : "light"
giscus.setAttribute("data-theme", theme)
}
/* Register event handlers after documented loaded */
document.addEventListener("DOMContentLoaded", function() {
var ref = document.querySelector("[data-md-component=palette]")
ref.addEventListener("change", function() {
var palette = __md_get("__palette")
if (palette && typeof palette.color === "object") {
var theme = palette.color.scheme === "slate" ? "dark_dimmed" : "light"
/* Instruct Giscus to change theme */
var frame = document.querySelector(".giscus-frame")
frame.contentWindow.postMessage(
{ giscus: { setConfig: { theme } } },
"https://giscus.app"
)
}
})
})
</script>
{% endif %}

View File

@@ -0,0 +1,770 @@
/* Color Settings */
/* https://github.com/squidfunk/mkdocs-material/blob/6b5035f5580f97532d664e3d1babf5f320e88ee9/src/assets/stylesheets/main/_colors.scss */
/* https://squidfunk.github.io/mkdocs-material/setup/changing-the-colors/#custom-colors */
:root>* {
--md-primary-fg-color: #ffffff;
--md-primary-bg-color: #1d1d20;
--md-default-fg-color: #1d1d20;
--md-default-bg-color: #ffffff;
--md-body-bg-color: #22272e;
--md-header-bg-color: rgba(255, 255, 255, 0.6);
--md-code-fg-color: #1d1d20;
--md-code-bg-color: #f5f5f5;
--md-accent-fg-color: #999;
--md-typeset-color: #1d1d20;
--md-typeset-a-color: #349890;
--md-typeset-btn-color: #55aea6;
--md-typeset-btn-hover-color: #52bbb1;
--md-admonition-icon--pythontutor: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19.14 7.5A2.86 2.86 0 0 1 22 10.36v3.78A2.86 2.86 0 0 1 19.14 17H12c0 .39.32.96.71.96H17v1.68a2.86 2.86 0 0 1-2.86 2.86H9.86A2.86 2.86 0 0 1 7 19.64v-3.75a2.85 2.85 0 0 1 2.86-2.85h5.25a2.85 2.85 0 0 0 2.85-2.86V7.5h1.18m-4.28 11.79c-.4 0-.72.3-.72.89 0 .59.32.71.72.71a.71.71 0 0 0 .71-.71c0-.59-.32-.89-.71-.89m-10-1.79A2.86 2.86 0 0 1 2 14.64v-3.78A2.86 2.86 0 0 1 4.86 8H12c0-.39-.32-.96-.71-.96H7V5.36A2.86 2.86 0 0 1 9.86 2.5h4.28A2.86 2.86 0 0 1 17 5.36v3.75a2.85 2.85 0 0 1-2.86 2.85H8.89a2.85 2.85 0 0 0-2.85 2.86v2.68H4.86M9.14 5.71c.4 0 .72-.3.72-.89 0-.59-.32-.71-.72-.71-.39 0-.71.12-.71.71s.32.89.71.89Z"/></svg>');
--md-admonition-pythontutor-color: #eee;
}
[data-md-color-scheme="slate"] {
--theme-dark-base: #1E1E1E;
--theme-dark-mantle: #1A1A1A;
--theme-dark-crust: #171717;
--hero-starfield-bg-color: var(--theme-dark-base);
--md-primary-fg-color: var(--theme-dark-base);
--md-primary-bg-color: #adbac7;
--md-default-fg-color: #adbac7;
--md-default-bg-color: var(--theme-dark-base);
--md-body-bg-color: var(--theme-dark-mantle);
--md-header-bg-color: rgba(26, 26, 26, 0.8);
--md-code-fg-color: #adbac7;
--md-code-bg-color: var(--theme-dark-crust);
--md-accent-fg-color: #aaa;
--md-footer-fg-color: #adbac7;
--md-footer-bg-color: var(--theme-dark-mantle);
--md-typeset-color: #adbac7;
--md-typeset-a-color: #52bbb1;
--md-typeset-btn-color: #52bbb1;
--md-typeset-btn-hover-color: #55aea6;
--md-admonition-pythontutor-color: var(--theme-dark-crust);
}
[data-md-color-scheme="slate"][data-md-color-primary="black"],
[data-md-color-scheme="slate"][data-md-color-primary="white"] {
--md-typeset-a-color: #52bbb1;
}
[data-md-color-scheme="slate"] .md-footer,
[data-md-color-scheme="slate"] .md-footer__inner {
background-color: var(--theme-dark-mantle);
color: var(--md-footer-fg-color);
}
[data-md-color-scheme="slate"] .md-footer-meta {
background-color: var(--theme-dark-crust);
color: var(--md-footer-fg-color);
}
[data-md-color-scheme="slate"] .md-footer__link {
background-color: var(--theme-dark-crust);
color: var(--md-footer-fg-color);
}
[data-md-color-scheme="slate"] .md-footer__link:hover {
background-color: var(--theme-dark-base);
}
[data-md-color-scheme="slate"] .md-footer__title,
[data-md-color-scheme="slate"] .md-footer__direction,
[data-md-color-scheme="slate"] .md-footer__button,
[data-md-color-scheme="slate"] .md-copyright,
[data-md-color-scheme="slate"] .md-copyright a,
[data-md-color-scheme="slate"] .md-social,
[data-md-color-scheme="slate"] .md-social__link {
color: var(--md-footer-fg-color);
}
/* https://github.com/squidfunk/mkdocs-material/issues/4832#issuecomment-1374891676 */
.md-nav__link[for] {
color: var(--md-default-fg-color) !important;
}
/* Figure class */
.animation-figure {
border-radius: 0.3rem;
display: block;
margin: 0 auto;
box-shadow: var(--md-shadow-z2);
}
/* Cover image class */
.cover-image {
width: 28rem;
height: auto;
border-radius: 0.3rem;
display: block;
margin: 0 auto;
box-shadow: var(--md-shadow-z2);
}
/* Center Markdown Tables (requires md_in_html extension) */
.center-table {
text-align: center;
}
/* Reset alignment for table cells */
.md-typeset .center-table :is(td, th):not([align]) {
text-align: initial;
}
/* Font size */
.md-typeset {
font-size: 0.75rem;
line-height: 1.5;
}
.md-typeset pre {
font-size: 0.95em;
}
/* Markdown Header */
/* https://github.com/squidfunk/mkdocs-material/blob/dcab57dd1cced4b77875c1aa1b53467c62709d31/src/assets/stylesheets/main/_typeset.scss */
.md-typeset h1 {
font-weight: 400;
color: var(--md-default-fg-color);
}
.md-typeset h2 {
font-weight: 400;
}
.md-typeset h3 {
font-weight: 500;
}
.md-typeset h5 {
text-transform: none;
}
.md-typeset a:hover {
color: var(--md-typeset-a-color);
text-decoration: underline;
}
.md-typeset code {
border-radius: 0.2rem;
}
.highlight span.filename {
font-weight: normal;
}
/* font-family setting for Win10 */
body {
--md-text-font-family: -apple-system, BlinkMacSystemFont,
var(--md-text-font, _), Helvetica, Arial, sans-serif;
--md-code-font-family: var(--md-code-font, _), SFMono-Regular, Consolas, Menlo,
-apple-system, BlinkMacSystemFont, var(--md-text-font, _), monospace;
}
/* max height of code block */
/* https://github.com/squidfunk/mkdocs-material/issues/3444 */
.md-typeset pre>code {
max-height: 25rem;
}
/* Keep code block scrollbar hover neutral instead of accent-colored */
.md-typeset pre>code:hover {
scrollbar-color: var(--md-default-fg-color--lighter) transparent;
}
.md-typeset pre>code::-webkit-scrollbar-thumb:hover {
background-color: var(--md-default-fg-color--lighter);
}
/* Make the picture not glare in dark theme */
[data-md-color-scheme="slate"] .md-typeset img,
[data-md-color-scheme="slate"] .md-typeset svg,
[data-md-color-scheme="slate"] .md-typeset video {
filter: brightness(0.85) invert(0.05);
}
/* landing page */
.header-img-div {
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto;
width: 100%;
/* Default to full width */
}
/* Admonition for python tutor */
.md-typeset .admonition.pythontutor,
.md-typeset details.pythontutor {
border-color: var(--md-default-fg-color--lightest);
margin-top: 0;
margin-bottom: 1.5625em;
}
.md-typeset .pythontutor>.admonition-title,
.md-typeset .pythontutor>summary {
background-color: var(--md-code-bg-color);
}
.md-typeset .pythontutor>.admonition-title::before,
.md-typeset .pythontutor>summary::before {
background-color: rgb(55, 118, 171);
-webkit-mask-image: var(--md-admonition-icon--pythontutor);
mask-image: var(--md-admonition-icon--pythontutor);
}
/* code block tabs */
.md-typeset .tabbed-labels>label {
font-size: 0.61rem;
}
.md-typeset .tabbed-labels--linked>label>a {
padding: .78125em 1.0em .625em;
}
/* header banner */
.md-banner {
background-color: var(--md-code-bg-color);
color: var(--md-default-fg-color);
font-size: 0.75rem;
}
.md-banner .banner-svg svg {
margin-right: 0.3rem;
height: 0.63rem;
fill: var(--md-default-fg-color);
}
.pythontutor-iframe {
width: 125%;
height: 125%;
max-width: 125% !important;
max-height: 125% !important;
transform: scale(0.8);
transform-origin: top left;
border: none;
}
/* landing page container */
.home-div {
width: 100%;
height: auto;
display: flex;
justify-content: center;
align-items: center;
background-color: var(--md-default-bg-color);
color: var(--md-default-fg-color);
font-size: 0.9rem;
padding: 3em 2em;
text-align: center;
}
.section-content {
width: 100%;
height: auto;
max-width: 70vw;
}
/* rounded button */
.rounded-button {
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 10em;
margin: 0 0.1em;
padding: 0.6em 1.3em;
border: none;
background-color: var(--md-typeset-btn-color);
color: var(--md-primary-fg-color) !important;
text-align: center;
text-decoration: none;
cursor: pointer;
}
.rounded-button:hover {
background-color: var(--md-typeset-btn-hover-color);
}
.rounded-button span {
margin: 0;
margin-bottom: 0.07em;
white-space: nowrap;
}
.rounded-button svg {
fill: var(--md-primary-fg-color);
width: auto;
height: 1.2em;
margin-right: 0.5em;
}
/* device image */
.device-on-hover {
width: auto;
transition: transform 0.3s ease-in-out, filter 0.3s ease-in-out;
}
a:hover .device-on-hover {
filter: drop-shadow(0 0 0.2rem rgba(0, 0, 0, 0.15));
transform: scale(1.01);
}
/* text button */
.reading-media {
display: flex;
justify-content: center;
align-items: flex-end;
height: 32vw;
}
.media-block {
height: 100%;
margin: 0 0.2em;
}
.text-button {
width: auto;
color: var(--md-typeset-btn-color);
text-decoration: none;
text-align: center;
margin: 2.7em auto;
}
.text-button span {
white-space: nowrap;
}
.text-button svg {
display: inline-block;
fill: var(--md-typeset-btn-color);
width: auto;
height: 0.9em;
background-size: cover;
padding-top: 0.17em;
margin-left: 0.15em;
}
a:hover .text-button span {
text-decoration: underline;
}
/* hero image */
.hero-div {
height: min(84vh, 75vw);
width: min(112vh, 100vw);
margin: 0 auto;
margin-top: -2.4rem;
padding: 0;
position: relative;
font-size: min(1.8vh, 2.5vw);
font-weight: normal;
}
.hero-bg {
height: 100%;
width: 100%;
object-fit: cover;
position: absolute;
}
/* hover on the planets */
.hero-div>a>img {
width: auto;
position: absolute;
transition: transform 0.3s ease-in-out, filter 0.3s ease-in-out;
}
.hero-div>a>span {
margin: 0;
position: absolute;
transform: translateX(-50%) translateY(-50%);
white-space: nowrap;
/* prevent line breaks */
color: white;
}
.hero-div>a:hover>img {
filter: brightness(1.15) saturate(1.1) drop-shadow(0 0 0.5rem rgba(255, 255, 255, 0.2));
transform: scale(1.03);
}
.hero-div>a:hover>span {
text-decoration: underline;
color: var(--md-typeset-btn-color);
}
.heading-div {
width: 100%;
position: absolute;
transform: translateX(-50%);
left: 50%;
bottom: min(2vh, 3vw);
pointer-events: none;
color: #fff;
}
/* code badge */
.code-badge {
width: 100%;
height: auto;
margin: 1em auto;
}
.code-badge img {
height: 1.07em;
width: auto;
}
/* brief intro */
.intro-container {
display: flex;
align-items: center;
margin: 2em auto;
}
.intro-image {
flex-shrink: 0;
flex-grow: 0;
width: 50%;
border-radius: 0.5em;
box-shadow: var(--md-shadow-z2);
}
.intro-text {
flex-grow: 1;
/* fill the space */
display: flex;
flex-direction: column;
justify-content: center;
text-align: left;
align-items: flex-start;
width: fit-content;
margin: 2em;
}
.intro-text>div {
align-self: flex-start;
width: auto;
margin: 0 auto;
}
.endor-text {
width: 50%;
}
.intro-quote {
color: var(--md-accent-fg-color);
font-weight: bold;
}
/* contributors table */
.profile-div {
display: flex;
flex-wrap: wrap;
justify-content: center;
max-width: 40em;
margin: 1em auto;
}
.profile-cell {
flex: 1 1 15%;
margin: 1em 0;
text-align: center;
}
.profile-img {
width: 5em;
border-radius: 50%;
margin-bottom: 0.5em;
}
.translator-profile-div {
gap: 0.5em;
}
.translator-profile-cell {
flex: 0 0 auto;
margin: 0.5em 0;
min-width: 8.5em;
}
.giscus-container {
width: 40em;
max-width: 100%;
margin: 0 auto;
}
/* Hide navigation */
@media screen and (max-width: 76.25em) {
.section-content {
max-width: 95vw;
}
.reading-media {
height: 33vw;
}
.contrib-image {
width: 100%;
}
}
/* mobile devices */
@media screen and (max-width: 60em) {
.home-div {
font-size: 0.75rem;
}
.hero-div {
margin-top: -4rem;
}
.intro-container {
flex-direction: column;
}
.intro-text {
width: auto;
order: 2;
margin: 0 auto;
}
.endor-text {
width: auto;
margin: 0 auto;
}
.intro-image {
width: 100%;
order: 1;
margin-bottom: 1em;
}
.text-button {
margin: 0.7em auto;
}
.profile-cell {
flex: 1 1 30%;
}
}
.video-container {
position: relative;
padding-bottom: 56.25%;
/* 16:9 */
height: 0;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* starfield */
.starfield {
position: absolute;
width: 100%;
height: 100%;
z-index: 0;
background-color: var(--hero-starfield-bg-color, transparent);
}
.starfield-origin {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Zensical-specific adjustments merged into the main stylesheet. */
:root>* {
--md-accent-fg-color: var(--md-typeset-a-color);
--md-admonition-pythontutor-color: var(--md-code-bg-color);
--hello-algo-sidebar-width: 13rem;
}
[data-md-color-scheme="slate"] {
--md-accent-fg-color: var(--md-typeset-a-color);
--md-admonition-pythontutor-color: var(--md-code-bg-color);
--md-body-bg-color: var(--md-default-bg-color);
--md-default-bg-color--light: rgb(30 30 30 / 0.8);
}
[data-md-color-scheme="slate"] .md-typeset details.pythontutor[open]> :not(summary),
[data-md-color-scheme="slate"] .md-typeset details.pythontutor[open]> :not(summary) :is(p, li, strong, em, sub, sup, code, a) {
background-color: #f5f5f5;
color: #1d1d20;
}
body {
background-color: var(--md-default-bg-color);
}
html:has(body[data-md-color-scheme="slate"]) {
background-color: #1e1e1e;
}
html:has(body[data-md-color-scheme="default"]) {
background-color: #ffffff;
}
.home-div[data-md-color-scheme="default"],
.home-div[data-md-color-scheme="default"] h1,
.home-div[data-md-color-scheme="default"] h2,
.home-div[data-md-color-scheme="default"] h3,
.home-div[data-md-color-scheme="default"] h4,
.home-div[data-md-color-scheme="default"] h5,
.home-div[data-md-color-scheme="default"] h6 {
color: var(--md-default-fg-color);
}
.home-div[data-md-color-scheme="slate"],
.home-div[data-md-color-scheme="slate"] h1,
.home-div[data-md-color-scheme="slate"] h2,
.home-div[data-md-color-scheme="slate"] h3,
.home-div[data-md-color-scheme="slate"] h4,
.home-div[data-md-color-scheme="slate"] h5,
.home-div[data-md-color-scheme="slate"] h6 {
color: var(--md-default-fg-color);
}
.home-div .intro-quote {
color: var(--md-default-fg-color--light) !important;
}
.reading-media+p {
margin-top: 1em !important;
}
.md-typeset .admonition-title:before,
.md-typeset summary:before,
.md-typeset summary:after {
top: 50%;
}
.md-typeset .admonition-title:before,
.md-typeset summary:before {
transform: translateY(-50%);
}
.md-typeset summary:after {
transform: translateY(-50%) rotate(0deg);
}
.md-typeset details[open]>summary:after {
transform: translateY(-50%) rotate(90deg);
}
.md-nav__link[for] {
color: inherit !important;
}
.md-nav__link[for].md-nav__link--active {
color: var(--md-accent-fg-color) !important;
}
@media screen and (min-width: 76.25em) {
.md-grid {
max-width: calc(61rem + 2 * (var(--hello-algo-sidebar-width) - 12.1rem));
}
.md-sidebar--primary,
.md-sidebar--secondary {
width: var(--hello-algo-sidebar-width);
}
[dir="ltr"] .md-sidebar__inner {
padding-right: calc(100% - (var(--hello-algo-sidebar-width) - 0.6rem));
}
[dir="rtl"] .md-sidebar__inner {
padding-left: calc(100% - (var(--hello-algo-sidebar-width) - 0.6rem));
}
}
.md-sidebar--primary .md-sidebar__scrollwrap {
scrollbar-color: var(--md-default-fg-color--lighter) transparent;
}
.md-sidebar--primary .md-sidebar__scrollwrap::-webkit-scrollbar-thumb,
.md-sidebar--primary .md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover {
background-color: var(--md-default-fg-color--lighter);
}
.md-footer,
.md-footer__inner,
.md-footer-meta,
.md-footer__link,
.md-footer__link:hover {
background-color: var(--md-default-bg-color);
}
.md-footer {
border-top: 0.05rem solid var(--md-default-fg-color--lightest);
}
[data-md-color-scheme="slate"] .md-footer,
[data-md-color-scheme="slate"] .md-footer__inner,
[data-md-color-scheme="slate"] .md-footer-meta,
[data-md-color-scheme="slate"] .md-footer__link,
[data-md-color-scheme="slate"] .md-footer__link:hover {
background-color: var(--md-default-bg-color);
}
.md-banner {
background-color: var(--md-default-bg-color);
}
.md-typeset .admonition.pythontutor,
.md-typeset details.pythontutor,
.md-typeset .pythontutor>.admonition-title,
.md-typeset .pythontutor>summary {
background-color: var(--md-code-bg-color);
}
.md-typeset .pythontutor>.admonition-title::before,
.md-typeset .pythontutor>summary::before,
.md-typeset .pythontutor>summary::after {
top: 50%;
}
.md-typeset .pythontutor>.admonition-title::before,
.md-typeset .pythontutor>summary::before {
transform: translateY(-50%);
}
.md-typeset .pythontutor>summary::after {
transform: translateY(-50%) rotate(0deg);
}
.md-typeset details[open].pythontutor>summary::after {
transform: translateY(-50%) rotate(90deg);
}
.md-typeset a:not(.md-button) {
text-decoration: none;
}
.md-typeset a:not(.md-button):hover,
.md-typeset a:not(.md-button):focus-visible {
text-decoration: underline;
}

View File

@@ -0,0 +1,20 @@
[project]
extra_css = [
"stylesheets/extra.css",
]
[project.theme]
features = [
"content.action.edit",
"content.code.annotate",
"content.code.copy",
"content.tabs.link",
"content.tooltips",
"navigation.indexes",
"navigation.top",
"navigation.tracking",
"search.highlight",
"search.share",
"search.suggest",
"toc.follow",
]

View File

@@ -15,8 +15,8 @@ end
### Увеличить длину массива ###
# Обратите внимание: Array в Ruby является динамическим массивом и может быть расширен напрямую
# Для удобства обучения эта функция рассматривает Array как массив неизменяемой длины
# Обратите внимание: Array в Ruby является динамическим массивом и может расширяться напрямую
# Для удобства обучения в этой функции Array рассматривается как массив неизменяемой длины
def extend(nums, enlarge)
# Инициализировать массив увеличенной длины
res = Array.new(nums.length + enlarge, 0)

View File

@@ -8,7 +8,7 @@ require_relative '../utils/list_node'
require_relative '../utils/print_util'
### Вставка узла _p после узла n0 в связном списке ###
# В Ruby `p` встроенная функция, а `P` — константа, поэтому вместо этого можно использовать `_p`
# В Ruby `p` является встроенной функцией, а `P` — константой, поэтому вместо них можно использовать `_p`
def insert(n0, _p)
n1 = n0.next
_p.next = n1

View File

@@ -40,7 +40,7 @@ def show_trunk(p)
end
### Вывести двоичное дерево ###
# Этот вывод дерева заимствован из TECHIE DELIGHT
# This tree printer is borrowed from TECHIE DELIGHT
# https://www.techiedelight.com/c-program-print-binary-tree/
def print_tree(root, prev=nil, is_right=false)
return if root.nil?

View File

@@ -3,135 +3,135 @@
В таблице ниже перечислены важные термины, встречающиеся в книге. Обратите внимание на следующие моменты.
- Рекомендуем запомнить английские названия терминов, чтобы легче читать англоязычную литературу.
- В русской версии третий столбец дублирует основной перевод, чтобы сохранить единый формат таблицы.
- В русской версии приводится единый рекомендуемый перевод каждого термина.
<p align="center"> Таблица <id> &nbsp; Важные термины по структурам данных и алгоритмам </p>
| English | Русский | Русский |
| ------------------------------ | ------------------------------ | ------------------------------ |
| algorithm | алгоритм | алгоритм |
| data structure | структура данных | структура данных |
| code | код | код |
| file | файл | файл |
| function | функция | функция |
| method | метод | метод |
| variable | переменная | переменная |
| asymptotic complexity analysis | асимптотический анализ сложности | асимптотический анализ сложности |
| time complexity | временная сложность | временная сложность |
| space complexity | пространственная сложность | пространственная сложность |
| loop | цикл | цикл |
| iteration | итерация | итерация |
| recursion | рекурсия | рекурсия |
| tail recursion | хвостовая рекурсия | хвостовая рекурсия |
| recursion tree | дерево рекурсии | дерево рекурсии |
| big-$O$ notation | нотация big-$O$ | нотация big-$O$ |
| asymptotic upper bound | асимптотическая верхняя граница | асимптотическая верхняя граница |
| sign-magnitude | прямой код | прямой код |
| 1s complement | обратный код | обратный код |
| 2s complement | дополнительный код | дополнительный код |
| array | массив | массив |
| index | индекс | индекс |
| linked list | связный список | связный список |
| linked list node, list node | узел связного списка | узел связного списка |
| head node | головной узел | головной узел |
| tail node | хвостовой узел | хвостовой узел |
| list | список | список |
| dynamic array | динамический массив | динамический массив |
| hard disk | жесткий диск | жесткий диск |
| random-access memory (RAM) | оперативная память | оперативная память |
| cache memory | кеш-память | кеш-память |
| cache miss | промах кеша | промах кеша |
| cache hit rate | коэффициент попадания в кеш | коэффициент попадания в кеш |
| stack | стек | стек |
| top of the stack | вершина стека | вершина стека |
| bottom of the stack | основание стека | основание стека |
| queue | очередь | очередь |
| double-ended queue | двусторонняя очередь | двусторонняя очередь |
| front of the queue | голова очереди | голова очереди |
| rear of the queue | хвост очереди | хвост очереди |
| hash table | хеш-таблица | хеш-таблица |
| hash set | хеш-набор | хеш-набор |
| bucket | корзина | корзина |
| hash function | хеш-функция | хеш-функция |
| hash collision | хеш-коллизия | хеш-коллизия |
| load factor | коэффициент заполнения | коэффициент заполнения |
| separate chaining | цепная адресация | цепная адресация |
| open addressing | открытая адресация | открытая адресация |
| linear probing | линейное зондирование | линейное зондирование |
| lazy deletion | ленивое удаление | ленивое удаление |
| binary tree | двоичное дерево | двоичное дерево |
| tree node | узел дерева | узел дерева |
| left-child node | левый дочерний узел | левый дочерний узел |
| right-child node | правый дочерний узел | правый дочерний узел |
| parent node | родительский узел | родительский узел |
| left subtree | левое поддерево | левое поддерево |
| right subtree | правое поддерево | правое поддерево |
| root node | корневой узел | корневой узел |
| leaf node | листовой узел | листовой узел |
| edge | ребро | ребро |
| level | уровень | уровень |
| degree | степень | степень |
| height | высота | высота |
| depth | глубина | глубина |
| perfect binary tree | идеальное двоичное дерево | идеальное двоичное дерево |
| complete binary tree | совершенное двоичное дерево | совершенное двоичное дерево |
| full binary tree | полное двоичное дерево | полное двоичное дерево |
| balanced binary tree | сбалансированное двоичное дерево | сбалансированное двоичное дерево |
| binary search tree | двоичное дерево поиска | двоичное дерево поиска |
| AVL tree | АВЛ-дерево | АВЛ-дерево |
| red-black tree | красно-черное дерево | красно-черное дерево |
| level-order traversal | обход по уровням | обход по уровням |
| breadth-first traversal | обход в ширину | обход в ширину |
| depth-first traversal | обход в глубину | обход в глубину |
| binary search tree | двоичное дерево поиска | двоичное дерево поиска |
| balanced binary search tree | сбалансированное двоичное дерево поиска | сбалансированное двоичное дерево поиска |
| balance factor | фактор баланса | фактор баланса |
| heap | куча | куча |
| max heap | максимальная куча | максимальная куча |
| min heap | минимальная куча | минимальная куча |
| priority queue | приоритетная очередь | приоритетная очередь |
| heapify | упорядочивание кучи | упорядочивание кучи |
| top-$k$ problem | поиск $k$ наибольших элементов | поиск $k$ наибольших элементов |
| graph | граф | граф |
| vertex | вершина | вершина |
| undirected graph | неориентированный граф | неориентированный граф |
| directed graph | ориентированный граф | ориентированный граф |
| connected graph | связный граф | связный граф |
| disconnected graph | несвязный граф | несвязный граф |
| weighted graph | взвешенный граф | взвешенный граф |
| adjacency | смежность | смежность |
| path | путь | путь |
| in-degree | входящая степень | входящая степень |
| out-degree | исходящая степень | исходящая степень |
| adjacency matrix | матрица смежности | матрица смежности |
| adjacency list | список смежности | список смежности |
| breadth-first search | поиск в ширину | поиск в ширину |
| depth-first search | поиск в глубину | поиск в глубину |
| binary search | двоичный поиск | двоичный поиск |
| searching algorithm | алгоритм поиска | алгоритм поиска |
| sorting algorithm | алгоритм сортировки | алгоритм сортировки |
| selection sort | сортировка выбором | сортировка выбором |
| bubble sort | сортировка пузырьком | сортировка пузырьком |
| insertion sort | сортировка вставкой | сортировка вставкой |
| quick sort | быстрая сортировка | быстрая сортировка |
| merge sort | сортировка слиянием | сортировка слиянием |
| heap sort | пирамидальная сортировка | пирамидальная сортировка |
| bucket sort | блочная сортировка | блочная сортировка |
| counting sort | сортировка подсчетом | сортировка подсчетом |
| radix sort | поразрядная сортировка | поразрядная сортировка |
| divide and conquer | разделяй и властвуй | разделяй и властвуй |
| hanota problem | задача о Ханойской башне | задача о Ханойской башне |
| backtracking algorithm | алгоритм поиска с возвратом | алгоритм поиска с возвратом |
| constraint | ограничение | ограничение |
| solution | решение | решение |
| state | состояние | состояние |
| pruning | отсечение | отсечение |
| permutations problem | задача о перестановках | задача о перестановках |
| subset-sum problem | задача о сумме подмножеств | задача о сумме подмножеств |
| $n$-queens problem | задача о $n$ ферзях | задача о $n$ ферзях |
| dynamic programming | динамическое программирование | динамическое программирование |
| initial state | начальное состояние | начальное состояние |
| state-transition equation | уравнение перехода состояния | уравнение перехода состояния |
| knapsack problem | задача о рюкзаке | задача о рюкзаке |
| edit distance problem | задача о расстоянии редактирования | задача о расстоянии редактирования |
| greedy algorithm | жадный алгоритм | жадный алгоритм |
| English | Русский |
| ------------------------------ | ------------------------------ |
| algorithm | алгоритм |
| data structure | структура данных |
| code | код |
| file | файл |
| function | функция |
| method | метод |
| variable | переменная |
| asymptotic complexity analysis | асимптотический анализ сложности |
| time complexity | временная сложность |
| space complexity | пространственная сложность |
| loop | цикл |
| iteration | итерация |
| recursion | рекурсия |
| tail recursion | хвостовая рекурсия |
| recursion tree | дерево рекурсии |
| big-$O$ notation | нотация big-$O$ |
| asymptotic upper bound | асимптотическая верхняя граница |
| sign-magnitude | прямой код |
| 1s complement | обратный код |
| 2s complement | дополнительный код |
| array | массив |
| index | индекс |
| linked list | связный список |
| linked list node, list node | узел связного списка |
| head node | головной узел |
| tail node | хвостовой узел |
| list | список |
| dynamic array | динамический массив |
| hard disk | жесткий диск |
| random-access memory (RAM) | оперативная память |
| cache memory | кеш-память |
| cache miss | промах кеша |
| cache hit rate | коэффициент попадания в кеш |
| stack | стек |
| top of the stack | вершина стека |
| bottom of the stack | основание стека |
| queue | очередь |
| double-ended queue | двусторонняя очередь |
| front of the queue | голова очереди |
| rear of the queue | хвост очереди |
| hash table | хеш-таблица |
| hash set | хеш-набор |
| bucket | корзина |
| hash function | хеш-функция |
| hash collision | хеш-коллизия |
| load factor | коэффициент заполнения |
| separate chaining | цепная адресация |
| open addressing | открытая адресация |
| linear probing | линейное зондирование |
| lazy deletion | ленивое удаление |
| binary tree | двоичное дерево |
| tree node | узел дерева |
| left-child node | левый дочерний узел |
| right-child node | правый дочерний узел |
| parent node | родительский узел |
| left subtree | левое поддерево |
| right subtree | правое поддерево |
| root node | корневой узел |
| leaf node | листовой узел |
| edge | ребро |
| level | уровень |
| degree | степень |
| height | высота |
| depth | глубина |
| perfect binary tree | идеальное двоичное дерево |
| complete binary tree | совершенное двоичное дерево |
| full binary tree | полное двоичное дерево |
| balanced binary tree | сбалансированное двоичное дерево |
| binary search tree | двоичное дерево поиска |
| AVL tree | АВЛ-дерево |
| red-black tree | красно-черное дерево |
| level-order traversal | обход по уровням |
| breadth-first traversal | обход в ширину |
| depth-first traversal | обход в глубину |
| binary search tree | двоичное дерево поиска |
| balanced binary search tree | сбалансированное двоичное дерево поиска |
| balance factor | фактор баланса |
| heap | куча |
| max heap | максимальная куча |
| min heap | минимальная куча |
| priority queue | приоритетная очередь |
| heapify | упорядочивание кучи |
| top-$k$ problem | поиск $k$ наибольших элементов |
| graph | граф |
| vertex | вершина |
| undirected graph | неориентированный граф |
| directed graph | ориентированный граф |
| connected graph | связный граф |
| disconnected graph | несвязный граф |
| weighted graph | взвешенный граф |
| adjacency | смежность |
| path | путь |
| in-degree | входящая степень |
| out-degree | исходящая степень |
| adjacency matrix | матрица смежности |
| adjacency list | список смежности |
| breadth-first search | поиск в ширину |
| depth-first search | поиск в глубину |
| binary search | двоичный поиск |
| searching algorithm | алгоритм поиска |
| sorting algorithm | алгоритм сортировки |
| selection sort | сортировка выбором |
| bubble sort | сортировка пузырьком |
| insertion sort | сортировка вставкой |
| quick sort | быстрая сортировка |
| merge sort | сортировка слиянием |
| heap sort | пирамидальная сортировка |
| bucket sort | блочная сортировка |
| counting sort | сортировка подсчетом |
| radix sort | поразрядная сортировка |
| divide and conquer | разделяй и властвуй |
| hanota problem | задача о Ханойской башне |
| backtracking algorithm | алгоритм поиска с возвратом |
| constraint | ограничение |
| solution | решение |
| state | состояние |
| pruning | отсечение |
| permutations problem | задача о перестановках |
| subset-sum problem | задача о сумме подмножеств |
| $n$-queens problem | задача о $n$ ферзях |
| dynamic programming | динамическое программирование |
| initial state | начальное состояние |
| state-transition equation | уравнение перехода состояния |
| knapsack problem | задача о рюкзаке |
| edit distance problem | задача о расстоянии редактирования |
| greedy algorithm | жадный алгоритм |