Knapsack problem/Continuous: Difference between revisions

→‎{{header|Haskell}}: hlint, hindent, added output
(→‎{{header|Haskell}}: hlint, hindent, minor tidying)
(→‎{{header|Haskell}}: hlint, hindent, added output)
Line 1,325:
 
Or similar to above (but more succinct):
<lang haskell>import Data.List (sortBy)
import Data.List (sortBy)
import Data.Ord (comparing)
import Text.Printf (printf)
 
-- (name, (value, weight))
items = [("beef", (36, 3.8)),
[ ("porkbeef", (4336, 53.48)),
, ("hampork", (9043, 35.64)),
, ("greavesham", (4590, 23.46)),
, ("flitchgreaves", (3045, 2.4.0)),
, ("brawnflitch", (5630, 24.50)),
, ("weltbrawn", (6756, 32.75)),
, ("salamiwelt", (9567, 3.07)),
, ("sausagesalami", (9895, 53.90))]
, ("sausage", (98, 5.9))
]
 
unitWeight (_, (val, weight)) = (fromIntegral val) / weight
 
solution k = loop k . sortBy (flip $ comparing unitWeight)
where
where loop k ((name, (_, weight)):xs)
| weight <loop k = putStrLn ("Take all the " ++ (name), >>(_, loop (k-weight) ):xs)
| weight < k = putStrLn ("Take all | otherwise = printfthe "Take %.2f++ kgname) of>> the %s\n"loop (k ::- Floatweight) namexs
| otherwise = printf "Take %.2f kg of the %s\n" (k :: Float) name
 
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}}==
9,655

edits