This commit is contained in:
krahets
2024-03-31 03:53:04 +08:00
parent 87af663929
commit c23e576da4
68 changed files with 2139 additions and 22 deletions

View File

@@ -293,6 +293,19 @@ Accessing elements in an array is highly efficient, allowing us to randomly acce
}
```
=== "Ruby"
```ruby title="array.rb"
### 随机访问元素 ###
def random_access(nums)
# 在区间 [0, nums.length) 中随机抽取一个数字
random_index = Random.rand 0...(nums.length - 1)
# 获取并返回随机元素
nums[random_index]
end
```
=== "Zig"
```zig title="array.zig"
@@ -487,6 +500,21 @@ It's important to note that due to the fixed length of an array, inserting an el
}
```
=== "Ruby"
```ruby title="array.rb"
### 在数组的索引 index 处插入元素 num ###
def insert(nums, num, index)
# 把索引 index 以及之后的所有元素向后移动一位
for i in (nums.length - 1).downto(index + 1)
nums[i] = nums[i - 1]
end
# 将 num 赋给 index 处的元素
nums[index] = num
end
```
=== "Zig"
```zig title="array.zig"
@@ -660,6 +688,18 @@ Please note that after deletion, the former last element becomes "meaningless,"
}
```
=== "Ruby"
```ruby title="array.rb"
### 删除索引 index 处的元素 ###
def remove(nums, index)
# 把索引 index 之后的所有元素向前移动一位
for i in index...nums.length
nums[i] = nums[i + 1] || 0
end
end
```
=== "Zig"
```zig title="array.zig"
@@ -900,6 +940,25 @@ In most programming languages, we can traverse an array either by using indices
}
```
=== "Ruby"
```ruby title="array.rb"
### 遍历数组 ###
def traverse(nums)
count = 0
# 通过索引遍历数组
for i in 0...nums.length
count += nums[i]
end
# 直接遍历数组元素
for num in nums
count += num
end
end
```
=== "Zig"
```zig title="array.zig"
@@ -1087,6 +1146,19 @@ Because arrays are linear data structures, this operation is commonly referred t
}
```
=== "Ruby"
```ruby title="array.rb"
### 在数组中查找指定元素 ###
def find(nums, target)
for i in 0...nums.length
return i if nums[i] == target
end
-1
end
```
=== "Zig"
```zig title="array.zig"
@@ -1310,6 +1382,26 @@ To expand an array, it's necessary to create a larger array and then copy the e
}
```
=== "Ruby"
```ruby title="array.rb"
### 扩展数组长度 ###
# 请注意Ruby 的 Array 是动态数组,可以直接扩展
# 为了方便学习,本函数将 Array 看作长度不可变的数组
def extend(nums, enlarge)
# 初始化一个扩展长度后的数组
res = Array.new(nums.length + enlarge, 0)
# 将原数组中的所有元素复制到新数组
for i in 0...nums.length
res[i] = nums[i]
end
# 返回扩展后的新数组
res
end
```
=== "Zig"
```zig title="array.zig"

View File

@@ -552,6 +552,18 @@ By comparison, inserting an element into an array has a time complexity of $O(n)
}
```
=== "Ruby"
```ruby title="linked_list.rb"
### 在链表的节点 n0 之后插入节点 _p ###
# Ruby 的 `p` 是一个内置函数, `P` 是一个常量,所以可以使用 `_p` 代替
def insert(n0, _p)
n1 = n0.next
_p.next = n1
n0.next = _p
end
```
=== "Zig"
```zig title="linked_list.zig"
@@ -752,6 +764,20 @@ It's important to note that even though node `P` continues to point to `n1` afte
}
```
=== "Ruby"
```ruby title="linked_list.rb"
### 删除链表的节点 n0 之后的首个节点 ###
def remove(n0)
return if n0.next.nil?
# n0 -> remove_node -> n1
remove_node = n0.next
n1 = remove_node.next
n0.next = n1
end
```
=== "Zig"
```zig title="linked_list.zig"
@@ -945,6 +971,20 @@ It's important to note that even though node `P` continues to point to `n1` afte
}
```
=== "Ruby"
```ruby title="linked_list.rb"
### 访问链表中索引为 index 的节点 ###
def access(head, index)
for i in 0...index
return nil if head.nil?
head = head.next
end
head
end
```
=== "Zig"
```zig title="linked_list.zig"
@@ -1164,6 +1204,22 @@ Traverse the linked list to locate a node whose value matches `target`, and then
}
```
=== "Ruby"
```ruby title="linked_list.rb"
### 在链表中查找值为 target 的首个节点 ###
def find(head, target)
index = 0
while head
return index if head.val == target
head = head.next
index += 1
end
-1
end
```
=== "Zig"
```zig title="linked_list.zig"

View File

@@ -2141,6 +2141,100 @@ To enhance our understanding of how lists work, we will attempt to implement a s
}
```
=== "Ruby"
```ruby title="my_list.rb"
### 列表类 ###
class MyList
attr_reader :size # 获取列表长度(当前元素数量)
attr_reader :capacity # 获取列表容量
### 构造方法 ###
def initialize
@capacity = 10
@size = 0
@extend_ratio = 2
@arr = Array.new capacity
end
### 访问元素 ###
def get(index)
# 索引如果越界,则抛出异常,下同
raise IndexError, "索引越界" if index < 0 || index >= size
@arr[index]
end
### 访问元素 ###
def set(index, num)
raise IndexError, "索引越界" if index < 0 || index >= size
@arr[index] = num
end
### 在尾部添加元素 ###
def add(num)
# 元素数量超出容量时,触发扩容机制
extend_capacity if size == capacity
@arr[size] = num
# 更新元素数量
@size += 1
end
### 在中间插入元素 ###
def insert(index, num)
raise IndexError, "索引越界" if index < 0 || index >= size
# 元素数量超出容量时,触发扩容机制
extend_capacity if size == capacity
# 将索引 index 以及之后的元素都向后移动一位
for j in (size - 1).downto(index)
@arr[j + 1] = @arr[j]
end
@arr[index] = num
# 更新元素数量
@size += 1
end
### 删除元素 ###
def remove(index)
raise IndexError, "索引越界" if index < 0 || index >= size
num = @arr[index]
# 将将索引 index 之后的元素都向前移动一位
for j in index...size
@arr[j] = @arr[j + 1]
end
# 更新元素数量
@size -= 1
# 返回被删除的元素
num
end
### 列表扩容 ###
def extend_capacity
# 新建一个长度为原数组 extend_ratio 倍的新数组,并将原数组复制到新数组
arr = @arr.dup + Array.new(capacity * (@extend_ratio - 1))
# 更新列表容量
@capacity = arr.length
end
### 将列表转换为数组 ###
def to_array
sz = size
# 仅转换有效长度范围内的列表元素
arr = Array.new sz
for i in 0...sz
arr[i] = get i
end
arr
end
end
```
=== "Zig"
```zig title="my_list.zig"

View File

@@ -182,6 +182,12 @@ The following function uses a `for` loop to perform a summation of $1 + 2 + \dot
}
```
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{for_loop}
```
=== "Zig"
```zig title="iteration.zig"
@@ -408,6 +414,12 @@ Below we use a `while` loop to implement the sum $1 + 2 + \dots + n$.
}
```
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{while_loop}
```
=== "Zig"
```zig title="iteration.zig"
@@ -649,6 +661,12 @@ For example, in the following code, the condition variable $i$ is updated twice
}
```
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{while_loop_ii}
```
=== "Zig"
```zig title="iteration.zig"
@@ -883,6 +901,12 @@ We can nest one loop structure within another. Below is an example using `for` l
}
```
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{nested_for_loop}
```
=== "Zig"
```zig title="iteration.zig"
@@ -1112,6 +1136,12 @@ Observe the following code, where simply calling the function `recur(n)` can com
}
```
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{recur}
```
=== "Zig"
```zig title="recursion.zig"
@@ -1318,8 +1348,9 @@ For example, in calculating $1 + 2 + \dots + n$, we can make the result variable
=== "Kotlin"
```kotlin title="recursion.kt"
/* Kotlin tailrec 关键词使函数实现尾递归优化 */
/* 尾递归 */
tailrec fun tailRecur(n: Int, res: Int): Int {
// 添加 tailrec 关键词,以开启尾递归优化
// 终止条件
if (n == 0)
return res
@@ -1328,6 +1359,12 @@ For example, in calculating $1 + 2 + \dots + n$, we can make the result variable
}
```
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{tail_recur}
```
=== "Zig"
```zig title="recursion.zig"
@@ -1554,6 +1591,12 @@ Using the recursive relation, and considering the first two numbers as terminati
}
```
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{fib}
```
=== "Zig"
```zig title="recursion.zig"
@@ -1890,6 +1933,12 @@ Therefore, **we can use an explicit stack to simulate the behavior of the call s
}
```
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{for_loop_recur}
```
=== "Zig"
```zig title="recursion.zig"

View File

@@ -1077,6 +1077,14 @@ Note that memory occupied by initializing variables or calling functions in a lo
}
```
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{function}
[class]{}-[func]{constant}
```
=== "Zig"
```zig title="space_complexity.zig"
@@ -1373,6 +1381,12 @@ Linear order is common in arrays, linked lists, stacks, queues, etc., where the
}
```
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{linear}
```
=== "Zig"
```zig title="space_complexity.zig"
@@ -1549,6 +1563,12 @@ As shown below, this function's recursive depth is $n$, meaning there are $n$ in
}
```
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{linear_recur}
```
=== "Zig"
```zig title="space_complexity.zig"
@@ -1783,6 +1803,12 @@ Quadratic order is common in matrices and graphs, where the number of elements i
}
```
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{quadratic}
```
=== "Zig"
```zig title="space_complexity.zig"
@@ -1972,6 +1998,12 @@ As shown below, the recursive depth of this function is $n$, and in each recursi
}
```
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{quadratic_recur}
```
=== "Zig"
```zig title="space_complexity.zig"
@@ -2164,6 +2196,12 @@ Exponential order is common in binary trees. Observe the below image, a "full bi
}
```
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{build_tree}
```
=== "Zig"
```zig title="space_complexity.zig"

View File

@@ -1140,6 +1140,12 @@ Constant order means the number of operations is independent of the input data s
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{constant}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -1312,6 +1318,12 @@ Linear order indicates the number of operations grows linearly with the input da
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{linear}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -1499,6 +1511,12 @@ Operations like array traversal and linked list traversal have a time complexity
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{array_traversal}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -1713,6 +1731,12 @@ Quadratic order means the number of operations grows quadratically with the inpu
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{quadratic}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -2013,6 +2037,12 @@ For instance, in bubble sort, the outer loop runs $n - 1$ times, and the inner l
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{bubble_sort}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -2269,6 +2299,12 @@ The following image and code simulate the cell division process, with a time com
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{exponential}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -2432,6 +2468,12 @@ In practice, exponential order often appears in recursive functions. For example
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{exp_recur}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -2623,6 +2665,12 @@ The following image and code simulate the "halving each round" process, with a t
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{logarithmic}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -2780,6 +2828,12 @@ Like exponential order, logarithmic order also frequently appears in recursive f
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{log_recur}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -2988,6 +3042,12 @@ Linear-logarithmic order often appears in nested loops, with the complexities of
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{linear_log_recur}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -3214,6 +3274,12 @@ Factorials are typically implemented using recursion. As shown in the image and
}
```
=== "Ruby"
```ruby title="time_complexity.rb"
[class]{}-[func]{factorial_recur}
```
=== "Zig"
```zig title="time_complexity.zig"
@@ -3603,6 +3669,14 @@ The "worst-case time complexity" corresponds to the asymptotic upper bound, deno
}
```
=== "Ruby"
```ruby title="worst_best_time_complexity.rb"
[class]{}-[func]{random_numbers}
[class]{}-[func]{find_one}
```
=== "Zig"
```zig title="worst_best_time_complexity.zig"

View File

@@ -594,6 +594,18 @@ The design of hash algorithms is a complex issue that requires consideration of
}
```
=== "Ruby"
```ruby title="simple_hash.rb"
[class]{}-[func]{add_hash}
[class]{}-[func]{mul_hash}
[class]{}-[func]{xor_hash}
[class]{}-[func]{rot_hash}
```
=== "Zig"
```zig title="simple_hash.zig"

View File

@@ -1426,6 +1426,12 @@ The code below provides a simple implementation of a separate chaining hash tabl
}
```
=== "Ruby"
```ruby title="hash_map_chaining.rb"
[class]{HashMapChaining}-[func]{}
```
=== "Zig"
```zig title="hash_map_chaining.zig"
@@ -3072,6 +3078,12 @@ The code below implements an open addressing (linear probing) hash table with la
}
```
=== "Ruby"
```ruby title="hash_map_open_addressing.rb"
[class]{HashMapOpenAddressing}-[func]{}
```
=== "Zig"
```zig title="hash_map_open_addressing.zig"

View File

@@ -1697,6 +1697,14 @@ The following code implements a simple hash table. Here, we encapsulate `key` an
}
```
=== "Ruby"
```ruby title="array_hash_map.rb"
[class]{Pair}-[func]{}
[class]{ArrayHashMap}-[func]{}
```
=== "Zig"
```zig title="array_hash_map.zig"

View File

@@ -1968,6 +1968,14 @@ The implementation code is as follows:
}
```
=== "Ruby"
```ruby title="linkedlist_deque.rb"
[class]{ListNode}-[func]{}
[class]{LinkedListDeque}-[func]{}
```
=== "Zig"
```zig title="linkedlist_deque.zig"
@@ -2634,7 +2642,7 @@ The implementation only needs to add methods for "front enqueue" and "rear deque
}
// 计算队尾指针,指向队尾索引 + 1
rear := q.index(q.front + q.queSize)
// 将 num 添加至队
// 将 num 添加至队
q.nums[rear] = num
q.queSize++
}
@@ -3450,6 +3458,12 @@ The implementation only needs to add methods for "front enqueue" and "rear deque
}
```
=== "Ruby"
```ruby title="array_deque.rb"
[class]{ArrayDeque}-[func]{}
```
=== "Zig"
```zig title="array_deque.zig"

View File

@@ -1196,6 +1196,12 @@ Below is the code for implementing a queue using a linked list:
}
```
=== "Ruby"
```ruby title="linkedlist_queue.rb"
[class]{LinkedListQueue}-[func]{}
```
=== "Zig"
```zig title="linkedlist_queue.zig"
@@ -2176,6 +2182,12 @@ In a circular array, `front` or `rear` needs to loop back to the start of the ar
}
```
=== "Ruby"
```ruby title="array_queue.rb"
[class]{ArrayQueue}-[func]{}
```
=== "Zig"
```zig title="array_queue.zig"

View File

@@ -1068,6 +1068,12 @@ Below is an example code for implementing a stack based on a linked list:
}
```
=== "Ruby"
```ruby title="linkedlist_stack.rb"
[class]{LinkedListStack}-[func]{}
```
=== "Zig"
```zig title="linkedlist_stack.zig"
@@ -1621,10 +1627,7 @@ Since the elements to be pushed onto the stack may continuously increase, we can
/* 出栈 */
fn pop(&mut self) -> Option<T> {
match self.stack.pop() {
Some(num) => Some(num),
None => None,
}
self.stack.pop()
}
/* 访问栈顶元素 */
@@ -1745,6 +1748,12 @@ Since the elements to be pushed onto the stack may continuously increase, we can
}
```
=== "Ruby"
```ruby title="array_stack.rb"
[class]{ArrayStack}-[func]{}
```
=== "Zig"
```zig title="array_stack.zig"