From: James Edward Gray II Date: 2007-07-16T01:44:59+09:00 Subject: Re: xkcd and ugly code On Jul 15, 2007, at 3:08 AM, Sharon Phillips wrote: > I read this xkcd strip the other day (http://www.xkcd.com/ > c287.html) and, of course, had to solve it. Fun problem. Thanks for sharing. > There has to be a 'ruby way' to do this. Any suggestions? Here's what I solved it with: #!/usr/bin/env ruby -wKU APPETIZERS = { "Mixed Fruit" => 215, "French Fries" => 275, "Side Salad" => 335, "Hot Wings" => 355, "Mozzarella Sticks" => 420, "Sampler Plate" => 580 } TOTAL_PRICE = 1505 MAX_COUNT = TOTAL_PRICE / APPETIZERS.values.min orders = Hash.new { |all, total| all[total] = Array.new } orders[0] << Array.new APPETIZERS.each do |name, price| orders.to_a.each do |total, items| 1.upto(MAX_COUNT) do |count| cost = total + price * count break if cost > TOTAL_PRICE orders[cost] += items.map { |order| order + [name] * count } end end end puts "Orders costing $15.05:" orders[1505].each do |order| puts( order.uniq.sort.map do |item| " #{item} * #{order.select { |i| i == item }.size}" end ) puts end __END__ James Edward Gray II