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,107 @@
/**
* File: array.swift
* Created Time: 2023-01-05
* Author: nuomi1 (nuomi1@qq.com)
*/
/* Случайный доступ к элементу */
func randomAccess(nums: [Int]) -> Int {
// Случайным образом выбрать число из интервала [0, nums.count)
let randomIndex = nums.indices.randomElement()!
// Получить и вернуть случайный элемент
let randomNum = nums[randomIndex]
return randomNum
}
/* Увеличить длину массива */
func extend(nums: [Int], enlarge: Int) -> [Int] {
// Инициализировать массив увеличенной длины
var res = Array(repeating: 0, count: nums.count + enlarge)
// Скопировать все элементы исходного массива в новый массив
for i in nums.indices {
res[i] = nums[i]
}
// Вернуть новый массив после расширения
return res
}
/* Вставить элемент num по индексу index в массив */
func insert(nums: inout [Int], num: Int, index: Int) {
// Сдвинуть элемент с индексом index и все последующие элементы на одну позицию назад
for i in nums.indices.dropFirst(index).reversed() {
nums[i] = nums[i - 1]
}
// Присвоить num элементу по индексу index
nums[index] = num
}
/* Удалить элемент по индексу index */
func remove(nums: inout [Int], index: Int) {
// Сдвинуть все элементы после индекса index на одну позицию вперед
for i in nums.indices.dropFirst(index).dropLast() {
nums[i] = nums[i + 1]
}
}
/* Обход массива */
func traverse(nums: [Int]) {
var count = 0
// Обход массива по индексам
for i in nums.indices {
count += nums[i]
}
// Непосредственно обходить элементы массива
for num in nums {
count += num
}
// Одновременно обходить индексы и элементы данных
for (i, num) in nums.enumerated() {
count += nums[i]
count += num
}
}
/* Найти заданный элемент в массиве */
func find(nums: [Int], target: Int) -> Int {
for i in nums.indices {
if nums[i] == target {
return i
}
}
return -1
}
@main
enum _Array {
/* Driver Code */
static func main() {
/* Инициализация массива */
let arr = Array(repeating: 0, count: 5)
print("Массив arr = \(arr)")
var nums = [1, 3, 2, 5, 4]
print("Массив nums = \(nums)")
/* Случайный доступ */
let randomNum = randomAccess(nums: nums)
print("Случайный элемент из nums = \(randomNum)")
/* Расширение длины */
nums = extend(nums: nums, enlarge: 3)
print("После увеличения длины массива до 8 nums = \(nums)")
/* Вставка элемента */
insert(nums: &nums, num: 6, index: 3)
print("После вставки числа 6 по индексу 3 nums = \(nums)")
/* Удаление элемента */
remove(nums: &nums, index: 2)
print("После удаления элемента по индексу 2 nums = \(nums)")
/* Обход массива */
traverse(nums: nums)
/* Поиск элемента */
let index = find(nums: nums, target: 3)
print("Поиск элемента 3 в nums: индекс = \(index)")
}
}
@@ -0,0 +1,90 @@
/**
* File: linked_list.swift
* Created Time: 2023-01-08
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* Вставить узел P после узла n0 в связном списке */
func insert(n0: ListNode, P: ListNode) {
let n1 = n0.next
P.next = n1
n0.next = P
}
/* Удалить первый узел после узла n0 в связном списке */
func remove(n0: ListNode) {
if n0.next == nil {
return
}
// n0 -> P -> n1
let P = n0.next
let n1 = P?.next
n0.next = n1
}
/* Доступ к узлу связного списка по индексу index */
func access(head: ListNode, index: Int) -> ListNode? {
var head: ListNode? = head
for _ in 0 ..< index {
if head == nil {
return nil
}
head = head?.next
}
return head
}
/* Найти в связном списке первый узел со значением target */
func find(head: ListNode, target: Int) -> Int {
var head: ListNode? = head
var index = 0
while head != nil {
if head?.val == target {
return index
}
head = head?.next
index += 1
}
return -1
}
@main
enum LinkedList {
/* Driver Code */
static func main() {
/* Инициализация связного списка */
// Инициализация всех узлов
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
// Построить ссылки между узлами
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
print("Исходный связный список")
PrintUtil.printLinkedList(head: n0)
/* Вставка узла */
insert(n0: n0, P: ListNode(x: 0))
print("Связный список после вставки узла")
PrintUtil.printLinkedList(head: n0)
/* Удаление узла */
remove(n0: n0)
print("Связный список после удаления узла")
PrintUtil.printLinkedList(head: n0)
/* Доступ к узлу */
let node = access(head: n0, index: 3)
print("Значение узла по индексу 3 в связном списке = \(node!.val)")
/* Поиск узла */
let index = find(head: n0, target: 2)
print("Индекс узла со значением 2 в связном списке = \(index)")
}
}
@@ -0,0 +1,63 @@
/**
* File: list.swift
* Created Time: 2023-01-08
* Author: nuomi1 (nuomi1@qq.com)
*/
@main
enum List {
/* Driver Code */
static func main() {
/* Инициализация списка */
var nums = [1, 3, 2, 5, 4]
print("Список nums = \(nums)")
/* Доступ к элементу */
let num = nums[1]
print("Элемент по индексу 1: num = \(num)")
/* Обновление элемента */
nums[1] = 0
print("После обновления элемента по индексу 1 до 0 nums = \(nums)")
/* Очистить список */
nums.removeAll()
print("После очистки списка nums = \(nums)")
/* Добавление элемента в конец */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
print("После добавления элементов nums = \(nums)")
/* Вставка элемента в середину */
nums.insert(6, at: 3)
print("После вставки числа 6 по индексу 3 nums = \(nums)")
/* Удаление элемента */
nums.remove(at: 3)
print("После удаления элемента по индексу 3 nums = \(nums)")
/* Обходить список по индексам */
var count = 0
for i in nums.indices {
count += nums[i]
}
/* Непосредственно обходить элементы списка */
count = 0
for x in nums {
count += x
}
/* Объединить два списка */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1)
print("После конкатенации списка nums1 к nums nums = \(nums)")
/* Отсортировать список */
nums.sort()
print("После сортировки списка nums = \(nums)")
}
}
@@ -0,0 +1,146 @@
/**
* File: my_list.swift
* Created Time: 2023-01-08
* Author: nuomi1 (nuomi1@qq.com)
*/
/* Класс списка */
class MyList {
private var arr: [Int] // Массив (для хранения элементов списка)
private var _capacity: Int // Вместимость списка
private var _size: Int // Длина списка (текущее число элементов)
private let extendRatio: Int // Коэффициент увеличения списка при каждом расширении
/* Конструктор */
init() {
_capacity = 10
_size = 0
extendRatio = 2
arr = Array(repeating: 0, count: _capacity)
}
/* Получить длину списка (текущее число элементов) */
func size() -> Int {
_size
}
/* Получить вместимость списка */
func capacity() -> Int {
_capacity
}
/* Доступ к элементу */
func get(index: Int) -> Int {
// Если индекс выходит за границы, выбросить ошибку; далее аналогично
if index < 0 || index >= size() {
fatalError("индекс выходит за границы")
}
return arr[index]
}
/* Обновление элемента */
func set(index: Int, num: Int) {
if index < 0 || index >= size() {
fatalError("индекс выходит за границы")
}
arr[index] = num
}
/* Добавление элемента в конец */
func add(num: Int) {
// При превышении вместимости по числу элементов запускается расширение
if size() == capacity() {
extendCapacity()
}
arr[size()] = num
// Обновить число элементов
_size += 1
}
/* Вставка элемента в середину */
func insert(index: Int, num: Int) {
if index < 0 || index >= size() {
fatalError("индекс выходит за границы")
}
// При превышении вместимости по числу элементов запускается расширение
if size() == capacity() {
extendCapacity()
}
// Сдвинуть элемент с индексом index и все следующие элементы на одну позицию назад
for j in (index ..< size()).reversed() {
arr[j + 1] = arr[j]
}
arr[index] = num
// Обновить число элементов
_size += 1
}
/* Удаление элемента */
@discardableResult
func remove(index: Int) -> Int {
if index < 0 || index >= size() {
fatalError("индекс выходит за границы")
}
let num = arr[index]
// Сдвинуть все элементы после индекса index на одну позицию вперед
for j in index ..< (size() - 1) {
arr[j] = arr[j + 1]
}
// Обновить число элементов
_size -= 1
// Вернуть удаленный элемент
return num
}
/* Расширение списка */
func extendCapacity() {
// Создать новый массив длиной в extendRatio раз больше исходного и скопировать в него исходный массив
arr = arr + Array(repeating: 0, count: capacity() * (extendRatio - 1))
// Обновить вместимость списка
_capacity = arr.count
}
/* Преобразовать список в массив */
func toArray() -> [Int] {
Array(arr.prefix(size()))
}
}
@main
enum _MyList {
/* Driver Code */
static func main() {
/* Инициализация списка */
let nums = MyList()
/* Добавление элемента в конец */
nums.add(num: 1)
nums.add(num: 3)
nums.add(num: 2)
nums.add(num: 5)
nums.add(num: 4)
print("Список nums = \(nums.toArray()) , вместимость = \(nums.capacity()) , длина = \(nums.size())")
/* Вставка элемента в середину */
nums.insert(index: 3, num: 6)
print("После вставки числа 6 по индексу 3 nums = \(nums.toArray())")
/* Удаление элемента */
nums.remove(index: 3)
print("После удаления элемента по индексу 3 nums = \(nums.toArray())")
/* Доступ к элементу */
let num = nums.get(index: 1)
print("Элемент по индексу 1: num = \(num)")
/* Обновление элемента */
nums.set(index: 1, num: 0)
print("После обновления элемента по индексу 1 до 0 nums = \(nums.toArray())")
/* Проверка механизма расширения */
for i in 0 ..< 10 {
// При i = 5 длина списка превысит его вместимость, и в этот момент сработает механизм расширения
nums.add(num: i)
}
print("Список nums после увеличения вместимости = \(nums.toArray()) , вместимость = \(nums.capacity()) , длина = \(nums.size())")
}
}