Skip to content

Instantly share code, notes, and snippets.

@naush
Last active December 12, 2015 08:49
Show Gist options
  • Save naush/4746770 to your computer and use it in GitHub Desktop.
Save naush/4746770 to your computer and use it in GitHub Desktop.
# http://xkcd.com/287/
def order(menu, amount, items)
return [] if amount < 0
return [items] if amount == 0
menu.inject([]) do |meals, (item, price)|
meals += order(menu, amount - price, items + [item])
end
end
menu = {:mixed_fruit => 215, :french_fries => 275, :side_salad => 335, :hot_wings => 355, :mozzarella_sticks => 420, :sampler_plate => 580}
order(menu, 1505, []).map(&:sort).uniq
@mikelikesbikes
Copy link

This doesn't identify all possible menus.

e.g.

menu = {
  :mixed_fruit => 2.15,
  :french_fries => 2.75,
  :side_salad => 3.35,
  :hot_wings => 3.55,
  :mozzarella_sticks => 4.20,
  :sampler_plate => 5.80,
  :water => 1.00
}

should return 8 possible choices for orders:

3 x french fries, 1 x sampler plate, 1 x water
1 x mixed fruit, 2 x hot wings, 1 x sampler plate
1 x mixed fruit, 1 x french fries, 1 x side salad, 1 x sampler plate, 1 x water
2 x mixed fruit, 1 x french fries, 4 x pop
2 x mixed fruit, 1 x french fries, 2 x water, 3 x pop
2 x mixed fruit, 1 x french fries, 4 x water, 2 x pop
2 x mixed fruit, 1 x french fries, 6 x water, 1 x pop
2 x mixed fruit, 1 x french fries, 8 x water

@naush
Copy link
Author

naush commented Feb 9, 2013

I intended it to return on the first match since the original comic didn't specify if he wanted all possible choices. Let me see if I can write a program that identify all choices. Thanks for providing a solution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment