Knapsack problem/Continuous: Difference between revisions

→‎{{header|Haskell}}: hlint, hindent, minor tidying
(Added Kotlin)
(→‎{{header|Haskell}}: hlint, hindent, minor tidying)
Line 1,267:
We use a greedy algorithm.
 
<lang haskell>import ControlData.MonadList (sortBy)
import Data.List (sortBy)
import Data.Ord (comparing)
import DataText.ListPrintf (sortByprintf)
import Control.Monad (forM_)
import Data.Ratio (numerator, denominator)
import Text.Printf
 
maxWgt :: Rational
maxWgt = 15
 
data Bounty = Bounty
{ itemName :: String,
, itemVal, itemWgt :: Rational}
}
 
items =:: [Bounty]
items =
[Bounty "beef" 36 3.8,
[ Bounty "porkbeef" 36 43 53.4,8
, Bounty "hampork" 43 90 35.6,4
, Bounty "greavesham" 90 45 23.4,6
, Bounty "flitchgreaves" 45 30 2.4.0,
, Bounty "brawnflitch" 30 56 24.5,0
, Bounty "weltbrawn" 56 67 32.7,5
, Bounty "salamiwelt" 95 67 3.0,7
, Bounty "sausagesalami" 95 98 53.9]0
, [Bounty "beefsausage" 98 36 35.8,9
]
 
solution :: [(Rational, Bounty)]
solution = g maxWgt $ sortBy (flip $ comparing f) items
where
where g room (b@(Bounty _ _ w) : bs) = if w < room
g thenroom (w, b)@(Bounty :_ g (room -_ w):bs) bs=
if w < else [(room, b)]
fthen (Bounty _ v w, b) =: vg /(room - w) bs
else [(room, b)]
where g roomf (b@(Bounty _ _v w) := bs)v = if/ w < room
 
main :: IO ()
main = do
forM_ solution $ \(w, b) -> printf "%s kg of %s\n" (mixedNum w) (itemName b)
(printf "%sTotal kg ofvalue: %s\n" (. mixedNum w. sum) (itemName$ b)f <$> solution
where
printf "Total value: %s\n" $ mixedNum $ sum $ map f solution
where f (w, Bounty _ v wtot) = v * (w / wtot)
mixedNum q = if b == 0
if b == then show a0
then show a
else printf "%d %d/%d" a (numerator b) (denominator b)
else printf where"%d %d/%d" a =(numerator b) floor(denominator qb)
where
b = q - toEnum a</lang>
a = floor q
b = q - toEnum a</lang>
{{Out}}
<pre>3 kg of salami
3 3/5 kg of ham
2 1/2 kg of brawn
2 2/5 kg of greaves
3 1/2 kg of welt
Total value: 349 14/37</pre>
 
Or similar to above (but more succinct):
9,655

edits