5

我在尝试理解如何使用递归来解决这个问题时遇到了麻烦。我正在使用 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 中帮助我,我也不介意伪代码。

4

2 回答 2

2

嗯,在我看来应该是

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
于 2012-04-15T23:00:03.793 回答
1
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
于 2012-04-15T23:04:42.017 回答