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

NP Problem Solution (See related posts)

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

items = ["Mixed Fruit", "French Fries", "Side Salad", "Hot Wings", "Mozzarella Sticks", "Sampler Plate"]
prices = [2.15, 2.75, 3.35, 3.55, 4.20, 5.80]

solution = []
sum = 0
loop do
    break if sum == 15.05
    if sum > 15.05
        solution = []
        sum = 0
        next
    else
        choice = rand prices.length
        sum += prices[choice]
        solution << items[choice]
    end
end

p "A solution is: #{solution.inspect}" 

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts