I'm having trouble trying to understand how to use recursion with this problem. I'm using Ruby to solve it because that's the only language I know so far!
You have some hash of firms that own other firms:
@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 }
For example ['A','B'] => 0.5 means that firm 'A' owns 0.5 (50%) of 'B'
The question is to define a method that allows you to determine how much of a firm a particular firm owns (directly and indirectly) through owning other firms. What I have determined so far:
def portfolio(entity)
portfolio = []
@hsh.keys.each do |relationship|
portfolio << relationship.last if relationship.first == entity
end
portfolio
end
This returns an array of the firms that a firm directly owns. Now, here is what I'm thinking what the total_ownership method will look like.
def total_ownership(entity, security)
portfolio(entity).inject() do |sum, company|
sum *= @hsh[[entity,company]]
total_ownership(company,security)
end
end
For the sake of this example let's assume we are looking for total_ownership('A','E')
Obviously, this doesn't work. What I can't really figure out is how to "store" the values of each recursive level and how to set the base case correctly. If you can't help me with it in Ruby, I don't mind pseudo-code as well.