Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created July 31, 2012 16:24
Show Gist options
  • Select an option

  • Save practicingruby/3218237 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/3218237 to your computer and use it in GitHub Desktop.
require "bigdecimal"
class Node
def initialize(name)
@name = name
@children = []
end
attr_reader :name
def <<(child)
@children << child
end
def path(destination)
return [] if @children.empty?
return [[name, destination]] if @children.any? { |c| c.name == destination }
@children.each do |child|
path = [[name, child.name]] + child.path(destination)
return path if path[-1][-1] == destination
end
end
end
rates = [ {:from => "AUD", :to => "CAD", :rate => BigDecimal("1.0079") },
{:from => "AUD", :to => "EUR", :rate => BigDecimal("0.7439") },
{:from => "CAD", :to => "AUD", :rate => BigDecimal("0.9921") },
{:from => "CAD", :to => "USD", :rate => BigDecimal("1.0090") },
{:from => "USD", :to => "CAD", :rate => BigDecimal("0.9911") } ]
nodes = Hash.new { |h,k| h[k] = Node.new(k) }
rates.each do |rate|
nodes[rate[:from]] << nodes[rate[:to]]
end
from = "CAD"
to = "EUR"
path = nodes[from].path(to)
p path
conversion_rate = path.reduce(1) { |s,(from, to)|
s * rates.find { |r| r[:from] == from && r[:to] == to }[:rate]
}
p conversion_rate.to_f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment