Skip to content

Instantly share code, notes, and snippets.

@ecin
Created April 16, 2011 05:04
Show Gist options
  • Save ecin/922886 to your computer and use it in GitHub Desktop.
Save ecin/922886 to your computer and use it in GitHub Desktop.
Going through Google Code Jam problem sets...
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