【问题标题】:Algorithm/Recursion tree challenge算法/递归树挑战
【发布时间】:2012-04-15 22:12:40
【问题描述】:

我很难理解如何使用递归来解决这个问题。我正在使用 Ruby 来解决它,因为这是我迄今为止所知道的唯一语言!

你有一些拥有其他公司的公司:

@hsh = { ['A','B'] => 0.5, ['B','E'] => 0.2, ['A','E'] => 0.2, 
         ['A','C'] => 0.3, ['C','D'] => 0.4, ['D','E'] => 0.2 }

例如['A','B'] => 0.5 表示公司“A”拥有“B”的 0.5 (50%) 问题是定义一种方法,使您可以通过拥有其他公司来确定特定公司(直接和间接)拥有多少公司。到目前为止我已经确定的:

def portfolio(entity)
  portfolio = []
  @hsh.keys.each do |relationship|
    portfolio << relationship.last if relationship.first == entity
  end
  portfolio
end

这将返回公司直接拥有的公司数组。现在,这就是我想的 total_ownership 方法的样子。

def total_ownership(entity, security)
  portfolio(entity).inject() do |sum, company|
    sum *= @hsh[[entity,company]]
    total_ownership(company,security)
  end
end

为了这个例子,假设我们正在寻找total_ownership('A','E')

显然,这是行不通的。我无法真正弄清楚的是如何“存储”每个递归级别的值以及如何正确设置基本情况。如果你不能在 Ruby 中帮助我,我也不介意伪代码。

【问题讨论】:

  • +1 有趣的问题。如果是作业,应该这样标记。
  • 确认一下,total_ownership('A', 'E') 的解是 (0.5 * 0.2) + 0.2 + (0.3 * 0.4 * 0.2)?
  • 不!只是我在考虑递归时想知道如何解决的问题。感谢您的提示

标签: ruby algorithm recursion tree


【解决方案1】:

嗯,我觉得应该是

def total_ownership(entity, security)
  indirect = portfolio(entity).inject(0) do |sum, company|
    share = @hsh[[entity, company]]
    sum + (share || 0) * total_ownership(company,security)
  end
  direct = @hsh[[entity, security]] || 0

  indirect + direct
end

【讨论】:

  • 非常感谢您的帮助;现在更有意义了
  • 现在是奖金挑战。如果 A 公司拥有 B 公司,而 B 公司拥有包括 A 公司的一些股票的投资组合怎么办?你的代码坏了...
【解决方案2】:
def total_ownership(a, b)
  direct_ownership(a, b) + indirect_ownership(a, b)
end

def direct_ownership(a, b)
  @hsh[[a, b]] || 0
end

def indirect_ownership(a, b)
  portfolio(a).map do |portfolio_item|
    @hsh[[a, portfolio_item]] * total_ownership(portfolio_item, b)
  end.inject(&:+) || 0
end

【讨论】:

  • 也感谢您提供的替代方法!
猜你喜欢
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 1970-01-01
  • 2012-11-06
  • 2021-12-10
  • 1970-01-01
相关资源
最近更新 更多