Created
April 16, 2011 05:04
-
-
Save ecin/922886 to your computer and use it in GitHub Desktop.
Going through Google Code Jam problem sets...
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
module Reader | |
def read(lines_per_problem = 1) | |
Enumerator.new do |yielder| | |
gets.chomp.to_i.times do | |
yielder.yield *[Array.new(lines_per_problem) { gets.chomp }] | |
end | |
end | |
end | |
end | |
class StoreCredit | |
extend Reader | |
def self.start | |
solutions = [] | |
read(3).each_with_index do |problem, index| | |
solutions << "Case ##{index + 1}: #{solve(problem)}" | |
end | |
puts solutions | |
end | |
private | |
def self.solve(problem) | |
credit = problem[0].to_i | |
quantity = problem[1].to_i | |
items = problem[2].split.map(&:to_i) | |
inventory = {} | |
items.each_with_index do |item, index| | |
if inventory[item].nil? | |
inventory[item] = index | |
else | |
inventory[-item] = index | |
end | |
end | |
items.each do |item| | |
complement = credit - item | |
next if complement < 0 | |
complement *= -1 if complement == item | |
if inventory[complement] | |
pair = [inventory[item] + 1, inventory[complement] + 1].sort | |
return "#{pair.min} #{pair.max}" | |
end | |
end | |
end | |
end | |
StoreCredit.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment