Knapsack problem/Continuous: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: hlint, hindent, minor tidying)
(→‎{{header|Haskell}}: hlint, hindent, added output)
Line 1,325: Line 1,325:


Or similar to above (but more succinct):
Or similar to above (but more succinct):
<lang haskell>
<lang haskell>import Data.List (sortBy)
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Ord (comparing)
import Text.Printf (printf)
import Text.Printf (printf)


-- (name, (value, weight))
-- (name, (value, weight))
items = [("beef", (36, 3.8)),
items =
("pork", (43, 5.4)),
[ ("beef", (36, 3.8))
("ham", (90, 3.6)),
, ("pork", (43, 5.4))
("greaves", (45, 2.4)),
, ("ham", (90, 3.6))
("flitch", (30, 4.0)),
, ("greaves", (45, 2.4))
("brawn", (56, 2.5)),
, ("flitch", (30, 4.0))
("welt", (67, 3.7)),
, ("brawn", (56, 2.5))
("salami", (95, 3.0)),
, ("welt", (67, 3.7))
("sausage", (98, 5.9))]
, ("salami", (95, 3.0))
, ("sausage", (98, 5.9))
]


unitWeight (_, (val, weight)) = (fromIntegral val) / weight
unitWeight (_, (val, weight)) = fromIntegral val / weight


solution k = loop k . sortBy (flip $ comparing unitWeight)
solution k = loop k . sortBy (flip $ comparing unitWeight)
where
where loop k ((name, (_, weight)):xs)
| weight < k = putStrLn ("Take all the " ++ name) >> loop (k-weight) xs
loop k ((name, (_, weight)):xs)
| otherwise = printf "Take %.2f kg of the %s\n" (k :: Float) name
| weight < k = putStrLn ("Take all the " ++ name) >> loop (k - weight) xs
| otherwise = printf "Take %.2f kg of the %s\n" (k :: Float) name


main = solution 15 items
main = solution 15 items</lang>
{{Out}}
</lang>
<pre>Take all the salami
Take all the ham
Take all the brawn
Take all the greaves
Take 3.50 kg of the welt</pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==