-
-
Save srinivt/01e80391715bea47d352 to your computer and use it in GitHub Desktop.
P1 of Puzzlenode
This file contains 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
#!/usr/bin/ruby | |
require 'rubygems' | |
require 'hpricot' | |
require 'yaml' | |
require 'csv' | |
require 'bigdecimal' | |
$Conversion = Hash.new | |
$Transactions = Hash.new | |
$One = BigDecimal.new('1') | |
def read_rates(file) | |
xml = File.read(file) | |
doc, rates = Hpricot::XML(xml), [] | |
(doc/:rate).each do |p| | |
from = (p/:from).inner_text | |
to = (p/:to).inner_text | |
conv = (p/:conversion).inner_text | |
$Conversion[to] ||= Hash[ to, $One ] | |
$Conversion[from] ||= Hash[ from, $One ] | |
$Conversion[to][from] = BigDecimal.new(conv) | |
$Conversion[from][to] = $One / $Conversion[to][from] | |
end | |
build_full_conversion_table | |
end | |
# Build conversion table using BFS | |
def build_full_conversion_table() | |
from = "USD" | |
queue = $Conversion[from].keys - [from] | |
seen = [] | |
until queue.empty? | |
curr = queue.shift | |
seen << curr | |
$Conversion[curr].keys.each do |k| | |
unless $Conversion[from][k] | |
$Conversion[from][k] = $Conversion[from][curr] * $Conversion[curr][k] | |
queue << k | |
end | |
end | |
end | |
$Conversion | |
end | |
def convert(amount, from, to = "USD") | |
c = amount * $Conversion[to][from] | |
return roundIt(c) | |
end | |
def roundIt(c) | |
c.round(2, BigDecimal::ROUND_HALF_EVEN) | |
end | |
def read_transactions(file) | |
CSV.foreach(file) do |r| | |
store, sku, amount = r | |
next if store == 'store' # skip header | |
amount, currency = amount.split(" ") | |
$Transactions[sku] ||= BigDecimal.new('0') | |
$Transactions[sku] += convert(BigDecimal.new(amount), currency) | |
end | |
end | |
def assert_eq(a, b) | |
raise "Assert failed! #{a} != #{b}" unless a == b | |
end | |
read_rates("RATES.xml") | |
read_transactions("TRANS.csv") | |
puts ($Transactions["DM1182"]).to_s('F') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment