mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
feat: Add Ruby code - chapter "computational complexity" (#1212)
* feat: add ruby code - chapter computational complexity * feat: add ruby code blocks
This commit is contained in:
@ -335,7 +335,30 @@
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
### 类 ###
|
||||
class Node
|
||||
attr_accessor :val # 节点值
|
||||
attr_accessor :next # 指向下一节点的引用
|
||||
|
||||
def initialize(x)
|
||||
@val = x
|
||||
end
|
||||
end
|
||||
|
||||
### 函数 ###
|
||||
def function
|
||||
# 执行某些操作...
|
||||
0
|
||||
end
|
||||
|
||||
### 算法 ###
|
||||
def algorithm(n) # 输入数据
|
||||
a = 0 # 暂存数据(常量)
|
||||
b = 0 # 暂存数据(变量)
|
||||
node = Node.new 0 # 暂存数据(对象)
|
||||
c = function # 栈帧空间(调用函数)
|
||||
a + b + c # 输出数据
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@ -499,7 +522,11 @@
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
|
||||
def algorithm(n)
|
||||
a = 0 # O(1)
|
||||
b = Array.new 10000 # O(1)
|
||||
nums = Array.new n if n > 10 # O(n)
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@ -763,7 +790,21 @@
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
def function
|
||||
# 执行某些操作
|
||||
0
|
||||
end
|
||||
|
||||
### 循环的空间复杂度为 O(1) ###
|
||||
def loop(n)
|
||||
(0...n).each { function }
|
||||
end
|
||||
|
||||
### 递归的空间复杂度为 O(n) ###
|
||||
def recur(n)
|
||||
return if n == 1
|
||||
recur n - 1
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@ -189,7 +189,16 @@
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
|
||||
# 在某运行平台下
|
||||
def algorithm(n)
|
||||
a = 2 # 1 ns
|
||||
a = a + 1 # 1 ns
|
||||
a = a * 2 # 10 ns
|
||||
# 循环 n 次
|
||||
(n...0).each do # 1 ns
|
||||
puts 0 # 5 ns
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@ -474,7 +483,20 @@ $$
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
# 算法 A 的时间复杂度:常数阶
|
||||
def algorithm_A(n)
|
||||
puts 0
|
||||
end
|
||||
|
||||
# 算法 B 的时间复杂度:线性阶
|
||||
def algorithm_B(n)
|
||||
(0...n).each { puts 0 }
|
||||
end
|
||||
|
||||
# 算法 C 的时间复杂度:常数阶
|
||||
def algorithm_C(n)
|
||||
(0...1_000_000).each { puts 0 }
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@ -688,7 +710,15 @@ $$
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
|
||||
def algorithm(n)
|
||||
a = 1 # +1
|
||||
a = a + 1 # +1
|
||||
a = a * 2 # +1
|
||||
# 循环 n 次
|
||||
(0...n).each do # +1
|
||||
puts 0 # +1
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@ -970,7 +1000,16 @@ $T(n)$ 是一次函数,说明其运行时间的增长趋势是线性的,因
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title=""
|
||||
|
||||
def algorithm(n)
|
||||
a = 1 # +0(技巧 1)
|
||||
a = a + n # +0(技巧 1)
|
||||
# +n(技巧 2)
|
||||
(0...(5 * n + 1)).each do { puts 0 }
|
||||
# +n*n(技巧 3)
|
||||
(0...(2 * n)).each do
|
||||
(0...(n + 1)).each do { puts 0 }
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user