This commit is contained in:
krahets
2024-04-03 21:48:54 +08:00
parent d5a7899137
commit 0a9daa8b9f
11 changed files with 685 additions and 97 deletions

View File

@ -185,7 +185,17 @@ comments: true
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{for_loop}
### for 循环 ###
def for_loop(n)
res = 0
# 循环求和 1, 2, ..., n-1, n
for i in 1..n
res += i
end
res
end
```
=== "Zig"
@ -417,7 +427,19 @@ comments: true
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{while_loop}
### while 循环 ###
def while_loop(n)
res = 0
i = 1 # 初始化条件变量
# 循环求和 1, 2, ..., n-1, n
while i <= n
res += i
i += 1 # 更新条件变量
end
res
end
```
=== "Zig"
@ -664,7 +686,21 @@ comments: true
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{while_loop_ii}
### while 循环(两次更新)###
def while_loop_ii(n)
res = 0
i = 1 # 初始化条件变量
# 循环求和 1, 4, 10, ...
while i <= n
res += i
# 更新条件变量
i += 1
i *= 2
end
res
end
```
=== "Zig"
@ -904,7 +940,20 @@ comments: true
=== "Ruby"
```ruby title="iteration.rb"
[class]{}-[func]{nested_for_loop}
### 双层 for 循环 ###
def nested_for_loop(n)
res = ""
# 循环 i = 1, 2, ..., n-1, n
for i in 1..n
# 循环 j = 1, 2, ..., n-1, n
for j in 1..n
res += "(#{i}, #{j}), "
end
end
res
end
```
=== "Zig"
@ -1139,7 +1188,15 @@ comments: true
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{recur}
### 递归 ###
def recur(n)
# 终止条件
return 1 if n == 1
# 递:递归调用
res = recur(n - 1)
# 归:返回结果
n + res
end
```
=== "Zig"
@ -1362,7 +1419,13 @@ comments: true
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{tail_recur}
### 尾递归 ###
def tail_recur(n, res)
# 终止条件
return res if n == 0
# 尾递归调用
tail_recur(n - 1, res + n)
end
```
=== "Zig"
@ -1594,7 +1657,15 @@ comments: true
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{fib}
### 斐波那契数列:递归 ###
def fib(n)
# 终止条件 f(1) = 0, f(2) = 1
return n - 1 if n == 1 || n == 2
# 递归调用 f(n) = f(n-1) + f(n-2)
res = fib(n - 1) + fib(n - 2)
# 返回结果 f(n)
res
end
```
=== "Zig"
@ -1936,7 +2007,25 @@ comments: true
=== "Ruby"
```ruby title="recursion.rb"
[class]{}-[func]{for_loop_recur}
### 使用迭代模拟递归 ###
def for_loop_recur(n)
# 使用一个显式的栈来模拟系统调用栈
stack = []
res = 0
# 递:递归调用
for i in n.downto(0)
# 通过“入栈操作”模拟“递”
stack << i
end
# 归:返回结果
while !stack.empty?
res += stack.pop
end
# res = 1+2+3+...+n
res
end
```
=== "Zig"