Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

NP Problem Solution

Taken from hoodwink.d on http://xkcd.com/c287.html

   1  
   2  items = ["Mixed Fruit", "French Fries", "Side Salad", "Hot Wings", "Mozzarella Sticks", "Sampler Plate"]
   3  prices = [2.15, 2.75, 3.35, 3.55, 4.20, 5.80]
   4  
   5  solution = []
   6  sum = 0
   7  loop do
   8      break if sum == 15.05
   9      if sum > 15.05
  10          solution = []
  11          sum = 0
  12          next
  13      else
  14          choice = rand prices.length
  15          sum += prices[choice]
  16          solution << items[choice]
  17      end
  18  end
  19  
  20  p "A solution is: #{solution.inspect}" 
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS