Add ru version (#1865)

* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
This commit is contained in:
Yudong Jin
2026-03-28 04:24:07 +08:00
committed by GitHub
parent 2ca570cc33
commit 772183705e
1958 changed files with 108186 additions and 0 deletions
@@ -0,0 +1,91 @@
// File: iteration.zig
// Created Time: 2023-09-27
// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const Allocator = std.mem.Allocator;
// Цикл for
fn forLoop(n: usize) i32 {
var res: i32 = 0;
// Циклическое суммирование 1, 2, ..., n-1, n
for (1..n + 1) |i| {
res += @intCast(i);
}
return res;
}
// Цикл while
fn whileLoop(n: i32) i32 {
var res: i32 = 0;
var i: i32 = 1; // Инициализация условной переменной
// Циклическое суммирование 1, 2, ..., n-1, n
while (i <= n) : (i += 1) {
res += @intCast(i);
}
return res;
}
// Цикл while (двойное обновление)
fn whileLoopII(n: i32) i32 {
var res: i32 = 0;
var i: i32 = 1; // Инициализация условной переменной
// Циклическое суммирование 1, 4, 10, ...
while (i <= n) : ({
// Обновить условную переменную
i += 1;
i *= 2;
}) {
res += @intCast(i);
}
return res;
}
// Двойной цикл for
fn nestedForLoop(allocator: Allocator, n: usize) ![]const u8 {
var res = std.ArrayList(u8).init(allocator);
defer res.deinit();
var buffer: [20]u8 = undefined;
// Цикл по i = 1, 2, ..., n-1, n
for (1..n + 1) |i| {
// Цикл по j = 1, 2, ..., n-1, n
for (1..n + 1) |j| {
const str = try std.fmt.bufPrint(&buffer, "({d}, {d}), ", .{ i, j });
try res.appendSlice(str);
}
}
return res.toOwnedSlice();
}
// Driver Code
pub fn run() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const n: i32 = 5;
var res: i32 = 0;
res = forLoop(n);
std.debug.print("Результат суммирования в цикле for res = {}\n", .{res});
res = whileLoop(n);
std.debug.print("Результат суммирования в цикле while res = {}\n", .{res});
res = whileLoopII(n);
std.debug.print("Результат суммирования в цикле while (двойное обновление) res = {}\n", .{res});
const resStr = try nestedForLoop(allocator, n);
std.debug.print("Результат обхода в двойном цикле for {s}\n", .{resStr});
allocator.free(resStr);
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "interation" {
try run();
}
@@ -0,0 +1,88 @@
// File: recursion.zig
// Created Time: 2023-09-27
// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
// Рекурсивная функция
fn recur(n: i32) i32 {
// Условие завершения
if (n == 1) {
return 1;
}
// Рекурсия: рекурсивный вызов
const res = recur(n - 1);
// Возврат: вернуть результат
return n + res;
}
// Имитация рекурсии итерацией
fn forLoopRecur(comptime n: i32) i32 {
// Использовать явный стек для имитации системного стека вызовов
var stack: [n]i32 = undefined;
var res: i32 = 0;
// Рекурсия: рекурсивный вызов
var i: usize = n;
while (i > 0) {
stack[i - 1] = @intCast(i);
i -= 1;
}
// Возврат: вернуть результат
var index: usize = n;
while (index > 0) {
index -= 1;
res += stack[index];
}
// res = 1+2+3+...+n
return res;
}
// Хвосторекурсивная функция
fn tailRecur(n: i32, res: i32) i32 {
// Условие завершения
if (n == 0) {
return res;
}
// Хвостовой рекурсивный вызов
return tailRecur(n - 1, res + n);
}
// Числа Фибоначчи
fn fib(n: i32) i32 {
// Условие завершения: f(1) = 0, f(2) = 1
if (n == 1 or n == 2) {
return n - 1;
}
// Рекурсивный вызов f(n) = f(n-1) + f(n-2)
const res: i32 = fib(n - 1) + fib(n - 2);
// Вернуть результат f(n)
return res;
}
// Driver Code
pub fn run() void {
const n: i32 = 5;
var res: i32 = 0;
res = recur(n);
std.debug.print("Результат суммирования в рекурсивной функции res = {}\n", .{recur(n)});
res = forLoopRecur(n);
std.debug.print("Результат суммирования при имитации рекурсии итерацией res = {}\n", .{forLoopRecur(n)});
res = tailRecur(n, 0);
std.debug.print("Результат суммирования в хвостовой рекурсии res = {}\n", .{tailRecur(n, 0)});
res = fib(n);
std.debug.print("Член последовательности Фибоначчи с номером {} = {}\n", .{ n, fib(n) });
std.debug.print("\n", .{});
}
pub fn main() void {
run();
}
test "recursion" {
run();
}
@@ -0,0 +1,142 @@
// File: space_complexity.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const utils = @import("utils");
const ListNode = utils.ListNode;
const TreeNode = utils.TreeNode;
// Функция
fn function() i32 {
// Выполнить некоторые операции
return 0;
}
// Постоянная сложность
fn constant(n: i32) void {
// Константы, переменные и объекты занимают O(1) памяти
const a: i32 = 0;
const b: i32 = 0;
const nums = [_]i32{0} ** 10000;
const node = ListNode(i32){ .val = 0 };
var i: i32 = 0;
// Переменные в цикле занимают O(1) памяти
while (i < n) : (i += 1) {
const c: i32 = 0;
_ = c;
}
// Функции в цикле занимают O(1) памяти
i = 0;
while (i < n) : (i += 1) {
_ = function();
}
_ = a;
_ = b;
_ = nums;
_ = node;
}
// Линейная сложность
fn linear(comptime n: i32) !void {
// Массив длины n занимает O(n) памяти
const nums = [_]i32{0} ** n;
// Список длины n занимает O(n) памяти
var nodes = std.ArrayList(i32).init(std.heap.page_allocator);
defer nodes.deinit();
var i: i32 = 0;
while (i < n) : (i += 1) {
try nodes.append(i);
}
// Хеш-таблица длины n занимает O(n) памяти
var map = std.AutoArrayHashMap(i32, []const u8).init(std.heap.page_allocator);
defer map.deinit();
var j: i32 = 0;
while (j < n) : (j += 1) {
const string = try std.fmt.allocPrint(std.heap.page_allocator, "{d}", .{j});
defer std.heap.page_allocator.free(string);
try map.put(i, string);
}
_ = nums;
}
// Линейная сложность (рекурсивная реализация)
fn linearRecur(comptime n: i32) void {
std.debug.print("Рекурсия n = {}\n", .{n});
if (n == 1) return;
linearRecur(n - 1);
}
// Квадратичная сложность
fn quadratic(n: i32) !void {
// Двумерный список занимает O(n^2) памяти
var nodes = std.ArrayList(std.ArrayList(i32)).init(std.heap.page_allocator);
defer nodes.deinit();
var i: i32 = 0;
while (i < n) : (i += 1) {
var tmp = std.ArrayList(i32).init(std.heap.page_allocator);
defer tmp.deinit();
var j: i32 = 0;
while (j < n) : (j += 1) {
try tmp.append(0);
}
try nodes.append(tmp);
}
}
// Квадратичная сложность (рекурсивная реализация)
fn quadraticRecur(comptime n: i32) i32 {
if (n <= 0) return 0;
const nums = [_]i32{0} ** n;
std.debug.print("В рекурсии n = {} длина nums = {}\n", .{ n, nums.len });
return quadraticRecur(n - 1);
}
// Экспоненциальная сложность (построение полного двоичного дерева)
fn buildTree(allocator: std.mem.Allocator, n: i32) !?*TreeNode(i32) {
if (n == 0) return null;
const root = try allocator.create(TreeNode(i32));
root.init(0);
root.left = try buildTree(allocator, n - 1);
root.right = try buildTree(allocator, n - 1);
return root;
}
// Освободить память дерева
fn freeTree(allocator: std.mem.Allocator, root: ?*const TreeNode(i32)) void {
if (root == null) return;
freeTree(allocator, root.?.left);
freeTree(allocator, root.?.right);
allocator.destroy(root.?);
}
// Driver Code
pub fn run() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const n: i32 = 5;
// Постоянная сложность
constant(n);
// Линейная сложность
try linear(n);
linearRecur(n);
// Квадратичная сложность
try quadratic(n);
_ = quadraticRecur(n);
// Экспоненциальная сложность
const root = try buildTree(allocator, n);
defer freeTree(allocator, root);
std.debug.print("{}\n", .{utils.fmt.tree(i32, root)});
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "space_complexity" {
try run();
}
@@ -0,0 +1,184 @@
// File: time_complexity.zig
// Created Time: 2022-12-28
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
// Постоянная сложность
fn constant(n: i32) i32 {
_ = n;
var count: i32 = 0;
const size: i32 = 100_000;
var i: i32 = 0;
while (i < size) : (i += 1) {
count += 1;
}
return count;
}
// Линейная сложность
fn linear(n: i32) i32 {
var count: i32 = 0;
var i: i32 = 0;
while (i < n) : (i += 1) {
count += 1;
}
return count;
}
// Линейная сложность (обход массива)
fn arrayTraversal(nums: []i32) i32 {
var count: i32 = 0;
// Число итераций пропорционально длине массива
for (nums) |_| {
count += 1;
}
return count;
}
// Квадратичная сложность
fn quadratic(n: i32) i32 {
var count: i32 = 0;
var i: i32 = 0;
// Число итераций квадратично зависит от размера данных n
while (i < n) : (i += 1) {
var j: i32 = 0;
while (j < n) : (j += 1) {
count += 1;
}
}
return count;
}
// Квадратичная сложность (пузырьковая сортировка)
fn bubbleSort(nums: []i32) i32 {
var count: i32 = 0; // Счетчик
// Внешний цикл: неотсортированный диапазон [0, i]
var i: i32 = @as(i32, @intCast(nums.len)) - 1;
while (i > 0) : (i -= 1) {
var j: usize = 0;
// Внутренний цикл: переместить максимальный элемент неотсортированного диапазона [0, i] в его правый конец
while (j < i) : (j += 1) {
if (nums[j] > nums[j + 1]) {
// Поменять местами nums[j] и nums[j + 1]
const tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Обмен элементов включает 3 элементарные операции
}
}
}
return count;
}
// Экспоненциальная сложность (итеративная реализация)
fn exponential(n: i32) i32 {
var count: i32 = 0;
var bas: i32 = 1;
var i: i32 = 0;
// На каждом шаге клетка делится надвое, образуя последовательность 1, 2, 4, 8, ..., 2^(n-1)
while (i < n) : (i += 1) {
var j: i32 = 0;
while (j < bas) : (j += 1) {
count += 1;
}
bas *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
// Экспоненциальная сложность (рекурсивная реализация)
fn expRecur(n: i32) i32 {
if (n == 1) return 1;
return expRecur(n - 1) + expRecur(n - 1) + 1;
}
// Логарифмическая сложность (итеративная реализация)
fn logarithmic(n: i32) i32 {
var count: i32 = 0;
var n_var: i32 = n;
while (n_var > 1) : (n_var = @divTrunc(n_var, 2)) {
count += 1;
}
return count;
}
// Логарифмическая сложность (рекурсивная реализация)
fn logRecur(n: i32) i32 {
if (n <= 1) return 0;
return logRecur(@divTrunc(n, 2)) + 1;
}
// Линейно-логарифмическая сложность
fn linearLogRecur(n: i32) i32 {
if (n <= 1) return 1;
var count: i32 = linearLogRecur(@divTrunc(n, 2)) + linearLogRecur(@divTrunc(n, 2));
var i: i32 = 0;
while (i < n) : (i += 1) {
count += 1;
}
return count;
}
// Факториальная сложность (рекурсивная реализация)
fn factorialRecur(n: i32) i32 {
if (n == 0) return 1;
var count: i32 = 0;
var i: i32 = 0;
// Из одного получается n
while (i < n) : (i += 1) {
count += factorialRecur(n - 1);
}
return count;
}
// Driver Code
pub fn run() void {
// Можно изменить n и запустить программу, чтобы увидеть, как меняется число операций при разных сложностях
const n: i32 = 8;
std.debug.print("Размер входных данных n = {}\n", .{n});
var count = constant(n);
std.debug.print("Число операций постоянной сложности = {}\n", .{count});
count = linear(n);
std.debug.print("Число операций линейной сложности = {}\n", .{count});
var nums = [_]i32{0} ** n;
count = arrayTraversal(&nums);
std.debug.print("Число операций линейной сложности (обход массива) = {}\n", .{count});
count = quadratic(n);
std.debug.print("Число операций квадратичной сложности = {}\n", .{count});
for (&nums, 0..) |*num, i| {
num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
}
count = bubbleSort(&nums);
std.debug.print("Число операций квадратичной сложности (пузырьковая сортировка) = {}\n", .{count});
count = exponential(n);
std.debug.print("Число операций экспоненциальной сложности (итеративная реализация) = {}\n", .{count});
count = expRecur(n);
std.debug.print("Число операций экспоненциальной сложности (рекурсивная реализация) = {}\n", .{count});
count = logarithmic(n);
std.debug.print("Число операций логарифмической сложности (итеративная реализация) = {}\n", .{count});
count = logRecur(n);
std.debug.print("Число операций логарифмической сложности (рекурсивная реализация) = {}\n", .{count});
count = linearLogRecur(n);
std.debug.print("Число операций линейно-логарифмической сложности (рекурсивная реализация) = {}\n", .{count});
count = factorialRecur(n);
std.debug.print("Число операций факториальной сложности (рекурсивная реализация) = {}\n", .{count});
std.debug.print("\n", .{});
}
pub fn main() !void {
run();
}
test "time_complexity" {
run();
}
@@ -0,0 +1,53 @@
// File: worst_best_time_complexity.zig
// Created Time: 2022-12-28
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const utils = @import("utils");
// Создать массив с элементами { 1, 2, ..., n } в случайном порядке
pub fn randomNumbers(comptime n: usize) [n]i32 {
var nums: [n]i32 = undefined;
// Создать массив nums = { 1, 2, 3, ..., n }
for (&nums, 0..) |*num, i| {
num.* = @as(i32, @intCast(i)) + 1;
}
// Случайно перемешать элементы массива
const rand = std.crypto.random;
rand.shuffle(i32, &nums);
return nums;
}
// Найти индекс числа 1 в массиве nums
pub fn findOne(nums: []i32) i32 {
for (nums, 0..) |num, i| {
// Когда элемент 1 находится в начале массива, достигается лучшая временная сложность O(1)
// Когда элемент 1 находится в конце массива, достигается худшая временная сложность O(n)
if (num == 1) return @intCast(i);
}
return -1;
}
// Driver Code
pub fn run() void {
var i: i32 = 0;
while (i < 10) : (i += 1) {
const n: usize = 100;
var nums = randomNumbers(n);
const index = findOne(&nums);
std.debug.print("После перемешивания массива [ 1, 2, ..., n ] = ", .{});
std.debug.print("{}\n", .{utils.fmt.slice(nums)});
std.debug.print("Индекс числа 1 = {}\n", .{index});
}
std.debug.print("\n", .{});
}
pub fn main() !void {
run();
}
test "worst_best_time_complexity" {
run();
}