Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.