-
-
Save practicingruby/3218237 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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