public
Created

  • Download Gist
choose.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#!/usr/bin/env ruby
 
require 'set'
 
class MealFinder
def initialize(file, *items)
@items = items
 
read_data(file)
 
unservable_items = items-@menus.keys
unless unservable_items.empty?
raise ArgumentError, "No restaurant has #{unservable_items}"
end
 
filter_restaurents_for(items)
 
if @restaurants.empty?
raise ArgumentError, "There's no restaurant serving all requested items"
end
 
@prices = calculate_prices(items)
end
 
def cheapest
@prices.first.join(", ")
end
private
def read_data(file)
@menus = {}
@restaurants = Set.new
 
open(file) do |file|
file.each_line do |line|
line.strip!
restaurant, price, menu_item = line.split(/\s*,\s*/)
@menus[menu_item] ||= {}
@menus[menu_item][restaurant] = price.to_f
@restaurants << restaurant
end
end
end
def filter_restaurents_for(items)
@restaurants.select! do |restaurant|
items.all? do |item|
@menus.has_key?(item) && @menus[item].keys.include?(restaurant)
end
end
end
 
def calculate_prices(items)
prices = @restaurants.map do |restaurant|
[restaurant, items.map { |item| @menus[item][restaurant] }.reduce(:+)]
end
 
prices.sort_by! { |pair| pair.last }
prices
end
end
 
 
begin
puts MealFinder.new(*ARGV).cheapest
rescue ArgumentError => e
puts 'nil'
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.