Files
hello-algo/ru/codes/ruby/chapter_dynamic_programming/unbounded_knapsack.rb
T
Yudong JinandClaude Opus 5.5 083dfdc7bc Fix code block headers that pulled in the previous function (#2031)
When the header comment above a cited function did not match the extractor's
format, the extractor kept scanning upward and the book showed the end of the
previous function too. Fix those comments in all editions:

- ruby min_cost_climbing_stairs_dp.rb: `# ...` -> `### ... ###` (all editions);
- ruby unbounded_knapsack.rb: `### ... ##3` -> `### ... ###` (zh, ja, ko, ru);
- c top_k.c: `// ...` above topKHeap -> `/* ... */` (all editions);
- ru Ruby: restore the `###` prefix written as `# ##` on 25 lines in 12 files,
  following the Chinese original line by line.

Also normalize whitespace-only lines inside the code tabs of space_complexity.md
and suggestions.md (30 lines per edition) to empty lines; the built HTML of those
pages is unchanged. zh-hant is regenerated by OpenCC.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 22:48:52 +08:00

62 lines
2.2 KiB
Ruby

=begin
File: unbounded_knapsack.rb
Created Time: 2024-05-29
Author: Xuan Khoa Tu Nguyen ([email protected])
=end
### Полный рюкзак: динамическое программирование ###
def unbounded_knapsack_dp(wgt, val, cap)
n = wgt.length
# Инициализация таблицы dp
dp = Array.new(n + 1) { Array.new(cap + 1, 0) }
# Переход состояний
for i in 1...(n + 1)
for c in 1...(cap + 1)
if wgt[i - 1] > c
# Если вместимость рюкзака превышена, предмет i не выбирать
dp[i][c] = dp[i - 1][c]
else
# Большее из двух решений: не брать или взять предмет i
dp[i][c] = [dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]].max
end
end
end
dp[n][cap]
end
### Полный рюкзак: динамическое программирование с оптимизацией памяти ###
def unbounded_knapsack_dp_comp(wgt, val, cap)
n = wgt.length
# Инициализация таблицы dp
dp = Array.new(cap + 1, 0)
# Переход состояний
for i in 1...(n + 1)
# Прямой обход
for c in 1...(cap + 1)
if wgt[i -1] > c
# Если вместимость рюкзака превышена, предмет i не выбирать
dp[c] = dp[c]
else
# Большее из двух решений: не брать или взять предмет i
dp[c] = [dp[c], dp[c - wgt[i - 1]] + val[i - 1]].max
end
end
end
dp[cap]
end
### Driver Code ###
if __FILE__ == $0
wgt = [1, 2, 3]
val = [5, 11, 15]
cap = 4
# Динамическое программирование
res = unbounded_knapsack_dp(wgt, val, cap)
puts "Максимальная стоимость предметов без превышения вместимости рюкзака = #{res}"
# Динамическое программирование с оптимизацией памяти
res = unbounded_knapsack_dp_comp(wgt, val, cap)
puts "Максимальная стоимость предметов без превышения вместимости рюкзака = #{res}"
end