Skip to content

Instantly share code, notes, and snippets.

@pencilcheck
Created September 5, 2011 19:56
Show Gist options
  • Save pencilcheck/1195780 to your computer and use it in GitHub Desktop.
Save pencilcheck/1195780 to your computer and use it in GitHub Desktop.
debug = false
inFile = File.open("inFile", "r")
outFile = File.open("outFile", "w")
def satisfied(customer, flavors)
flavors.each_with_index.any? {|el,index| customer.has_key?(index) ? customer[index] == el : false}
end
def all_be_satisfied(customers, flavors)
customers.all? {|customer| satisfied customer, flavors}
end
def has_malt(customer)
customer.has_value?(1)
end
def malt_flavor(customer)
customer.key(1)-1 # already been checked by has_malt, shifting 1 for correct conversion
end
def satisfy_only_malt(flavor, flavors)
flavors[flavor] = 1
end
# Case loop
for i in (1..inFile.gets.to_i)
# flavors
num_flavors = inFile.gets.to_i
# customers
num_customers = inFile.gets.to_i
flavors = Array.new(num_flavors, 0) # all unmalted
needs_of_customers = []
num_customers.times do |i|
line = inFile.gets.split[1..-1].map {|x| x.to_i}
customer = Hash[*line]
needs_of_customers << customer
end
result = ""
while not all_be_satisfied needs_of_customers, flavors && result != "IMPOSSIBLE"
needs_of_customers.each do |customer|
if not satisfied(customer, flavors) && has_malt(customer)
satisfy_only_malt(malt_flavor(customer), flavors)
break
elsif (not satisfied(customer, flavors)) && (not has_malt(customer))
result = "IMPOSSIBLE"
break
end
end
end
if result != "IMPOSSIBLE"
result = flavors.join(" ")
end
output = "Case ##{i}: #{result} \n"
puts output if debug
outFile.write(output)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment