mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-29 03:17:13 +00:00
build
This commit is contained in:
@@ -496,9 +496,39 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="fractional_knapsack.rb"
|
||||
[class]{Item}-[func]{}
|
||||
### 物品 ###
|
||||
class Item
|
||||
attr_accessor :w # 物品重量
|
||||
attr_accessor :v # 物品價值
|
||||
|
||||
[class]{}-[func]{fractional_knapsack}
|
||||
def initialize(w, v)
|
||||
@w = w
|
||||
@v = v
|
||||
end
|
||||
end
|
||||
|
||||
### 分數背包:貪婪 ###
|
||||
def fractional_knapsack(wgt, val, cap)
|
||||
# 建立物品串列,包含兩個屬性:重量,價值
|
||||
items = wgt.each_with_index.map { |w, i| Item.new(w, val[i]) }
|
||||
# 按照單位價值 item.v / item.w 從高到低進行排序
|
||||
items.sort! { |a, b| (b.v.to_f / b.w) <=> (a.v.to_f / a.w) }
|
||||
# 迴圈貪婪選擇
|
||||
res = 0
|
||||
for item in items
|
||||
if item.w <= cap
|
||||
# 若剩餘容量充足,則將當前物品整個裝進背包
|
||||
res += item.v
|
||||
cap -= item.w
|
||||
else
|
||||
# 若剩餘容量不足,則將當前物品的一部分裝進背包
|
||||
res += (item.v.to_f / item.w) * cap
|
||||
# 已無剩餘容量,因此跳出迴圈
|
||||
break
|
||||
end
|
||||
end
|
||||
res
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -310,7 +310,24 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="coin_change_greedy.rb"
|
||||
[class]{}-[func]{coin_change_greedy}
|
||||
### 零錢兌換:貪婪 ###
|
||||
def coin_change_greedy(coins, amt)
|
||||
# 假設 coins 串列有序
|
||||
i = coins.length - 1
|
||||
count = 0
|
||||
# 迴圈進行貪婪選擇,直到無剩餘金額
|
||||
while amt > 0
|
||||
# 找到小於且最接近剩餘金額的硬幣
|
||||
while i > 0 && coins[i] > amt
|
||||
i -= 1
|
||||
end
|
||||
# 選擇 coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
end
|
||||
# 若未找到可行方案, 則返回 -1
|
||||
amt == 0 ? count : -1
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -397,7 +397,28 @@ $$
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="max_capacity.rb"
|
||||
[class]{}-[func]{max_capacity}
|
||||
### 最大容量:貪婪 ###
|
||||
def max_capacity(ht)
|
||||
# 初始化 i, j,使其分列陣列兩端
|
||||
i, j = 0, ht.length - 1
|
||||
# 初始最大容量為 0
|
||||
res = 0
|
||||
|
||||
# 迴圈貪婪選擇,直至兩板相遇
|
||||
while i < j
|
||||
# 更新最大容量
|
||||
cap = [ht[i], ht[j]].min * (j - i)
|
||||
res = [res, cap].max
|
||||
# 向內移動短板
|
||||
if ht[i] < ht[j]
|
||||
i += 1
|
||||
else
|
||||
j -= 1
|
||||
end
|
||||
end
|
||||
|
||||
res
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -371,7 +371,19 @@ $$
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="max_product_cutting.rb"
|
||||
[class]{}-[func]{max_product_cutting}
|
||||
### 最大切分乘積:貪婪 ###
|
||||
def max_product_cutting(n)
|
||||
# 當 n <= 3 時,必須切分出一個 1
|
||||
return 1 * (n - 1) if n <= 3
|
||||
# 貪婪地切分出 3 ,a 為 3 的個數,b 為餘數
|
||||
a, b = n / 3, n % 3
|
||||
# 當餘數為 1 時,將一對 1 * 3 轉化為 2 * 2
|
||||
return (3.pow(a - 1) * 2 * 2).to_i if b == 1
|
||||
# 當餘數為 2 時,不做處理
|
||||
return (3.pow(a) * 2).to_i if b == 2
|
||||
# 當餘數為 0 時,不做處理
|
||||
3.pow(a).to_i
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user